Skip to content
Advertisement

Is there a way to get the count of every element in lists stored as rows in a data frame?

Hi, I’m using pandas to display and analyze a csv file, some columns were ‘object dtype’ and were displayed as lists, I used ‘literal_eval’ to convert the rows of a column named ‘sdgs’ to lists, my problem is how to use ‘groupby’ or any another way to display the count of every element stored at this lists uniquely, especially since there are many common elements between these lists.

JavaScript

This is a sample of data and my problem is about the last column

This is an example of the elements I want to count

Thank you

Advertisement

Answer

Given this example data:

JavaScript
JavaScript

To get the word count across all the lists in the sdgs column you can concatenate the lists with Series.agg and use collections.Counter:

JavaScript
JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement