Pandas groupby and convert to json list

I have a dataframe ramp like the following

idx, f1, f2, f3 1, a, a, b 2, b, a, c 3, a, b, c . . . 87 e, e, e 

I need to convert other columns to a dictionary list based on idx column. The final result should be:

 idx, features 1 , [{f1:a, f2:a, f3:b}, {f1:b, f2:a, f3:c}, {f1:a, f2:b, f3:c}] . . . 87, [{f1: e, f2:e, f3:e}] 

Is it possible to do something similar using gangbang in pandas?

+11
source share
1 answer

You can use groupby by index and then apply to_json :

 print df f1 f2 f3 idx 1 aab 1 bac 1 abc 87 eee print df.groupby(level=0).apply(lambda x: x.to_json(orient='records')) 1 [{"f1":"a","f2":"a","f3":"b"},{"f1":"b","f2":"... 87 [{"f1":"e","f2":"e","f3":"e"}] dtype: object 

Or if the idx column is not index :

 print df idx f1 f2 f3 0 1 aab 1 1 bac 2 1 abc 3 87 eee print df.groupby('idx').apply(lambda x: x.to_json(orient='records')) idx 1 [{"idx":1,"f1":"a","f2":"a","f3":"b"},{"idx":1... 87 [{"idx":87,"f1":"e","f2":"e","f3":"e"}] dtype: object 
+10
source

Source: https://habr.com/ru/post/1243773/


All Articles