假设我们要比较的两个数据框为df1和df2,我们可以使用以下代码来查找在两个数据框中都出现过的重复行:
common_rows = df1[df1.isin(df2)].dropna()
其中,isin()
方法可以查找df1中的元素是否在df2中出现过,返回一个布尔型数据框。然后我们再通过dropna()
方法去掉NaN值,即为在两个数据框中都出现的行。
例如,我们有以下两个数据框:
import pandas as pd
df1 = pd.DataFrame({'col1': [1, 2, 3], 'col2': ['a', 'b', 'c']})
df2 = pd.DataFrame({'col1': [2, 3, 4], 'col2': ['b', 'c', 'd']})
使用上面的方法,可以得到df1和df2中都出现的行:
col1 col2
1 2 b
2 3 c
另外,如果我们只需要查找其中一个数据框中的重复行,可以使用pandas提供的duplicated()
方法,如下:
# 查找df1中的重复行
duplicate_rows = df1[df1.duplicated()]
# 查找df2中的重复行
duplicate_rows = df2[df2.duplicated()]