I want to convert groups to dict after groupby function in pandas.
This is the data sample:
user val1 val2
0 A 1 one
1 A 3 one
2 A 2 one
3 B 2 two
4 B 2 three
5 C 3 one
After
df = df.groupby('user')
I want to get result something like this:
group_A = {'val1':[1,3,2], 'val2':['one', 'one', 'one']}
group_B = {'val1':[2,2], 'val2':['two', 'three']}
group_C = {'val1':[3], 'val2':['one']}
So for example:
for group in df:
print(group)
Result:
{'val1':[1,3,2], 'val2':['one', 'one', 'one']}
{'val1':[2,2], 'val2':['two', 'three']}
{'val1':[3], 'val2':['one']}
>Solution :
So you can do
df.groupby('user').agg(lambda x : x.values.tolist()).to_dict('records')
Out[165]:
[{'val1': [1, 3, 2], 'val2': ['one', 'one', 'one']},
{'val1': [2, 2], 'val2': ['two', 'three']},
{'val1': [3], 'val2': ['one']}]
Or
d = df.groupby('user').agg(lambda x : x.values.tolist()).to_dict('index')
d['A']
If do need for loop
for x, y in df.groupby('user'):
print(y.drop(['user'],1).to_dict('list'))