首页 > 解决方案 > 如果第二个数据帧不存在,则取两个数据帧的差异,同时保留第一个数据帧的值

问题描述

我有 2 个数据框: 数据框Current如下:

Type1   Type2   Val1    Val2
A       a       73      86
B       s       8       17
D       d       33      41

数据框Target如下:

Type1   Type2   Val1    Val2
A       a       159     199
B       s       135     198
C       f       200     145
D       d       149     119

我想找到Target - Current获得以下内容的区别:

Type1   Type2   Val1    Val2
A       a       86      113
B       s       127     181
C       f       200     145
D       d       116     78

所有Type1, Type2Current都存在于中,Target但反之亦然。我不确定如何处理上述问题。

159 - 73 = 86对于Type 1 = A and Type 2 = aType 1 = C and Type 2 = f不存在,Current因此对于数据帧它基本上为 0 Current。因此,Target - Currnet设置为Target

标签: pandasdataframepython-3.8

解决方案


用于将和数据帧中的索引set_index设置为and ,然后与可选参数一起使用(如果它不存在于 中,则保留这些值):MultiLeveltargetcurrentType1Type2DataFrame.subfill_value=0firstsecond

diff = (
    target.set_index(['Type1', 'Type2'])
    .sub(current.set_index(['Type1', 'Type2']), fill_value=0).reset_index()
)

结果:

print(diff)
  Type1 Type2   Val1   Val2
0     A     a   86.0  113.0
1     B     s  127.0  181.0
2     C     f  200.0  145.0
3     D     d  116.0   78.0

推荐阅读