代码之家  ›  专栏  ›  技术社区  ›  Ratha

如何使用pandas pivot表中的column*value得到行的和?

  •  1
  • Ratha  · 技术社区  · 6 年前

    我试图得到以下输出。坚持要得到总数。

    enter image description here

    这是我的密码;

    def generate_invoice_summary_info():                                                                                                         
        file_path = 'output.xlsx'                                                                                                                
        df = pd.read_excel(file_path, sheet_name='Invoice Details', usecols="E:F,I,L:M")                                                         
    
        df['Price'] = df['Price'].astype(float)                                                                                                  
        # df['Total'] = 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,margins=True)                                                                           
        print(df.head())                                                                                                                         
        df.to_excel('a.xlsx',sheet_name='Invoice Summary')       
    

    以上代码产生以下输出(90%正确) enter image description here

    计算每行的总计列,基于 count* price

    Total = count*price column
    

    如何在透视表中执行此操作?

    编辑 打印(df):

    Price                                           10.4        ...    85.0   All
    Reporting Frequency                                M        ...       M      
    Data Feed                                        BWH EMAIL  ... StarBOS      
    Invoice Cost Centre Invoice Category                        ...              
    D3TM                Reseller Non Equity           21    10  ...       0   125
    EQUITYEMP           Baileys                        0     7  ...       0    10
                        Energy NSW                     16     0  ...       0    32
                        Far North Queensland           3     0  ...       0     6
                        South East                     6     0  ...       0    16
                        Cooper & Dysart                0     0  ...       0     3
                        Petro Fuel & Lubricants        8     0  ...       0    20
                        South East QLD Fuels           0     0  ...       0    19
    R1M                 Retail QLD                    60     0  ...       0   867
    
    0 回复  |  直到 6 年前