I would like to ask help on how to creating nested json from dataframe.
I have a 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'}
The problem is I want to separate into two json objects.
Here is my attempt:
[
{
"name":x['name'],
"xAxis":x['xAxis1'],
"yAxis":x['yAxis1'],
"lineStyle":x['lineStyle']} for _, x in global_line.iterrows()
]
It gives the result:
[{'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'}}]
The response that I want :
{
"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
}
]
],
...
}
Any help and suggestion would be much appreciated.
Thank you.
3
Answers
Use
DataFrame.to_dict
with join in list comprehension:Based on of your code (but using
itertuples
that is more efficient thaniterrows
):Output:
Another option with keys separation: