如何在python透视表中只找到一列的合计?

2024-04-27 23:16:25 发布

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

我的数据是从excel中获取的

Invoice Cost centre Invoice Category Price DataFeed Reporting Fequency
RIM                  Retail QLD      22.25  WEB      DWM
R5M                  Retail SYD      22.25  BWH      M
.....

我的数据透视表就像

df = pd.read_excel(file_path, sheet_name='Invoice Details', usecols="E:F,I,L:M")                       

df['Price'] = df['Price'].astype(float)                                                                
df1 = df.groupby(["Invoice Cost Centre", "Invoice Category"]).agg({'Price': 'sum'}).reset_index()      

df = pd.pivot_table(df, index=["Invoice Cost Centre", "Invoice Category"],                             
                    columns=['Price', 'Reporting Frequency', 'Data Feed'],                             
                    aggfunc=len,                                                                       
                    fill_value=0)                                                                      

df2 = df.merge(df1, left_on=["Invoice Cost Centre", "Invoice Category"],                               
               right_on=["Invoice Cost Centre", "Invoice Category"], how='left').fillna(0) 

enter image description here

我只想为价格列添加总值。如何在透视表中添加值

预期产出应该是这样的

Invoice Cost Centre  Invoice Category (22.25,M,BWH) (40,DWM,WEB)...     Price
           D3TM        Retail QLD                                     1907.85
          EQUITYEMP     Retail SYD                                    104.00
           EQUITYEMP                                                   463.15
           EQUITYEMP       ...                                         62.40
           EQUITYEMP                                                   201.95

                                                               **Total=2800**

Tags: 数据webdfinvoiceexcelpricereportingcategory