ValueError:对象类型 <class 'pandas.core.frame.DataFrame 没有名为“type”的轴

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42505601/
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 03:05:26  来源:igfitidea点击:

ValueError: No axis named "type" for object type <class 'pandas.core.frame.DataFrame

pythonpandas

提问by Dinosaurius

This is my data frame dfreceived after some preprocessing:

这是我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]

I want to transform it into the following json string:

我想将其转换为以下 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]]

If I do it this way, I get an error ValueError: No axis named "type" for object type <class 'pandas.core.frame.DataFrame'>:

如果我这样做,我会收到一个错误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

It only works if I do df.groupby('name')or df.groupby('type').

它只有在我这样做时才有效df.groupby('name')df.groupby('type')

采纳答案by jezrael

You can use convert to tupleinstead list:

可以使用convert来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]]}]