如何将此嵌套的JSON以列形式转换为Pandas数据框 [英] how to convert this nested JSON in columnar form into Pandas dataframe
本文介绍了如何将此嵌套的JSON以列形式转换为Pandas数据框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我可以将这种嵌套的JSON格式以列格式读入熊猫.
I could read this nested JSON format in columnar format into pandas.
req = requests.get(REQUEST_API)
returned_data = json.loads(req.text)
# status
print("status: {0}".format(returned_data["status"]))
# api version
print("version: {0}".format(returned_data["version"]))
data_in_columnar_form = pd.DataFrame(returned_data["data"])
data = data_in_columnar_form["data"]
更新
我想将以下JSON方案转换为表格形式的表格,如何?
UPDATE
I want to convert the following JSON scheme into the tabular format as the table, how to ?
"data":[
{
"year":"2009",
"values":[
{
"Actual":"(0.2)"
},
{
"Upper End of Range":"-"
},
{
"Upper End of Central Tendency":"-"
},
{
"Lower End of Central Tendency":"-"
},
{
"Lower End of Range":"-"
}
]
},
{
"year":"2010",
"values":[
{
"Actual":"2.8"
},
{
"Upper End of Range":"-"
},
{
"Upper End of Central Tendency":"-"
},
{
"Lower End of Central Tendency":"-"
},
{
"Lower End of Range":"-"
}
]
},...
]
推荐答案
Pandas has a JSON normalization function (as of 0.13), straight out of the docs:
In [205]: from pandas.io.json import json_normalize
In [206]: data = [{'state': 'Florida',
.....: 'shortname': 'FL',
.....: 'info': {
.....: 'governor': 'Rick Scott'
.....: },
.....: 'counties': [{'name': 'Dade', 'population': 12345},
.....: {'name': 'Broward', 'population': 40000},
.....: {'name': 'Palm Beach', 'population': 60000}]},
.....: {'state': 'Ohio',
.....: 'shortname': 'OH',
.....: 'info': {
.....: 'governor': 'John Kasich'
.....: },
.....: 'counties': [{'name': 'Summit', 'population': 1234},
.....: {'name': 'Cuyahoga', 'population': 1337}]}]
.....:
In [207]: json_normalize(data, 'counties', ['state', 'shortname', ['info', 'governor']])
Out[207]:
name population info.governor state shortname
0 Dade 12345 Rick Scott Florida FL
1 Broward 40000 Rick Scott Florida FL
2 Palm Beach 60000 Rick Scott Florida FL
3 Summit 1234 John Kasich Ohio OH
4 Cuyahoga 1337 John Kasich Ohio OH
这篇关于如何将此嵌套的JSON以列形式转换为Pandas数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文