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

如何在Polars中对表达式使用pipe管道操作?

如何在Polars中对表达式执行pipe管道操作?

假设我们有这样一个转换函数:

def transformation(col: pl.Series) -> pl.Series:
    return col.tanh().name.suffix('_tanh')

我原本希望通过pipe方法批量处理列,写法如下:

df.with_columns(
   pl.col('colA').pipe(transformation), 
   pl.col('colB').pipe(transformation), 
   pl.col('colC').pipe(transformation), 
   pl.col('colD').pipe(transformation), 
)

但Polars原生并不支持对Series或表达式使用.pipe方法,只能用以下替代写法:

df.with_columns(
   transformation(pl.col('colA')), 
   transformation(pl.col('colB')), 
   transformation(pl.col('colC')), 
   transformation(pl.col('colD')), 
)

不过当transformation函数需要传入额外参数时,这种写法会显得杂乱。

自定义实现pipe方法

我自行给Polars的Expr类添加了pipe方法,目前可以正常运行:

def _pipe(self, func, *args, **kwargs):
    return func(self, *args, **kwargs)

pl.Expr.pipe = _pipe

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 16:25:32