gpt4 book ai didi

python - 将数据帧列合并到具有动态列名称或索引的嵌套键中

转载 作者:行者123 更新时间:2023-12-01 06:29:26 25 4
gpt4 key购买 nike

我是 python 和 pandas 的新手。我需要将数据帧上的多个列合并到输出 json 中的嵌套键中。除名称列外,列名称都是动态的。

输入:

   name      384925  504100  296371  487730  296373  487729  296374  489406  296400  486601  384113
0 abc 0.0 0.0 -0.375 0.0 0.375 0.000 0.5 0.00 0.5 0.000 0.5
1 def NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
2 xyz 0.0 0.0 -0.375 0.0 0.375 0.000 0.5 0.00 0.5 0.000 0.5

预期输出 json

[
{
"name": "abc",
"sizes": [
{ "384925": 0.0 },
{ "504100": 0.0 },
{ "296371": -0.375 },
{ "487730": 0.0 },
{ "296373": 0.375 },
{ "487729": 0.0 },
{ "296374": 0.5 },
{ "489406": 0.0 },
{ "296400": 0.5 },
{ "486601": 0.0 },
{ "384113": 0.5 }
]
},
{
"name": "def",
"sizes": [
{ "384925": null },
{ "504100": null },
{ "296371": null },
...
{ "486601": null },
{ "384113": null }
]
},
{
"name": "xyz",
"sizes": [
{ "384925": 0.0 },
{ "504100": 0.0 },
{ "296371": -0.375 },
...
{ "486601": 0.0 },
{ "384113": 0.5 }
]
},
]

我尝试过的代码

df.iloc[:, 2:].apply(lambda x: tuple(x)).to_dict()

json_out = df.to_json(orient='records')

最佳答案

一行,创建所需的输出

out = [
{'name': gname, 'sizes': gdf.drop(columns='name').to_dict(orient='records')}
for gname, gdf in df.groupby('name')
]

如果你想转换成json,

json.dumps(out)

关于python - 将数据帧列合并到具有动态列名称或索引的嵌套键中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59974945/

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