我从pd.pivot_table发出了下面的数据框
sum
Price
Manager Status
Debra Henley declined 70000
pending 50000
presented 50000
won 65000
Fred Anderson declined 65000
pending 5000
presented 45000
won 172000
我想在最后一行的索引中添加一个TOTAL,以得到以下结果:
sum
Price
Manager Status
Debra Henley declined 70000
pending 50000
presented 50000
won 65000
Fred Anderson declined 65000
pending 5000
presented 45000
won 172000
All TOTAL 522000
请问我该怎么做?
答案 0 :(得分:0)
例如,这是数据帧:
Manager Status Price
0 Debra Henley declined 1000
1 Fred Anderson pending 1001
2 Debra Henley presented 1002
3 Fred Anderson won 1003
4 Debra Henley declined 1004
5 Fred Anderson pending 1005
6 Debra Henley presented 1006
7 Fred Anderson won 1007
8 Debra Henley declined 1008
9 Fred Anderson pending 1009
10 Debra Henley presented 1010
11 Fred Anderson won 1011
12 Debra Henley declined 1012
13 Fred Anderson declined 1013
14 Debra Henley pending 1014
15 Fred Anderson presented 1015
16 Debra Henley won 1016
17 Fred Anderson declined 1017
18 Debra Henley declined 1018
旋转表:
df.pivot_table(values='Price', index=['Manager', 'Status'], margins=True, margins_name='Total', aggfunc={'Price': np.sum})
结果:
Price
Manager Status
Debra Henley declined 5042
pending 1014
presented 3018
won 1016
Fred Anderson declined 2030
pending 3015
presented 1015
won 3021
要在最后一行添加总计,请将此margins=True, margins_name='Total'
添加到您的数据透视代码中。
最终代码:
df.pivot_table(values='Price', index=['Manager', 'Status'], margins=True, margins_name='Total', aggfunc={'Price': np.sum})
结果:
Price
Manager Status
Debra Henley declined 5042
pending 1014
presented 3018
won 1016
Fred Anderson declined 2030
pending 3015
presented 1015
won 3021
Total 19171
希望它有用