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

如何在Polars中用when-then-otherwise条件替换指定列值?

问题:根据字符串匹配替换DataFrame列值

需求:

  • 检查数据集的A列是否包含子串"foo"
  • 若A列字符串匹配"foo",将L列的值替换为G列的值
  • 若不匹配,保持L列原数值不变

示例数据集

import polars as pl

df = pl.DataFrame(
        {
            "A": ["foo1", "ham", "foo2", "egg"],
            "L": ["A54", "A12", "B84", "C12"],
            "G": ["X34", "C84", "G96", "L6"],
        }
    )
print(df)

输出:

shape: (4, 3)
┌──────┬─────┬─────┐
│ A    ┆ L   ┆ G   │
│ ---  ┆ --- ┆ --- │
│ str  ┆ str ┆ str │
╞══════╪═════╪═════╡
│ foo1 ┆ A54 ┆ X34 │
│ ham  ┆ A12 ┆ C84 │
│ foo2 ┆ B84 ┆ G96 │
│ egg  ┆ C12 ┆ L6  │
└──────┴─────┴─────┘

期望输出

shape: (4, 3)
┌──────┬─────┬─────┐
│ A    ┆ L   ┆ G   │
│ ---  ┆ --- ┆ --- │
│ str  ┆ str ┆ str │
╞══════╪═════╪═════╡
│ foo1 ┆ X34 ┆ X34 │
│ ham  ┆ A12 ┆ C84 │
│ foo2 ┆ G96 ┆ G96 │
│ egg  ┆ C12 ┆ L6  │
└──────┴─────┴─────┘

错误代码分析

你写的代码存在两个问题:

  1. 逻辑颠倒:需求是替换L列,但代码里尝试修改的是G列,且then中使用pl.col("L")完全不符合需求逻辑
  2. 语法错误:.alias("G")的位置错误,应该放在.otherwise()之后,否则会中断when/then/otherwise的链式调用

错误代码:

df = df.with_columns(
            pl.when(
                pl.col("A")
                .str.contains("foo"))
            .then(pl.col("L"))
            .alias("G")
            .otherwise(pl.col("G"))
        )

正确代码

我们需要以L列为目标列,当A列包含"foo"时用G列的值填充,否则保留L列原值:

df = df.with_columns(
    pl.when(pl.col("A").str.contains("foo"))
    .then(pl.col("G"))
    .otherwise(pl.col("L"))
    .alias("L")
)

print(df)

运行这段代码即可得到预期结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 22:48:20