小计& Pandas的Grandtotal转向

时间:2018-02-24 14:00:41

标签: pandas pivot xlsxwriter

Data Currently Populated

Data Desired

使用的代码段: -

df["Average"] = df["Average"].astype("category")

writer = pd.ExcelWriter('New.xlsx', engine='xlsxwriter')

table1 = pd.pivot_table(df,values=['Average'],index=['Manager','Cost'],aggfunc=[len],fill_value=0)

table2 = pd.pivot_table(df,values=['Average'], index=['Manager','Cost'],aggfunc=[np.sum],fill_value=0)

table = pd.concat((table1, table2), axis=1)

table.to_excel(writer, sheet_name='Sheet2')

table3 = pd.pivot_table(df,values=['Average'], index=['Project','Cost'],aggfunc=[len],fill_value=0)

table4 = pd.pivot_table(df,values=['Average'], index=['Project','Cost'],aggfunc=[np.sum],fill_value=0)

project_table = pd.concat((table3, table4), axis=1)

project_table.to_excel(writer, sheet_name='Sheet3')

请帮助我达到预期的效果?

1 个答案:

答案 0 :(得分:1)

您需要按sum创建新的DataFrame,MultiIndex.from_arrays添加MultiIndex的新级别,concat sort_index,{{3}},最后添加grandtotal {{3}} 1}}。

sum已更改为TotalA_total以便正确排序。

B_total
df = pd.DataFrame({'Manager':['A']*10+['B']*5,
                   'Cost':['a']*5+['c']*5+['b']*4+['a'],
                   'Average':range(15)})

print (df)
    Average Cost Manager
0         0    a       A
1         1    a       A
2         2    a       A
3         3    a       A
4         4    a       A
5         5    c       A
6         6    c       A
7         7    c       A
8         8    c       A
9         9    c       A
10       10    b       B
11       11    b       B
12       12    b       B
13       13    b       B
14       14    a       B