如何在Pandas中进行反连接操作(附实例)

337 阅读1分钟

反连接允许你返回一个数据集中所有在另一个数据集中没有匹配值的记录。

你可以使用以下语法在两个pandas DataFrames之间执行反连接。

outer = df1.merge(df2, how='outer', indicator=True)

anti_join = outer[(outer._merge=='left_only')].drop('_merge', axis=1)

下面的例子展示了如何在实践中使用这种语法。

例子:在Pandas中执行反连接

假设我们有以下两个pandas DataFrames:

import pandas as pd

#create first DataFrame
df1 = pd.DataFrame({'team': ['A', 'B', 'C', 'D', 'E'],
                    'points': [18, 22, 19, 14, 30]})

print(df1)

  team  points
0    A      18
1    B      22
2    C      19
3    D      14
4    E      30

#create second DataFrame
df2 = pd.DataFrame({'team': ['A', 'B', 'C', 'F', 'G'],
                    'points': [18, 22, 19, 22, 29]})

print(df2)

  team  points
0    A      18
1    B      22
2    C      19
3    F      22
4    G      29

我们可以使用下面的代码来返回第一个DataFrame中所有在第二个DataFrame中没有匹配团队的行:

#perform outer join
outer = df1.merge(df2, how='outer', indicator=True)

#perform anti-join
anti_join = outer[(outer._merge=='left_only')].drop('_merge', axis=1)

#view results
print(anti_join)

  team  points
3    D      14
4    E      30

我们可以看到,第一个数据框架中正好有两个团队在第二个数据框架中没有匹配的团队名称。

反连接按预期进行。

最终的结果是一个数据框架,其中只包含团队名称属于第一个数据框架但不属于第二个数据框架的行。

其他资源

下面的教程解释了如何在pandas中执行其他常见任务:

如何在Pandas中做内联
如何在Pandas中做左联
如何在Pandas中做交叉联接