我有这个Python Pandas数据帧:
code name account_name value
1 john debt 123
1 john revenue 432
1 john growth 2
2 mark cost 345
2 mark debt 432
2 mark revenue 432
2 mark growth 456
我需要它看起来像这样:
code name debt revenue growth cost
1 john 123 432 2
2 mark 432 432 456 345
我想这可能是分组和转置的组合,但我做得不对。
使用 df.pivot_table()
:
df.pivot_table(index=['name','code'],columns='account_name',values='value').rename_axis(None,1).reset_index()
name code cost debt growth revenue
0 john 1 NaN 123.0 2.0 432.0
1 mark 2 345.0 432.0 456.0 432.0