我导出 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()
.
问题:
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
谢谢!
您可以使用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] 删除。
我来说两句