简体   繁体   English

使用 Pandas 的数据透视表,在末尾添加额外的行并进行减法计算

[英]Pivot table using Pandas, add extra row at the end with subtract calculation

I have a dataframe df, looks like below:我有一个数据框 df,如下所示:

product    price

prod0       10
prod1       20
prod2       30
prod3       40         
cashback    30

I want to create a pivot table using panda, where margin will be "GrandTot" and extra row will be there at the end "with cashbak" how can I get an output like below?我想使用 Panda 创建一个数据透视表,其中边距为“GrandTot”,并且在“with cashbak”末尾会有额外的行,我怎样才能得到如下输出?

col_name     price     GrandTot
Product
prod0         10         10
prod1         20         20
prod2         30         30
prod3         40         40
cashback      30         30
GrandTot      100        100
with cashbak  70         70 

Convert product to index and add new column by sum , also add GrandTot row with subtract cashback :product转换为索引并按sum添加新列,同时添加GrandTot行并减去cashback

df = df.set_index('product')
df['GrandTot'] = df.sum(axis=1)
df.loc['GrandTot'] = df.sum().sub(df.loc['cashback'], fill_value=0)
df.loc['with cashbak'] = df.loc['GrandTot'].sub(df.loc['cashback'], fill_value=0)

print (df)
              price  GrandTot
product                      
prod0            10        10
prod1            20        20
prod2            30        30
prod3            40        40
cashback         30        30
GrandTot        100       100
with cashbak     70        70

But it seems more logic is add total sum to with cashbak :但似乎更多的逻辑是with cashbak加上sum

df = df.set_index('product')
df['GrandTot'] = df.sum(axis=1)
sum = df.sum()
df.loc['GrandTot'] = sum.sub(df.loc['cashback'], fill_value=0)
df.loc['with cashbak'] = sum

print (df)
              price  GrandTot
product                      
prod0            10        10
prod1            20        20
prod2            30        30
prod3            40        40
cashback         30        30
GrandTot        100       100
with cashbak    130       130

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM