这是我收到的数据框df
一些预处理:
name type range time number
0 XXXX 11111 1-120 [1-120, 261.05] [1-120, 23229]
1 XXXX 11111 121-240 [121-240, 277.79] [121-240, 6382]
2 XXXX 11111 241-360 [241-360, 269.64] [241-360, 2769]
3 XXXX 11111 361-480 [361-480, 279.09] [361-480, 1331]
我想将其转换为以下json字符串:
[{"name":"XXXX","type":11111,"time":[["1-120",261.05],["121-240",277.79],["241-360",269.64],["361-480",279.09]],"number":[["1-120",23229],["121-240",6382],["241-360",2769],["361-480",1331]]
如果我这样做,我收到错误ValueError: No axis named "type" for object type <class 'pandas.core.frame.DataFrame'>
:
jsonresult = df.groupby('name','type')['time','number'].agg(lambda x : x.tolist()).reset_index().to_json(orient='records')
jsonresult
仅当我执行df.groupby('name')
或df.groupby('type')
时才有效。
答案 0 :(得分:1)
您可以使用转换为tuple
代替list
:
jsonresult = df.groupby(['name','type'])['time','number']
.agg(lambda x: tuple(x)).reset_index().to_json(orient='records')
print (jsonresult)
[{"name":"XXXX",
"type":11111,
"time":[[-119,261.05],[-119,277.79],[-119,269.64],[-119,279.09]],
"number":[[-119,23229],[-119,6382],[-119,2769],[-119,1331]]}]