条件应用 
要修改一个 Series 或 DataFrame 中的一列,需要以下两步。
- 基于一些谓词创建一个 boolean掩码
- 替换掉掩码评估为 True的值
- (仅当惰性操作时) 定义掩码评估为 False的值
数据集 
python
import numpy as np
import polars as pl
# 构造数据帧
df = pl.DataFrame({"range": np.arange(10), "left": ["foo"] * 10, "right": ["bar"] * 10})
df.head()text
shape: (5, 3)
┌───────┬──────┬───────┐
│ range ┆ left ┆ right │
│ ---   ┆ ---  ┆ ---   │
│ i64   ┆ str  ┆ str   │
╞═══════╪══════╪═══════╡
│ 0     ┆ foo  ┆ bar   │
│ 1     ┆ foo  ┆ bar   │
│ 2     ┆ foo  ┆ bar   │
│ 3     ┆ foo  ┆ bar   │
│ 4     ┆ foo  ┆ bar   │
└───────┴──────┴───────┘我们可以使用 .when()/.then()/.otherwise() 表达式。
- when- 接受一个谓词表达式
- then- 当- 谓词 == True时使用的表达式
- otherwise- 当- 谓词 == False时使用的表达式
请参见以下例子。
python
q = df.lazy().with_columns(
    pl.when(pl.col("range") >= 5).then(pl.col("left")).otherwise(pl.col("right")).alias("foo_or_bar")  # .alias增加一列
)
df = q.collect()
print(df)text
shape: (10, 4)
┌───────┬──────┬───────┬────────────┐
│ range ┆ left ┆ right ┆ foo_or_bar │
│ ---   ┆ ---  ┆ ---   ┆ ---        │
│ i64   ┆ str  ┆ str   ┆ str        │
╞═══════╪══════╪═══════╪════════════╡
│ 0     ┆ foo  ┆ bar   ┆ bar        │
│ 1     ┆ foo  ┆ bar   ┆ bar        │
│ 2     ┆ foo  ┆ bar   ┆ bar        │
│ 3     ┆ foo  ┆ bar   ┆ bar        │
│ …     ┆ …    ┆ …     ┆ …          │
│ 6     ┆ foo  ┆ bar   ┆ foo        │
│ 7     ┆ foo  ┆ bar   ┆ foo        │
│ 8     ┆ foo  ┆ bar   ┆ foo        │
│ 9     ┆ foo  ┆ bar   ┆ foo        │
└───────┴──────┴───────┴────────────┘