将小计移至底部

2024-05-23 16:26:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这个数据框

DistrictName         RegionName Value
Ashburton            Canterbury 451
Auckland City        Auckland   2459
Banks Peninsula      Canterbury 132
Buller               West Coast 361
Carterton            Wellington 75
Central Hawkes Bay   Hawkes Bay 67
Central Otago* Central Otago & Lakes District        Central Otago & Lakes District 190
Christchurch City    Canterbury 2046
Clutha               Otago  119
Dunedin City         Otago  312

我正在尝试将此作为重点,并为每个区域提供值&;地区,这么做

pivot_table(districtleveldatav1.head(10), values=['Value'],index=['RegionName'], 
                    columns=['DistrictName'], aggfunc=np.sum, margins=True).stack('DistrictName').drop('All', level=0)

给我这个

enter image description here

我需要做两件事

  1. 我怎么能在每个区域的底部都有'All'in DistrictName。?可能带有标签“Total”

  2. 是否可以根据我的自定义订单手动订购RegionName。类似的地区名称?谢谢


Tags: 区域cityvalueall地区centralbayhawkes
1条回答
网友
1楼 · 发布于 2024-05-23 16:26:18

这些列似乎是按名字的字母顺序排列的All首先出现,因为它以A开头,按字母顺序排列时,前面没有其他列

要使名称Total而不是All,可以使用margins_name参数,如中所示

a.pivot_table(values=['Value'],index=['RegionName'], columns=['DistrictName'], aggfunc=np.sum, margins=True,margins_name="Total").stack('DistrictName').drop('Total', level=0)

在设置margins=True之后

这会给你

                                                                               Value
RegionName                     DistrictName
Auckland                       Auckland City                                  2459.0
                               Total                                          2459.0
Canterbury                     Ashburton                                       451.0
                               Banks Peninsula                                 132.0
                               Christchurch City                              2046.0
                               Total                                          2629.0
Central Otago & Lakes District Central Otago* Central Otago & Lakes District   190.0
                               Total                                           190.0
Hawkes Bay                     Central Hawkes Bay                               67.0
                               Total                                            67.0
Otago                          Clutha                                          119.0
                               Dunedin City                                    312.0
                               Total                                           431.0
Wellington                     Carterton                                        75.0
                               Total                                            75.0
West Coast                     Buller                                          361.0
                               Total                                           361.0

参见documentation

相关问题 更多 >