开发者社区> 问答> 正文

如何在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) 

我只想为价格列添加总价值。怎么在数据透视表中做呢? 预期产量应该是这样的;

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**

问题来源StackOverflow 地址:/questions/59383476/how-to-find-total-of-only-one-column-in-python-pandas-pivot-table

展开
收起
kun坤 2019-12-27 10:19:05 836 0
1 条回答
写回答
取消 提交回答
  • 通过query方法进行操作就可以啦

    2020-03-25 17:05:56
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
From Python Scikit-Learn to Sc 立即下载
Data Pre-Processing in Python: 立即下载
双剑合璧-Python和大数据计算平台的结合 立即下载