我有两个数据框: df1:
| from id | from group | to id | to group |
| 1 | A | 3 | B |
| 4 | B | 4 | X |
| 5 | F | 5 | J |
| 2 | B | 3 | A |
df2:
| From | To |
| A | B |
| F | J |
我想过滤掉 df2 中的值(如果存在于 df1 的“来自组”和“至组”列中)
预期输出:
| from id | from group | to id | to group |
| 4 | B | 4 | X |
| 2 | B | 3 | A |
我正在寻找灵活的解决方案。如果 df2 列中的值发生更改,该解决方案也不会更改。
最佳答案
您可以将 .merge
与 indicator=True
一起使用,然后过滤 df1
:
x = df1[
df1.merge(
df2,
left_on=["from group", "to group"],
right_on=["From", "To"],
indicator=True,
how="left",
)._merge.eq("left_only")
]
print(x)
打印:
from id from group to id to group
1 4 B 4 X
3 2 B 3 A
关于python - 根据数据框中的条件过滤数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69166179/