Reputation: 23
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 :(
Upvotes: 2
Views: 1084
Reputation: 2161
df.explode('Column1').groupby('Column1').size().reset_index(name='Column2')
Output:
Column1 Column2
0 A 4
1 B 3
2 C 2
Upvotes: 2
Reputation:
Try:
df1['column1'].explode().groupby().count()
or
df1.explode('column1').groupby('column1').count()
Upvotes: 2