相关疑难解决方法(0)

pandas DataFrame:标准化一个JSON列并与其他列合并

我有一个熊猫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...
Run Code Online (Sandbox Code Playgroud)

我想要

>>>df_actions_parsed
   id      type    value
   12      a        17
   12      b        19
   15      a        1
   15      b        3
   15      c        5
Run Code Online (Sandbox Code Playgroud)

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

pd.concat([pd.DataFrame(json_normalize(x)) for x in df_actions['actions']],ignore_index=True)
Run Code Online (Sandbox Code Playgroud)

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

python json dataframe pandas

4
推荐指数
2
解决办法
3208
查看次数

标签 统计

dataframe ×1

json ×1

pandas ×1

python ×1