After merging I miss pivot table columns in pandas

守給你的承諾、 提交于 2020-01-14 07:00:32

问题


I try to create an output like this;

I face difficulties to get my Total column. To get it I use merge as follows;

Total = count*price column

Here is my code;

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

This produces the output like; In the above, my pivot tables' columns are joined with ,. How can i make them to remain as it is while doing join?

来源:https://stackoverflow.com/questions/59367985/after-merging-i-miss-pivot-table-columns-in-pandas

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!