分解多个 dict 列并与原始 Pandas 数据框连接

zeroes_ones

我导出 Postgres SQL 查询以创建df类似于以下内容的 Pandas 数据框:

df = pd.DataFrame({
    'employee_id' : [123, 456, 789],
    'country_code' : ['US', 'CAN', 'MEX'],
    'sales' : [{'foo': 2, 'bar': 0, 'baz': 1},
               {'foo': 3, 'bar': 1, 'baz': 2},
               {'foo': 7, 'bar': 0, 'baz': 4}],
    'expenses' : [{'red': 1, 'white': 0, 'blue': 3},
               {'red': 1, 'white': 0, 'blue': 1},
               {'red': 2, 'white': 2, 'blue': 2}]
})

df
 
    employee_id   country_code      sales                             expenses
0   123           US                {'foo': 2, 'bar': 0, 'baz': 1}    {'red': 1, 'white': 0, 'blue': 3}
1   456           CAN               {'foo': 3, 'bar': 1, 'baz': 2}    {'red': 1, 'white': 0, 'blue': 1}
2   789           MEX               {'foo': 7, 'bar': 0, 'baz': 4}    {'red': 2, 'white': 2, 'blue': 2}

我希望能够同时sales分解和expenses列,以便它们的键是单独的列目前,我只能分解其中一个列,如下所示:

df = pd.json_normalize(df['sales'])
df
    foo bar baz
0   2   0   1
1   3   1   2
2   7   0   4

我无法将列列表传递给pd.json.normalize().

问题:

  1. 如何同时爆炸salesexpenses列?
  2. 爆炸两列后,如何从原始数据框中添加另外两列(employee_id和)?country_code

所需的输出是:

    employee_id   country_code   foo   bar   baz   red   white   blue
0   123           US             2     0     1     1     0       3
1   456           CAN            3     1     2     1     0       1
2   789           MEX            7     0     4     2     2       2

谢谢!

某哥们

您可以使用concat沿着 axis=1 json_normalize

json_cols = ['sales','expenses']
result = pd.concat([pd.json_normalize(df[col]) for col in json_cols],axis=1)
result = pd.concat([df.drop(json_cols,axis=1),result],axis=1)

输出:

结果

    employee_id country_code    foo bar baz red white   blue
0   123         US               2   0   1   1   0       3 
1   456         CAN              3   1   2   1   0       1
2   789         MEX              7   0   4   2   2       2

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

Python Pandas连接多个数据框

在Pandas数据框中连接重复的列

如何解析pandas数据框中的JSON列,并将新数据框连接到原始数据框中?

在Spark SQL数据框中压缩和分解多个列

使用多个列连接熊猫数据框

连接/粘贴数据框中的多个列

将来自多个pandas数据框的所有列连接到一个包含数据和列名称的数据框

在pandas数据框中选择多个列

在pandas数据框中选择多个列

将多个文件连接到 Pandas 数据框中

连接多个数据框时保留原始分类映射

Pandas:来自同一数据框的列的条件连接

Pandas Python:连接具有相同列的数据框

在 Pandas 数据框的 dict 行中创建 elem 计数的新列

如果将dict键关闭,则将其映射到pandas数据框的列

从Pandas数据框中检索非零列作为dict

将字典中的键从dict添加到现有Pandas数据框中的列标题

pandas数据框to_dict两列作为索引,第三列作为值

嵌套字典中的Pandas数据框将dict键添加到自己的列

Pandas dict 列到列

从dict合并多个数据框

使用 dict 中的键在 pandas 数据框中查找相同的“键”,然后将值从 dict 分配给数据框空列

将数据框中的特定列转换为numpy数组并与原始数据框合并

Pandas数据框-根据多个条件计算创建多个列

Pandas 数据框:如何组合 2 个数据框但仅聚合 1 列,而新行被连接?

合并和连接wo pandas数据框,其中不包括右侧数据框列

Pandas:水平扩展/分解数据框

按一列右连接多个数据框

在Python中连接同一数据框的多个列