1

I have a pandas dataframe like this:

import pandas as pd
foo = pd.DataFrame({'s': ['a','b','a','a'], 'versions':[['1','2'],'2',['1','2'],'2']})

I would like to value_counts() he columns versions by group s

I have tried

foo.groupby('s')['versions'].value_counts()

but i get an error TypeError: unhashable type: 'list', any ideas ?

1 Answer 1

1

You can convert lists/arrays to hashable tuples, but because there are also strings need if-else statement for avoid split strings 100 to tuple (1,0,0):

foo['versions'] = foo['versions'].apply(lambda x: tuple(x) if isinstance(x, list) else (x,))
print (foo)
   s versions
0  a   (1, 2)
1  b     (2,)
2  a   (1, 2)
3  a     (2,)

s = foo.groupby('s')['versions'].value_counts()
print (s)
s  versions
a  (1, 2)      2
   (2,)        1
b  (2,)        1
Name: versions, dtype: int64
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.