首页 > 解决方案 > 如何对多个数据框列使用 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与多个列一起使用。

我也检查了类似的问题,但没有发现任何只针对特定列的内容。

如果可能的话,我还想避免合并两个数据框。

那么我将如何实现这一目标?

标签: pythonpandasdataframe

解决方案


因为你想避免merge这里是一个可能的解决方案是比较MultiIndexIndex.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))]

对于与mergeindicator参数比较解决方案:

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

推荐阅读