gpt4 book ai didi

python - 如何旋转 Pandas 数据框?

转载 作者:太空宇宙 更新时间:2023-11-03 23:53:29 33 4
gpt4 key购买 nike

我的 DataFrame 看起来像这样:

enter image description here

如何为每个 部门 制定预算

应该是这样的:

enter image description here

import pandas as pd 

df=pd.DataFrame ({
'TotalAmount':[500,600,780,900],
'Division': ['Commercial Auto', 'Commercial Auto','Surety', 'Worker''s Comp'],
'MonthNumber':[1,2,3,4],
'YearNumber': [2019,2019,2019,2019],
'Budget': [550,570,700,920],
'PostDate': ['2019-01-01', '2019-02-01','2019-03-01','2019-04-01']
})
#print(df)
t = pd.pivot_table(df, values='Budget', index='Division',columns='MonthNumber',fill_value=0).reset_index()
print(t)

最佳答案

df1 = pd.pivot_table(df, values=['TotalAmount','Budget'] , index='Division',columns='MonthNumber',fill_value=0).T.unstack(0).T.reset_index()
df1.columns.name = None
df1 = df1.sort_values(['Division','level_1'], 0, [True,False])
df1.Division = df1.level_1.where(df1.level_1 == 'Budget', df1.Division)
df1 = df1.drop('level_1', 1)

结果:

          Division    1    2    3    4
1 Commercial Auto 500 600 0 0
0 Budget 550 570 0 0
3 Surety 0 0 780 0
2 Budget 0 0 700 0
5 Workers Comp 0 0 0 900
4 Budget 0 0 0 920

关于python - 如何旋转 Pandas 数据框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58599306/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com