如何用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
相关产品推荐
相关产品推荐

