使用多索引计算pandas pivot_表中的小计

2024-09-29 02:19:26 发布

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

在数据帧中,我有以下原始数据:

   BROKER    VENUE  QUANTITY
0  BrokerA  Venue_1       300
1  BrokerA  Venue_2       400
2  BrokerA  Venue_2      1400
3  BrokerA  Venue_3       800
4  BrokerB  Venue_2       500
5  BrokerB  Venue_3      1100
6  BrokerC  Venue_1      1000
7  BrokerC  Venue_1      1200
8  BrokerC  Venue_2     17000

我想对数据进行总结,看看每个经纪人向每个场地发送了多少,所以我创建了一个pivot_表:

^{pr2}$

结果如预期:

                 QUANTITY
BROKER  VENUE            
BrokerA Venue_1     300.0
        Venue_2    1800.0
        Venue_3     800.0
BrokerB Venue_2     500.0
        Venue_3    1100.0
BrokerC Venue_1    2200.0
        Venue_2   17000.0

我也要给每个经纪人发多少。在同一张桌子上展示。我可以通过输入df.groupby('BROKER').sum()来获得这些信息,但是如何将其作为一个名为brokertotal的列添加到pivot表中呢?在

注意:这个问题很相似,但似乎是老版本的问题,我最好的猜测是不适合我的情况:Pandas Pivot tables row subtotals


Tags: 数据df原始数据经纪人brokerquantitypivotgroupby
1条回答
网友
1楼 · 发布于 2024-09-29 02:19:26

您可以为df1创建^{},为pt和最后一个^{}创建{a1}:

df1 = df.groupby('BROKER').sum()
df1.index = pd.MultiIndex.from_arrays([df1.index + '_total', len(df1.index) * ['']])
print (df1)
                QUANTITY
BrokerA_total       2900
BrokerB_total       1600
BrokerC_total      19200

print (pd.concat([pt, df1]).sort_index())
                       QUANTITY
BROKER        VENUE            
BrokerA       Venue_1       300
              Venue_2      1800
              Venue_3       800
BrokerA_total              2900
BrokerB       Venue_2       500
              Venue_3      1100
BrokerB_total              1600
BrokerC       Venue_1      2200
              Venue_2     17000
BrokerC_total             19200

相关问题 更多 >