How to count occurrence of each element in pandas series of lists?

Viewed 275

I'm a newbie and quite stuck with my python project. I have a pandas series containing lists, like this:

>> df.head()
>> column1       
   ['A', 'B']
   ['A']
   ['A', 'C']
   ['A', 'B', 'C']
   ['B']

The desired output should be like this:

>> column1   column2
    'A'         4
    'B'         3
    'C'         2

It doesn't matter whether column1 is a string or a list with one element.

I tried these:

df.groupby('column1').count()

df['column1'].value_counts()

But both gave me:

TypeError: unhashable type: 'list'

Also tried:

df.groupby('column1')

But it does not display results.

Tried solutions here (How to print a groupby object) but none worked :(

2 Answers

Try:

df1['column1'].explode().groupby().count()

or

df1.explode('column1').groupby('column1').count()
df.explode('Column1').groupby('Column1').size().reset_index(name='Column2')

Output:

  Column1  Column2
0       A        4
1       B        3
2       C        2
Related