2017-05-31 155 views
0

我有以下的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?

回答

1

您可以使用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 
+0

謝謝!有用!但是我不明白什麼是正在做json_normalize? – bAN

0

請嘗試使用此方法解決你的問題: 在「詞典列表」的形式獲取值(從價格字典)從網上API響應:這樣 值= [{},{}]並將其傳遞到pd數據框。

df = pd.DataFrame(values) 
print(df) 

你會得到你想要的。更多詳情http://pbpython.com/pandas-list-dict.html