Home > OS >  In Python Creating dictionary from the group-by result and making list for the unique elements
In Python Creating dictionary from the group-by result and making list for the unique elements

Time:02-11

I have this dataset:

pd.DataFrame({'pid' : ['12A', '12A', '12A', '10B', '10B', '10B', '10B'],
                'wips' : ['Aa', 'Aa', 'Aa', 'Dd', 'Dd', 'Dd', 'Dd'], 
                'be':['charlie','charlie','charlie','hanami','hanami','hanami','hanami'],
                'rownum':[1,2,3,1,2,3,4]})
   pid wips       be  rownum
0  12A   Aa  charlie       1
1  12A   Aa  charlie       2
2  12A   Aa  charlie       3
3  10B   Dd   hanami       1
4  10B   Dd   hanami       2
5  10B   Dd   hanami       3
6  10B   Dd   hanami       4

I need to convert this df into a dictionary, like this -

[{'pid':'12A','wips':'Aa','be':'charlie','rownum':[1,2,3]},{'pid':'10B','wips':'Dd','be':'hanami','rownum':[1,2,3,4]}]

Please help me with a piece of code to get this result. Thank you.

CodePudding user response:

Group, apply list, turn into dict.

result = df.groupby(['pid', 'wips', 'be'])['rownum'].apply(list).reset_index().to_dict(orient='records')

CodePudding user response:

we can first groupby with list then to_dict

out = df.groupby(['pid','wips','be'])['rownum'].agg(list).reset_index().to_dict('records')
Out[16]: 
[{'pid': '10B', 'wips': 'Dd', 'be': 'hanami', 'rownum': [1, 2, 3, 4]},
 {'pid': '12A', 'wips': 'Aa', 'be': 'charlie', 'rownum': [1, 2, 3]}]
  • Related