Python 转换嵌套JSON
我有以下数据:Python 转换嵌套JSON,python,json,python-2.7,pandas,nested,Python,Json,Python 2.7,Pandas,Nested,我有以下数据: josonloc = [{u'borough': u'MANHATTAN', u'location': {u'latitude': u'40.8082795', u'needs_recoding': False}, u'unique_key': u'3405059', u'zip_code': u'10035'}] 但是当我导入数据时,它没有正确显示 df = pd.read_joson(jsonloc) 我尝试用以下方法清理数据: from pandas.io.json
josonloc = [{u'borough': u'MANHATTAN',
u'location': {u'latitude': u'40.8082795',
u'needs_recoding': False},
u'unique_key': u'3405059',
u'zip_code': u'10035'}]
但是当我导入数据时,它没有正确显示
df = pd.read_joson(jsonloc)
我尝试用以下方法清理数据:
from pandas.io.json import json_normalize
result = json_normalize(config, 'location',['latitude','longitude','needs_recoding'])
但这似乎不起作用。我得到:
KeyError: 'needs_recoding'
我认为您可以使用无参数:
import pandas as pd
from pandas.io.json import json_normalize
jsonloc = [{u'borough': u'MANHATTAN',
u'location': {u'latitude': u'40.8082795',
u'needs_recoding': False},
u'unique_key': u'3405059',
u'zip_code': u'10035'}]
result = json_normalize(jsonloc)
print result
borough location.latitude location.needs_recoding unique_key zip_code
0 MANHATTAN 40.8082795 False 3405059 10035
如果要更改列名,请使用列表理解:
cols = result.columns.str.split('.')
print cols
Index([ [u'borough'], [u'location', u'latitude'],
[u'location', u'needs_recoding'], [u'unique_key'],
[u'zip_code']],
dtype='object')
print [col[0] if len(col) == 1 else col[1] for col in result.columns.str.split('.')]
[u'borough', 'latitude', 'needs_recoding', u'unique_key', u'zip_code']
result.columns=[col[0] if len(col) == 1 else col[1] for col in result.columns.str.split('.')]
print result
borough latitude needs_recoding unique_key zip_code
0 MANHATTAN 40.8082795 False 3405059 10035