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']}
CodePudding user response:
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'))
CodePudding user response:
So, i came up with the same idea of Beny but with a function to store it in a variable :
group_A, group_B, group_C = {},{},{}
def add_to_dict (user_dict,user):
d = df.groupby('user').agg(lambda x : x.values.tolist()).to_dict('index')
return (d[user])
group_A = add_to_dict(group_A,'A')
group_B = add_to_dict(group_B,'B')
group_C = add_to_dict(group_C,'C')