gpt4 book ai didi

python - ValueError : No axis named "type" for object type
转载 作者:太空宇宙 更新时间:2023-11-04 02:55:31 27 4
gpt4 key购买 nike

这是我的数据框 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') .

最佳答案

您可以使用转换为 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]]}]

关于python - ValueError : No axis named "type" for object type <class 'pandas. core.frame.DataFrame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42505601/

27 4 0

Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com