我有一个使用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
我如何用熊猫来做到这一点?
答案 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