简体   繁体   中英

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

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:(

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM