You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Polars中筛选出不在另一DataFrame行元素中的数据?

用Polars实现DataFrame行筛选(排除匹配另一DataFrame的行)

你需要从df1中排除那些c和l列组合与df2完全匹配的行,Polars里用**反连接(anti join)**就能直接实现,不需要像pandas那样借助多索引,步骤如下:

1. 构建示例数据

先还原你的两个DataFrame:

import polars as pl

df1 = pl.DataFrame({
    "c": ["A", "A", "B", "C", "C"],
    "k": [1, 2, 2, 2, 2],
    "l": ["a", "b", "a", "a", "d"]
})

df2 = pl.DataFrame({
    "c": ["A", "C"],
    "l": ["b", "a"]
})

2. 执行反连接筛选

使用join方法并指定how="anti",连接列为c和l:

result = df1.join(df2, on=["c", "l"], how="anti")
print(result)

输出结果

运行后会得到你预期的筛选结果:

shape: (3, 3)
┌─────┬─────┬─────┐
│ c   ┆ k   ┆ l   │
│ --- ┆ --- ┆ --- │
│ str ┆ i64 ┆ str │
╞═════╪═════╪═════╡
│ A   ┆ 1   ┆ a   │
│ B   ┆ 2   ┆ a   │
│ C   ┆ 2   ┆ d   │
└─────┴─────┴─────┘

原理说明

how="anti"的作用是:只保留df1中那些在指定连接列(这里是c和l)上无法与df2找到匹配项的行,完美契合你“筛选出df1中所有未出现在df2中的行”的需求。

内容的提问来源于stack exchange,提问作者user7802048

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 22:05:18