合并后,我想念熊猫中的数据透视表列

时间:2019-12-17 05:15:50

标签: python pandas pandas-groupby

我尝试创建这样的输出; enter image description here

我在获得总计栏时遇到困难。要获得它,我使用合并如下;

Total = count*price column

这是我的代码;

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


    print(df2)                                                                                                                                
    df2.to_excel('a.xlsx',sheet_name='Invoice Summary')   

这将产生类似的输出; enter image description here 在上面,我的数据透视表的列与,相连。 我怎样才能让他们在加入时保持原样?

0 个答案:

没有答案