【问题标题】:Converting nested JSON转换嵌套 JSON
【发布时间】:2016-08-09 15:41:41
【问题描述】:

我有以下数据:

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'

【问题讨论】:

    标签: python json python-2.7 pandas nested


    【解决方案1】:

    我认为你可以不带参数使用json_normalize

    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
    

    如果您想更改列名,请使用split 的列表理解:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-26
      • 2022-01-15
      • 2019-03-15
      相关资源
      最近更新 更多