【发布时间】:2022-11-07 09:44:55
【问题描述】:
我导出 Postgresql 查询以创建类似于以下内容的 Pandas 数据框 df:
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()。
问题:
- 如何分解
sales和expenses列? - 爆炸两列后,如何从原始数据框中添加回另外两列(
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谢谢!
【问题讨论】:
标签: pandas