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

如何用Polars的pl.when填充null列为同长度指定内容的列表?

Polars替换列表列中的Null值为对应长度的指定元素列表

我需要处理Polars DataFrame,将d列中的Null值替换为与c列列表长度相同、元素均为"no_value"的列表。示例DataFrame如下:

import polars as pl

df = pl.DataFrame({
    "a": ["one", "two"],
    "b": ["three", "four"],
    "c": [[1, 2], [3, 4]],
    "d": [[5, 6], None]
})

期望将d列的Null值替换为["no_value", "no_value"],得到目标结果。


可行解决方案

方法一:利用pl.repeat生成对应长度的列表

通过pl.repeat根据c列的列表长度生成目标列表,再转为列表类型匹配d列格式:

df = df.with_columns(
    d=pl.when(pl.col("d").is_null())
        .then(pl.repeat("no_value", n=pl.col("c").list.len()).list())
        .otherwise(pl.col("d"))
)

方法二:通过list.eval替换列表元素

对c列的每个列表元素统一替换为"no_value",自动生成与原列表等长的新列表:

df = df.with_columns(
    d=pl.when(pl.col("d").is_null())
        .then(pl.col("c").list.eval(pl.lit("no_value")))
        .otherwise(pl.col("d"))
)

之前尝试的错误原因

你之前的代码报错核心是混淆了Polars的表达式特性:

  • Polars的pl.col()返回的是延迟计算的表达式对象,不能用Python列表推导式直接迭代
  • 直接传入Python列表/Series会导致类型不匹配,Polars要求整列数据用统一的表达式逻辑处理

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 14:05:19