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

2024-09-29 02:28:29 发布

您现在位置: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_表:

pt = df.pivot_table(index=['BROKER', 'VENUE'], values=['QUANTITY'], aggfunc=np.sum)

结果如预期:

                 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()来获得这些信息,但是如何将其作为名为BROKER_TOTAL的列添加到透视表中呢

注意:这个问题类似,但似乎是在一个旧版本上,我最好的猜测是根据我的情况调整它,但没有成功:Pandas Pivot tables row subtotals


Tags: 数据ptdf原始数据经纪人brokerquantitypivot
1条回答
网友
1楼 · 发布于 2024-09-29 02:28:29

您可以为df1创建^{}^{}它到pt和最后一个^{}

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

相关问题 更多 >