Polars中是否有np.where等效实现?如何生成阈值判断新列
在Polars中实现类似numpy.where的条件赋值逻辑
需求:给Polars DataFrame添加新列Is_Acceptable?,当value列数值小于0.9时赋值为1,否则为0。以下是用Pandas结合numpy的实现作为参考:
import polars as pl import numpy as np df = pl.DataFrame({"fruit":["orange","apple","mango","kiwi"], "value":[1.0,0.8,0.7,1.2]}) df_pd = df.to_pandas() df_pd["Is_Acceptable?"] = np.where(df_pd["value"].lt(0.9), 1, 0) print(pl.from_pandas(df_pd))
输出结果:
shape: (4, 3) ┌────────┬───────┬────────────────┐ │ fruit ┆ value ┆ Is_Acceptable? │ │ --- ┆ --- ┆ --- │ │ str ┆ f64 ┆ i64 │ ╞════════╪═══════╪════════════════╡ │ orange ┆ 1.0 ┆ 0 │ │ apple ┆ 0.8 ┆ 1 │ │ mango ┆ 0.7 ┆ 1 │ │ kiwi ┆ 1.2 ┆ 0 │ └────────┴───────┴────────────────┘
Polars原生实现方法
方法1:使用pl.when().then().otherwise()(对应numpy.where逻辑)
这是最直观的替代方案,完全匹配numpy.where(条件, 真值, 假值)的逻辑结构:
import polars as pl df = pl.DataFrame({"fruit":["orange","apple","mango","kiwi"], "value":[1.0,0.8,0.7,1.2]}) df = df.with_columns( pl.when(pl.col("value") < 0.9) .then(1) .otherwise(0) .alias("Is_Acceptable?") ) print(df)
方法2:布尔列直接转整数(更简洁)
Polars中布尔值True等价于1,False等价于0,因此可以直接将条件判断结果转为整数类型:
import polars as pl df = pl.DataFrame({"fruit":["orange","apple","mango","kiwi"], "value":[1.0,0.8,0.7,1.2]}) df = df.with_columns( (pl.col("value") < 0.9).cast(pl.Int64).alias("Is_Acceptable?") ) print(df)
两种方法都会输出与参考实现完全一致的结果。
内容的提问来源于stack exchange,提问作者Ross
相关产品推荐
相关产品推荐

