我需要从我的数据帧生成一个json,但是我尝试了很多df格式但是我仍然无法获得所需的json格式。
我需要的json格式是,
[
{
"Keyword": "Red",
"values": [
{
"value": 5,
"TC": "Color"
}
]
},
{
"Keyword": "Orange",
"values": [
{
"value": 5,
"TC": "Color"
}
]
},
{
"Keyword": "Violet",
"values": [
{
"value": 5,
"TC": "Color"
}
]
}
]
我想要一个df来生成这个json。请帮忙。
但目前我正在获取df.to_json:
{"Names":{"0":"Ram","1":"pechi","2":"Sunil","3":" Ravi","4":"sri"},"Values":{"0":"[{'value':2,'TC': 'TC Count'}]","1":"[{'value':2,'TC': 'TC Count'}]","2":"[{'value':1,'TC': 'TC Count'}]","3":"[{'value':1,'TC': 'TC Count'}]","4":"[{'value':1,'TC': 'TC Count'}]"}}
答案 0 :(得分:1)
我认为你需要:
set_index
表示不在嵌套dictionaries
to_dict
apply
创建dicts
reset_index
来自索引to_json
print (df)
Keyword TC value
0 Red Color 5
1 Orange Color 5
2 Violet Color 5
j = (df.set_index('Keyword')
.apply(lambda x: [x.to_dict()], axis=1)
.reset_index(name='values')
.to_json(orient='records'))
print (j)
[{"Keyword":"Red","values":[{"TC":"Color","value":5}]},
{"Keyword":"Orange","values":[{"TC":"Color","value":5}]},
{"Keyword":"Violet","values":[{"TC":"Color","value":5}]}]
写入file
:
(df.set_index('Keyword')
.apply(lambda x: [x.to_dict()], axis=1)
.reset_index(name='values')
.to_json('myfile.json', orient='records'))