大熊猫数据帧从嵌套JSON
问题描述:
我有以下的JSON为Web API响应:大熊猫数据帧从嵌套JSON
{"prices": [
{
"start_date": "2016-07-06T00:00:00+02:00",
"end_date": "2016-07-07T00:00:00+02:00",
"values": [
{
"start_date": "2016-07-06T00:00:00+02:00",
"end_date": "2016-07-06T00:30:00+02:00",
"upward_weighted": 45.66,
"downward_weighted": 20.63,
"upward_marginal": 30.1,
"downward_marginal": 12.8,
"updated_date": "2016-07-07T15:45:36+02:00"
},
{
"start_date": "2016-07-06T00:30:00+02:00",
"end_date": "2016-07-06T01:00:00+02:00",
"upward_weighted": 45.66,
"downward_weighted": 20.63,
"upward_marginal": 30.1,
"downward_marginal": 12.8,
"updated_date": "2016-07-07T15:45:36+02:00"
}
]}
]}
,我会检索prices->值作为一个数据帧。
start_date|end_date|upward_weighted|downward_weighted|...|updated_date|
----------|--------|---------------|-----------------|---|------------|
xxxxxxx |xxxxxxx |xxxxxxxx |xxxxxxx | |xxxxxx |
xxxxxxx |xxxxxxx |xxxxxxxx |xxxxxxx | |xxxxxx |
当我尝试pandas.read_json(resp.content)我得到的仅包含一列“价格”与字典错误的数据帧。
是否可以告诉pandas.read_json()
使用价格 - >值创建DataFrame?
答
您可以使用json_normalize
:
from pandas.io.json import json_normalize
df = json_normalize(d['prices'], 'values')
print (df)
downward_marginal downward_weighted end_date \
0 12.8 20.63 2016-07-06T00:30:00+02:00
1 12.8 20.63 2016-07-06T01:00:00+02:00
start_date updated_date upward_marginal \
0 2016-07-06T00:00:00+02:00 2016-07-07T15:45:36+02:00 30.1
1 2016-07-06T00:30:00+02:00 2016-07-07T15:45:36+02:00 30.1
upward_weighted
0 45.66
1 45.66
答
请尝试使用此方法解决你的问题: 在“词典列表”的形式获取值(从价格字典)从网上API响应:这样 值= [{},{}]并将其传递到pd数据框。
df = pd.DataFrame(values)
print(df)
你会得到你想要的。更多详情http://pbpython.com/pandas-list-dict.html
谢谢!有用!但是我不明白什么是正在做json_normalize? – bAN