如果第二个数据帧不存在,则取两个数据帧的差异,同时保留第一个数据帧的值
Taking difference of two dataframe while keeping values from first if it doesnt exist in second
我有 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
Current
中的所有 Type1, Type2
对都存在于 Target
中,反之亦然。我不确定如何处理上述问题。
159 - 73 = 86
对于 Type 1 = A and Type 2 = a
但 Type 1 = C and Type 2 = f
不存在于 Current
中,因此对于 Current
数据帧基本上是 0。因此,Target - Currnet
设置为 Target
的值
使用set_index
将target
和current
数据帧中的MultiLevel
索引设置为Type1
和Type2
,然后使用DataFrame.sub
带有可选参数 fill_value=0
(如果 second
中不存在,则保留 first
的值):
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
我有 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
Current
中的所有 Type1, Type2
对都存在于 Target
中,反之亦然。我不确定如何处理上述问题。
159 - 73 = 86
对于 Type 1 = A and Type 2 = a
但 Type 1 = C and Type 2 = f
不存在于 Current
中,因此对于 Current
数据帧基本上是 0。因此,Target - Currnet
设置为 Target
使用set_index
将target
和current
数据帧中的MultiLevel
索引设置为Type1
和Type2
,然后使用DataFrame.sub
带有可选参数 fill_value=0
(如果 second
中不存在,则保留 first
的值):
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