如何在Polars Series中替换特定值?替换inf为0的实现方法
如何用Polars表达式替换Series中的inf值为0?
当然可以用Polars表达式实现这个需求,核心是借助Polars的表达式上下文(pl.when属于表达式API,无法直接在Series对象上调用),以下是两种简洁的实现方式:
方法一:临时DataFrame中转
import polars as pl example = pl.Series([1,2,float('inf'),4]) # 将Series转为单列DataFrame,用表达式完成替换后转回Series output = example.to_frame().select( pl.when(pl.col(example.name) == float('inf')) .then(0) .otherwise(pl.col(example.name)) ).to_series() print(output) # 输出: # shape: (4,) # Series: '0' [f64] # [ # 1.0 # 2.0 # 0.0 # 4.0 # ]
方法二:直接用pl.select结合表达式
这种写法无需显式转换DataFrame,更简洁:
output = pl.select( pl.when(example == float('inf')) .then(0) .otherwise(example) ).to_series()
补充说明
Polars的pl.when是表达式级别的API,仅能在DataFrame的操作上下文(比如select、with_columns)中使用,而Series本身没有when属性,因此需要通过上述方式将Series纳入表达式上下文完成替换。相比你之前使用的map_dict方法,表达式写法的扩展性更强——如果后续需要添加更多替换规则(比如同时处理负无穷-inf),直接追加.when(...).then(...)即可。
内容的提问来源于stack exchange,提问作者Sandwichnick
相关产品推荐
相关产品推荐

