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

如何在Polars中基于when条件一次性生成多列?

一次性在Polars中通过条件生成多列的方法

方法1:利用结构体(Struct)统一处理条件分支

通过pl.struct()在then和otherwise中返回包含目标列的结构体,最后用unnest()展开成独立列,只需写一次条件判断逻辑:

import polars as pl

so_df = pl.DataFrame({"low_limit": [1, 3, 0], "high_limit": [3, 4, 2], "value": [0, 5, 1]})

result = so_df.with_columns(
    pl.when(pl.col('value') > pl.col('high_limit'))
      .then(pl.struct(Flag=pl.lit("High"), Normality=pl.lit("Abnormal")))
      .when(pl.col('value') < pl.col('low_limit'))
      .then(pl.struct(Flag=pl.lit("Low"), Normality=pl.lit("Abnormal")))
      .otherwise(pl.struct(Flag=pl.lit("Within Range"), Normality=pl.lit("Normal")))
      .alias('temp_struct')
).unnest('temp_struct')

print(result)

执行后输出:

shape: (3, 5)
┌──────────┬───────────┬───────┬───────────────┬───────────┐
│ low_limit┆ high_limit┆ value ┆ Flag          ┆ Normality │
│ ---      ┆ ---       ┆ ---   ┆ ---           ┆ ---       │
│ i64      ┆ i64       ┆ i64   ┆ str           ┆ str       │
╞══════════╪═══════════╪═══════╪═══════════════╪═══════════╡
│ 1        ┆ 3         ┆ 0     ┆ Low           ┆ Abnormal  │
│ 3        ┆ 4         ┆ 5     ┆ High          ┆ Abnormal  │
│ 0        ┆ 2         ┆ 1     ┆ Within Range  ┆ Normal    │
└──────────┴───────────┴───────┴───────────────┴───────────┘

方法2:在with_columns中同时定义多列

直接在with_columns里为每个目标列单独编写条件逻辑,Polars的查询优化器会自动复用条件计算结果,不会重复执行判断:

import polars as pl

so_df = pl.DataFrame({"low_limit": [1, 3, 0], "high_limit": [3, 4, 2], "value": [0, 5, 1]})

result = so_df.with_columns(
    Flag=pl.when(pl.col('value') > pl.col('high_limit'))
           .then(pl.lit("High"))
           .when(pl.col('value') < pl.col('low_limit'))
           .then(pl.lit("Low"))
           .otherwise(pl.lit("Within Range")),
    Normality=pl.when((pl.col('value') > pl.col('high_limit')) | (pl.col('value') < pl.col('low_limit')))
                .then(pl.lit("Abnormal"))
                .otherwise(pl.lit("Normal"))
)

print(result)

输出和方法1完全一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 09:20:04