[英]python: Pandas - Convert complex json to a dataframe
我有一個復雜的JSON數據結構,必須將其轉換為數據框。 JSON結構如下:
{'fields': [{'id': 'a', 'label': 'Particulars', 'type': 'string'},
{'id': 'b', 'label': 'States', 'type': 'string'},
{'id': 'c', 'label': 'Gender', 'type': 'string'},
{'id': 'd', 'label': ' 11-2013', 'type': 'string'},
{'id': 'e', 'label': ' 12-2013', 'type': 'string'},
{'id': 'f', 'label': ' 1-2014', 'type': 'string'},
{'id': 'g', 'label': ' 2-2014', 'type': 'string'}],
'data': [['Animal Husbandry- incl Poultry, Dairy and Herdsman',
'Andhra Pradesh',
'Men',
'156.12',
'153.18',
'163.56',
'163.56'],
['Animal Husbandry- incl Poultry, Dairy and Herdsman',
'Bihar',
'Men',
'159.39',
'149.38',
'147.24',
'155.89'],
['Animal Husbandry- incl Poultry, Dairy and Herdsman',
'Gujarat',
'Men',
'157.08',
'145',
'145',
'145']]}
我想以以下格式從中制作一個數據框:
我直接嘗試使用read_json
函數,這給了我錯誤。 然后我嘗試使用json.normalize
,因為我不知道它的正常工作,它沒有給我想要的輸出。 誰能讓我知道如何使用json.normalize()
來獲取所需格式的輸出?
使用json_normalize
並通過列表理解設置列名稱:
from pandas.io.json import json_normalize
df = json_normalize(d, 'data')
df.columns = [x.get('label') for x in d['fields']]
print (df)
Particulars States Gender \
0 Animal Husbandry- incl Poultry, Dairy and Herd... Andhra Pradesh Men
1 Animal Husbandry- incl Poultry, Dairy and Herd... Bihar Men
2 Animal Husbandry- incl Poultry, Dairy and Herd... Gujarat Men
11-2013 12-2013 1-2014 2-2014
0 156.12 153.18 163.56 163.56
1 159.39 149.38 147.24 155.89
2 157.08 145 145 145
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.