如何在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
相关产品推荐
相关产品推荐

