2017-11-11 73 views
0

我試圖分析來自網站的數據。我解析了HTML以使用json.loads()獲取json數據。解析來自json.loads()的數據,在python中

​​3210

所以現在我留下了數據,如下所示:

data = """ 
{'aggregateRating': {'reviewCount': 1691, 
        '@type'  : 'AggregateRating', 
        'ratingValue': 4.0}, 
'review': [{'reviewRating' : {'ratingValue': 5}, 
       'datePublished': '2017-10-31', 
       'description' : "I had a chance to see the Lakers ...", 
       'author'  : 'Andre W.'}] 
} 
"""" 

我感興趣的是「檢討」數組中返回從reviewRating的「ratingValue」整數。當我運行此腳本:

pd.DataFrame(data['review'], columns = ['reviewRating']) 

我得到這個:

reviewRating 
0 {'ratingValue': 5} 

相反,我在尋找的形式來獲取數據:

ratingValue 
0 5 

我已經嘗試各種變體如

pd.DataFrame(data['review'], columns = ['reviewRating']['ratingValue']) 
pd.DataFrame(data['review'], columns = ['reviewRating'][['ratingValue']]) 
pd.DataFrame(data['review']['reviewRating'], columns = ['ratingValue']) 

但我是s我不明白數據或大熊貓的下層結構。

因此,我最好清理{'ratingValue':5}作爲字符串以保留感興趣的整數,還是有一種簡單的方法來創建具有整數值'ratingValue的DataFrame 「?

謝謝。

+0

你使它看起來像如果'數據'是'json'字符串,而它可能是一個字典。 –

回答

0

如果您使用 pandas.io.json您可以直接從json創建數據框。

使用您的樣本數據,我能夠輸出:

>>> frame = json_normalize(data) 

    author datePublished       description \ 
0 Andre W. 2017-10-31 I had a chance to see the Lakers ... 

    reviewRating.ratingValue 
0       5 

然後你就可以使用訪問評定值:

frame.at[0, 'reviewRating.ratingValue'] # which should give you 5