pandas DataFrame: normalize one JSON column and merge with other columns

前端 未结 1 972
太阳男子
太阳男子 2020-12-06 06:53

I have a pandas DataFrame containing one column with multiple JSON data items as list of dicts. I want to normalize the JSON column and duplicate the non-JSON columns:

相关标签:
1条回答
  • 2020-12-06 07:35

    You can use concat with dict comprehension with pop for extract column, remove second level and join to original:

    df1 = (pd.concat({i: pd.DataFrame(x) for i, x in df_actions.pop('actions').items()})
             .reset_index(level=1, drop=True)
             .join(df_actions)
             .reset_index(drop=True))
    

    What is same as:

    df1 = (pd.concat({i: json_normalize(x) for i, x in df_actions.pop('actions').items()})
             .reset_index(level=1, drop=True)
             .join(df_actions)
             .reset_index(drop=True))
    

    print (df1)
      type value  id
    0    a    17  12
    1    b    19  12
    2    a     1  15
    3    b     3  15
    4    c     5  15
    
    0 讨论(0)
提交回复
热议问题