我想请教如何从 Dataframe 创建嵌套的json。我有一个 Dataframe
name value xAxis1 yAxis1 xAxis2 yAxis2 lineStyle
0 LCL 0.205512 0 0.205512 200 0.205512 {'type': 'dashed'}
1 UCL 0.327907 0 0.327907 200 0.327907 {'type': 'dashed'}
2 CL 0.269737 0 0.269737 200 0.269737 {'type': 'dashed'}
问题是我想把它分成两个json对象,下面是我的尝试:
[
{
"name":x['name'],
"xAxis":x['xAxis1'],
"yAxis":x['yAxis1'],
"lineStyle":x['lineStyle']} for _, x in global_line.iterrows()
]
它给出了结果:
[{'name': 'LCL',
'xAxis': 0,
'yAxis': 0.20551206141285452,
'lineStyle': {'type': 'dashed'}},
{'name': 'UCL',
'xAxis': 0,
'yAxis': 0.327906798236399,
'lineStyle': {'type': 'dashed'}},
{'name': 'CL',
'xAxis': 0,
'yAxis': 0.2697369344707218,
'lineStyle': {'type': 'dashed'}}]
我想要的回答是:
{
"data": [
[
{
"name": "LCL",
"xAxis1": 0,
"yAxis1": 0.205512,
"lineStyle": {
"type": "dashed"
}
},
{
"xAxis2": 200,
"yAxis2": 0.205512
}
],
[
{
"name": "UCL",
"xAxis1": 0,
"yAxis1": 0.327907,
"lineStyle": {
"type": "dashed"
}
},
{
"xAxis2": 200,
"yAxis2": 0.327907
}
]
],
...
}
如有任何帮助和建议,我将不胜感激。谢谢。
3条答案
按热度按时间332nm8kg1#
在列表解析中结合使用
DataFrame.to_dict
:py49o6xq2#
另一个具有键分离的选项:
ajsxfq5m3#
基于您的代码(但使用比
iterrows
更高效的itertuples
):输出: