python - 如何对多个数据框列使用 isin(不合并)
问题描述
我有两个数据框:
df1
Company Symbol ID Date Value
0 AAA Inc A 123 2019-12-31 10
1 AAA Inc A 123 2020-03-30 11
2 BBB Inc B 456 2019-03-31 12
3 FFF Inc F 653 2019-06-31 22
4 ZZZ Inc Z 999 2019-03-30 13
df2
Company Symbol ID Date Price
0 AAA Inc A 123 2019-12-31 10
1 AAA Inc A 123 2019-09-30 20
2 AAA Inc A 123 2019-06-31 30
3 AAA Inc A 123 2019-03-30 40
4 BBB Inc B 456 2019-12-31 50
5 BBB Inc B 456 2019-09-30 50
6 BBB Inc B 456 2019-06-31 90
7 BBB Inc B 456 2019-03-31 10
8 CCC Inc C 789 2019-12-31 79
9 CCC Inc C 789 2019-09-31 43
我想创建一个第三个数据框,它是所有的['Symbol', 'ID', 'Date']
行df1
,但不是df2
。所以输出看起来像这样:
Company Symbol ID Date
0 AAA Inc A 123 2020-03-30
1 FFF Inc F 653 2019-06-31
2 ZZZ Inc Z 999 2019-03-30
我知道我可以做类似的事情df3 = df1[~df1['Symbol'].isin(df2['Symbol'])]
,但是在做了一些研究之后,似乎没有一个好方法可以isin
与多个列一起使用。
我也检查了类似的问题,但没有发现任何只针对特定列的内容。
如果可能的话,我还想避免合并两个数据框。
那么我将如何实现这一目标?
解决方案
因为你想避免merge
这里是一个可能的解决方案是比较MultiIndex
:Index.isin
cols = ['Symbol', 'ID', 'Date']
df3 = df1[~df1.set_index(cols).index.isin(df2.set_index(cols).index)]
print (df3)
Company Symbol ID Date Value
1 AAA Inc A 123 2020-03-30 11
3 FFF Inc F 653 2019-06-31 22
4 ZZZ Inc Z 999 2019-03-30 13
或者将列转换为元组:
cols = ['Symbol', 'ID', 'Date']
df3 = df1[~df1[cols].apply(tuple, 1).isin(df2[cols].apply(tuple, 1))]
对于与merge
和indicator
参数比较解决方案:
cols = ['Symbol', 'ID', 'Date']
df3 = (df1.merge(df2, on=cols, indicator=True, how='left', suffixes=('','_'))
.query("_merge == 'left_only'")[df1.columns])
print (df3)
Company Symbol ID Date Value
1 AAA Inc A 123 2020-03-30 11
3 FFF Inc F 653 2019-06-31 22
4 ZZZ Inc Z 999 2019-03-30 13
推荐阅读
- c# - 将 XML 反序列化为 List<>
- java - 为什么可迭代操作会在 Apache Beam 函数中引发错误?
- python - Pyramid 项目的 .jinja 模板中的 Vue.js
- java - Java:使用第一个数组的前 3 个整数,然后使用第二个数组的 3 个整数将 2 个数组组合成第三个数组
- r - 使用库(gpg)加密/解密 R 中的对象
- wordpress - 如何根据 WordPress 中另一个下拉列表的值更改下拉列表的内容?
- powershell - 检查文件是否存在于监视文件夹中
- c++ - 将递归算法生成所有组合转换为迭代
- javascript - 描述之外的 beforeEach 是否总是在描述内部的 beforeEach 开始之前完成?
- pytorch - 使用 Dev Pytorch 1.0 将 Pytorch 模型加载到 C++ 中