【问题标题】:pandas DataFrame: normalize one JSON column and merge with other columnspandas DataFrame:规范化一个 JSON 列并与其他列合并
【发布时间】:2018-09-15 05:40:42
【问题描述】:

我有一个 pandas DataFrame,其中包含一列,其中包含多个 JSON 数据项作为字典列表。我想规范化 JSON 列并复制非 JSON 列:

# creating dataframe
df_actions = pd.DataFrame(columns=['id', 'actions'])
rows = [[12,json.loads('[{"type": "a","value": "17"},{"type": "b","value": "19"}]')],
   [15, json.loads('[{"type": "a","value": "1"},{"type": "b","value": "3"},{"type": "c","value": "5"}]')]]
df_actions.loc[0] = rows[0]
df_actions.loc[1] = rows[1]

>>>df_actions
   id                                            actions
0  12  [{'type': 'a', 'value': '17'}, {'type': 'b', '...
1  15  [{'type': 'a', 'value': '1'}, {'type': 'b', 'v...

我想要

>>>df_actions_parsed
   id      type    value
   12      a        17
   12      b        19
   15      a        1
   15      b        3
   15      c        5

我可以使用以下方法标准化 JSON 数据:

pd.concat([pd.DataFrame(json_normalize(x)) for x in df_actions['actions']],ignore_index=True)

但我不知道如何将其连接回原始 DataFrame 的 id 列。

【问题讨论】:

    标签: python json pandas dataframe


    【解决方案1】:

    您可以使用concatdict comprehensionpop 提取列,删除第二级和join 到原始:

    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))
    

    什么是相同的:

    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
    

    【讨论】:

    • 男人是一个很棒的单线!谢谢,就这样!
    • 我有点震惊,以前从未有人提出过这个问题。
    • @jezrael 不确定你是否还在,但我已经尝试过这个解决方案,它会抛出错误“DataFrame not proper called!”是否需要更新 sytnax?
    • @DBA108642 在 pandas 0.25.1 中,两种解决方案仍然有效。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-11
    • 2021-09-20
    • 1970-01-01
    相关资源
    最近更新 更多