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

能否在Polars中使用类Pandas的字符串表达式过滤DataFrame?

在Polars中兼容Pandas风格的字符串过滤表达式

Polars支持直接使用类似Pandas query的简洁字符串表达式进行过滤,无需用户修改原有语法,核心是通过pl.expr()方法解析字符串形式的谓词表达式。

基础用法示例

针对你提供的DataFrame,使用字符串表达式"foo < 3"过滤的写法如下:

import polars as pl

df = pl.DataFrame(
    {
        "foo": [1, 2, 3],
        "bar": [6, 7, 8],
        "ham": ["a", "b", "c"],
    }
)

# 用pl.expr解析字符串表达式后传入filter
result = df.filter(pl.expr("foo < 3"))
print(result)

执行后输出与df.filter(pl.col("foo") < 3)完全一致:

shape: (2, 3)
┌─────┬─────┬─────┐
│ foo ┆ bar ┆ ham │
│ --- ┆ --- ┆ --- │
│ i64 ┆ i64 ┆ str │
╞═════╪═════╪═════╡
│ 1   ┆ 6   ┆ a   │
│ 2   ┆ 7   ┆ b   │
└─────┴─────┴─────┘

复合表达式处理

对于多条件的复合表达式,只需保证语法符合Python逻辑运算规则(注意运算符优先级,必要时加括号),同样可以直接解析:

# 解析多条件字符串表达式
result = df.filter(pl.expr("(foo < 3) & (ham == 'a')"))
print(result)

输出:

shape: (1, 3)
┌─────┬─────┬─────┐
│ foo ┆ bar ┆ ham │
│ --- ┆ --- ┆ --- │
│ i64 ┆ i64 ┆ str │
╞═════╪═════╪═════╡
│ 1   ┆ 6   ┆ a   │
└─────┴─────┴─────┘

外部变量引用(兼容Pandas @语法)

如果你的用户表达式中需要引用外部变量(类似Pandas的@var写法),可以通过pl.expr()的globals参数传入变量:

threshold = 3
# 引用外部变量threshold
result = df.filter(pl.expr("foo < @threshold", globals={"threshold": threshold}))

原理说明

pl.expr()会将输入的字符串解析为Polars原生的表达式对象,等价于手动编写pl.col("foo") < 3这类Polars特定语法,从而实现用户无感知的库替换。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 04:15:29