【问题标题】:How to read a json to a pandas MultiIndex Dataframe?如何将 json 读取到 pandas MultiIndex Dataframe?
【发布时间】:2020-05-28 23:45:05
【问题描述】:

我有一个像这样的 json 格式文件。

{'accounting': [{'firstName': 'John',
   'lastName': 'De',
   'age': 29,
   'PhNumber': 253435221},
  {'firstName': 'Mary',
   'lastName': 'Smith',
   'age': 38,
   'PhNumber': 5766546221}],
 'sales': [{'firstName': 'Sally',
   'lastName': 'Green',
   'age': 29,
   'PhNumber': 63546433221},
  {'firstName': 'Jim',
   'lastName': 'Galley',
   'age': 48,
   'PhNumber': 3566648322}]}

如何将其读入带有列的 pandas 多索引数据框

(accounting, firstname), (accoutning, lastName), (accounting, age), 
(accounting, PhNumber), (sales, firstname), (sales, lastName), (sales, age), (sales, PhNumber)

【问题讨论】:

    标签: json python-3.x pandas


    【解决方案1】:

    一种更简单的方法是在 concat 级别指定轴。这将有助于避免拆垛和排序,并保持原始列顺序。

    import json
    with open('myJson.json') as data_file:    
        d = json.load(data_file)  
    
    df = pd.concat({k: pd.DataFrame(v) for k, v in d.items()}, axis=1)
    
    

    【讨论】:

      【解决方案2】:

      通过DataFrame 构造函数使用字典理解:

      import json
      with open('myJson.json') as data_file:    
          d = json.load(data_file)  
      
      df = pd.concat({k: pd.DataFrame(v) for k, v in d.items()}).unstack(0).swaplevel(1,0, axis=1).sort_index(axis=1)
      print (df)
         accounting                               sales                       
           PhNumber age firstName lastName     PhNumber age firstName lastName
      0   253435221  29      John       De  63546433221  29     Sally    Green
      1  5766546221  38      Mary    Smith   3566648322  48       Jim   Galley
      

      【讨论】:

      • 请展开答案。将 json 读入数据框后,每个元素都形成一个字典。你已经为每个元素写了 if from dict 对吗?
      • pandas.read_json。那这个呢?这对多索引有帮助吗?
      • @Bharath_Raja - 不幸的是没有。
      猜你喜欢
      • 2020-08-17
      • 1970-01-01
      • 2013-10-06
      • 1970-01-01
      • 2019-04-22
      • 2016-04-01
      • 2019-05-20
      • 2017-08-25
      相关资源
      最近更新 更多