如何找到第一个 pandas 数据框中而不是第二个数据框中的元素,反之亦然。 python

How to find elements that are in first pandas Data frame and not in second, and viceversa. python

我有两个数据框。

first_dataframe

id
9
8
6
5
7
4

second_dataframe

id
6
4
1
5
2
3

注意:我的dataframe有很多列,但我只需要根据ID进行比较| 我需要找到:

  1. 第一个数据帧中而不是第二个数据帧中的 ID [1,2,3]
  2. 在第二个数据帧中而不在第一个数据帧中的 ID [7,8,9]

我已经搜索了答案,但我找到的所有解决方案似乎都不适合我,因为它们会根据索引查找更改。

使用set减法:

inDF1_notinDF2 = set(df1['id']) - set(df2['id']) # Removes all items that are in df2 from df1
inDF2_notinDF1 = set(df2['id']) - set(df1['id']) # Removes all items that are in df1 from df2

输出:

>>> inDF1_notinDF2
{7, 8, 9} 

>>> inDF2_notinDF1
{1, 2, 3}