Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Covert groups to json after groupby() in Pandas

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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'))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading