json - 将包含 json 数据的 pandas 数据框的列拆分为多个列

我加载并规范化了一个 json 数据:

json_string = json.loads(data)
df_norm = json_normalize(json_string, errors='ignore')

假设它现在有 2 列:

Group       Members

A           [{'id':'1', 'metrics': '34', 'profile': 'abc'},{'id':'3', 
              'metrics': '32', 'profile': 'dc'}]
B           [{'id':'2', 'metrics': '4', 'profile': 'bac'}]

我正在寻找一种方法来拆分“成员”列并将其合并回同一“组”下的原始数据框,例如:

Group   Members                                                                                          id     metrics     profile
A       {'id':'1', 'metrics': '34', 'profile': 'abc'},{'id':'3', 'metrics': '32', 'profile': 'dc'}]      1      34          abc
A       {'id':'1', 'metrics': '34', 'profile': 'abc'},{'id':'3', 'metrics': '32', 'profile': 'dc'}]      3      32          dc
B       [{'id':'2', 'metrics': '4', 'profile': 'bac'}]                                                   4      4           bac

如有任何帮助,我们将不胜感激。

最佳答案

使用:

import ast

#if necessary convert column to list of dicts
df['Members'] = df['Members'].apply(ast.literal_eval)
#create DataFrames in list comprehension
df1 = pd.concat({k:pd.DataFrame(v) for k, v in df['Members'].items()})
#join to original
df = df.join(df1.reset_index(level=1, drop=True)).reset_index(drop=True)
print (df)
  Group                                            Members id metrics profile
0     A  [{'id': '1', 'metrics': '34', 'profile': 'abc'...  1      34     abc
1     A  [{'id': '1', 'metrics': '34', 'profile': 'abc'...  3      32      dc
2     B    [{'id': '2', 'metrics': '4', 'profile': 'bac'}]  2       4     bac

https://stackoverflow.com/questions/54971005/

相关文章:

android - 在自定义 Camera2 API 上显示矩形边界框(覆盖),以便仅捕获框内的图像

ionic-framework - Ionic3 - 电子邮件编辑器 - 对象(...)不是函数

uml - 如何建立伙伴关系模型?

python-3.x - 在将多头 pandas 数据帧输出到 excel 时摆脱索引

unity3d - 应该如何使用 Unity 的 ExecuteEvents.Execute?

angular - 由于内存问题,compodoc 未生成图形

html - 如何判断 Chrome 表单不包含信用卡字段?

kubernetes - 如何在 OSX 上使用 Kubernetes 持久本地卷和 Minikub

debugging - 如何从 Web 应用程序连接本地托管的 Azure BOT

angular7 - 无法加载 server.component.html