how to convert this nested JSON in columnar form into Pandas dataframe

后端 未结 1 727
一整个雨季
一整个雨季 2020-12-11 22:16

I could read this nested JSON format in columnar format into pandas.

JSON Scheme

JSON scheme format

相关标签:
1条回答
  • 2020-12-11 23:10

    Pandas has a JSON normalization function (as of 0.13), straight out of the docs:

    In [205]: from pandas.io.json import json_normalize
    
    In [206]: data = [{'state': 'Florida',
       .....:           'shortname': 'FL',
       .....:           'info': {
       .....:                'governor': 'Rick Scott'
       .....:           },
       .....:           'counties': [{'name': 'Dade', 'population': 12345},
       .....:                       {'name': 'Broward', 'population': 40000},
       .....:                       {'name': 'Palm Beach', 'population': 60000}]},
       .....:          {'state': 'Ohio',
       .....:           'shortname': 'OH',
       .....:           'info': {
       .....:                'governor': 'John Kasich'
       .....:           },
       .....:           'counties': [{'name': 'Summit', 'population': 1234},
       .....:                        {'name': 'Cuyahoga', 'population': 1337}]}]
       .....: 
    
    In [207]: json_normalize(data, 'counties', ['state', 'shortname', ['info', 'governor']])
    Out[207]: 
             name  population info.governor    state shortname
    0        Dade       12345    Rick Scott  Florida        FL
    1     Broward       40000    Rick Scott  Florida        FL
    2  Palm Beach       60000    Rick Scott  Florida        FL
    3      Summit        1234   John Kasich     Ohio        OH
    4    Cuyahoga        1337   John Kasich     Ohio        OH
    
    0 讨论(0)
提交回复
热议问题