I am trying to build a dictionary based on entity
df = pd.DataFrame({
'entity': ['foo', 'bar', 'baz', 'buzz', 'bar', 'buzz', 'foo', 'foo'],
'value': [4, 3, 2, 1, 9, 8, 7, 4]
})
out = dict(df.groupby('entity'))
But I get the following error
out = dict(df.groupby('entity'))
TypeError: 'str' object is not callable
What’s wrong???
This is my pandas and python version
print(pd.__version__)
print(sys.version)
pandas == 1.5.3
sys == 3.10.9
>Solution :
In old version of pandas need convert groupby
object to iterator
or tuples:
out = dict(iter(df.groupby('entity')))
Or:
out = dict(tuple(df.groupby('entity')))
print (out)
{'bar': entity value
1 bar 3
4 bar 9, 'baz': entity value
2 baz 2, 'buzz': entity value
3 buzz 1
5 buzz 8, 'foo': entity value
0 foo 4
6 foo 7
7 foo 4}
Better explanation by @tdelaney from commnents:
A dict prefers initialization by a "Mapping" to an iterable. I don’t know exactly where a "Mapping" is defined, but the groupby object as a .keys parameter that holds the columns you use to group. In your case, its the string "entity". The dict constructor sees a .keys attribute and tries to call it, assuming its a function that lists the mapping’s keys. But its a string, so boom. had you groupby([‘entity’, ‘value’]), you’d get a ‘list’ object is not callable instead.