重命名多索引元组pandas数据帧

问题描述 投票:0回答:1

我有一个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

我该怎么办?

dataframe indexing multi-index
1个回答
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

希望它有用

© www.soinside.com 2019 - 2024. All rights reserved.