pandas - 如果第二个数据帧不存在,则取两个数据帧的差异,同时保留第一个数据帧的值
问题描述
我有 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, Type2
对Current
都存在于中,Target
但反之亦然。我不确定如何处理上述问题。
159 - 73 = 86
对于Type 1 = A and Type 2 = a
但Type 1 = C and Type 2 = f
不存在,Current
因此对于数据帧它基本上为 0 Current
。因此,Target - Currnet
设置为Target
解决方案
用于将和数据帧中的索引set_index
设置为and ,然后与可选参数一起使用(如果它不存在于 中,则保留这些值):MultiLevel
target
current
Type1
Type2
DataFrame.sub
fill_value=0
first
second
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
推荐阅读
- google-chrome - Chromium 构建在 Ubuntu 上一段时间后失败
- python-3.x - 将您的谷歌浏览器克隆到 Selenium Webdriver
- python - 如何使按钮单击事件
- node.js - 使用 Express/NestJS 在 2 个 API 之间检索 ip:port
- jupyter-notebook - 我们如何使用 ThebeLab 执行由带有 ielixir 内核的 Jupyter Notbook 支持的代码单元
- c++ - 一个类的所有实例共享的静态 std::mutex
- java - 使用 JDA 10 秒后删除 MessageEmbed
- javascript - 使用 CSS 或使用脚本更改按钮
- javascript - 在反应中切换路由时如何删除事件侦听器?
- r - R Funktion selber schreiben -> Moderationsanalysis