使用熊猫在数据透视表中添加第二个边距

时间:2020-01-28 13:51:40

标签: python pandas pivot-table

我有一个使用pandas()创建的数据透视表,如下所示:

Type    Type-1  Type-2  Type-3  Grand Total
product             
A           5   0           0   5
B           0   6           9   15
C           0   0           0   0
D           12  7           44  63
E           6   0           0   6
Deduction   0   0           9   9
H           50  6           8   64
I           0   0           0   0
Grand Total 73  19          70  162

现在,我想创建一个称为“ W / O Deduction”的第二边距,该边距将基本上从相应的列中减去要扣除的值。所以最终结果应该是这样的:

Type        Type-1  Type-2  Type-3  Grand Total
product             
A               5   0           0   5
B               0   6           9   15
C               0   0           0   0
D               12  7           44  63
E               6   0           0   6
Deduction       0   0           9   9
H               50  6           8   64
I               0   0           0   0
Grand Total     73  19          70  162
With DEDUCTION  73  19          61  153

我如何用熊猫来做到这一点?

1 个答案:

答案 0 :(得分:0)

DataFrame.loc用于新行,并用fill_value=0参数将Series.sub的所有列的值相减,以将NaN s替换为0的计数:< / p>

df.loc['W/O DEDUCTION'] = df.loc['Grand Total'].sub(df.loc['Deduction'], fill_value=0)
#alternative
#df.loc['W/O DEDUCTION'] = df.loc['Grand Total'] - df.loc['Deduction']


print (df)
               Type-1  Type-2  Type-3  Grand Total
Type                                              
A                   5       0       0            5
B                   0       6       9           15
C                   0       0       0            0
D                  12       7      44           63
E                   6       0       0            6
Deduction           0       0       9            9
H                  50       6       8           64
I                   0       0       0            0
Grand Total        73      19      70          162
W/O DEDUCTION      73      19      61          153