pandas groupby 并转换为 json 列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35608208/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 00:45:17  来源:igfitidea点击:

pandas groupby and convert to json list

pythondictionarypandas

提问by Abhishek Thakur

I have a pandas dataframe like the following

我有一个如下所示的Pandas数据框

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

I need to convert the other columns to list of dictionaries based on idx column. so, final result should be:

我需要将其他列转换为基于 idx 列的字典列表。所以,最终结果应该是:

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 like this using groupby in pandas?

是否可以在 Pandas 中使用 groupby 来做这样的事情?

采纳答案by jezrael

You can use groupbyby indexand then applyto_json:

您可以使用groupbybyindex和 then :applyto_json

print df
    f1 f2 f3
idx         
1    a  a  b
1    b  a  c
1    a  b  c
87   e  e  e

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 column idxis not index:

或者如果列idx不是index

print df
   idx f1 f2 f3
0    1  a  a  b
1    1  b  a  c
2    1  a  b  c
3   87  e  e  e

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