在pandas数据帧中提取嵌套的JSON

时间:2016-11-20 09:48:10

标签: python json pandas

我正在尝试在以下pandas数据帧中解压缩嵌套的JSON:

           id                                                              info
0           0  [{u'a': u'good', u'b': u'type1'}, {u'a': u'bad', u'b': u'type2'}]
1           1  [{u'a': u'bad', u'b': u'type1'}, {u'a': u'bad', u'b': u'type2'}]
2           2  [{u'a': u'good', u'b': u'type1'}, {u'a': u'good', u'b': u'type2'}]

我的预期结果是:

           id        type1    type2
0           0        good     bad
1           1        bad      bad
2           2        good     good

我一直在寻找包括json_normalize在内的其他解决方案,但不幸的是,这对我不起作用。我应该将JSON视为一个字符串来获得我想要的东西吗?或者有更简单的方法来做到这一点吗?

1 个答案:

答案 0 :(得分:5)

  1. 在此处设置公共路径( info )后,使用json_normalize处理list词典并将单个词组分成单独的系列。然后,unstack +应用系列,该系列会向下追加该级别。
  2. from pandas.io.json import json_normalize
    
    df_info = json_normalize(df.to_dict('list'), ['info']).unstack().apply(pd.Series)
    df_info
    

    enter image description here

    1. 使用可选的DF旋转aggfunc以处理重复的索引轴:
    2. DF = df_info.pivot_table(index=df_info.index.get_level_values(1), columns=['b'], 
                               values=['a'], aggfunc=' '.join)
      
      DF
      

      enter image description here

      1. 最后连接侧面:
      2. pd.concat([df[['ID']], DF.xs('a', axis=1).rename_axis(None, 1)], axis=1)
        

        enter image description here

        开始使用DF

        df = pd.DataFrame(dict(ID=[0,1,2], info=[[{u'a': u'good', u'b': u'type1'}, {u'a': u'bad', u'b': u'type2'}], 
                                                [{u'a': u'bad', u'b': u'type1'}, {u'a': u'bad', u'b': u'type2'}],
                                                [{u'a': u'good', u'b': u'type1'}, {u'a': u'good', u'b': u'type2'}]]))