如何在Polars中展开含缺失值的多列表列?
Polars处理含Null列表列的多列爆炸问题
给定如下Polars DataFrame:
import polars as pl df = pl.DataFrame({ "x": [[1], [1, 2], [1, 2, 3]], "y": [[True], None, [True, False, True]] })
其结构为:
shape: (3, 2) ┌───────────┬─────────────────────┐ │ x ┆ y │ │ --- ┆ --- │ │ list[i64] ┆ list[bool] │ ╞═══════════╪═════════════════════╡ │ [1] ┆ [true] │ │ [1, 2] ┆ null │ │ [1, 2, 3] ┆ [true, false, true] │ └───────────┴─────────────────────┘
直接调用df.explode("x", "y")会抛出ShapeError: exploded columns must have matching element counts错误,因为第二行的y为Null,无法和x的列表长度匹配。我们需要实现的效果是:当y为Null时,爆炸后对应行填充Null,最终得到如下输出:
shape: (6, 2) ┌─────┬───────┐ │ x ┆ y │ │ --- ┆ --- │ │ i64 ┆ bool │ ╞═════╪═══════╡ │ 1 ┆ true │ │ 1 ┆ null │ │ 2 ┆ null │ │ 1 ┆ true │ │ 2 ┆ false │ │ 3 ┆ true │ └─────┴───────┘
解决方案
核心思路是将y列中的Null值替换为与对应x列列表长度一致的Null元素列表,确保两列列表长度匹配后再执行爆炸操作:
import polars as pl df = pl.DataFrame({ "x": [[1], [1, 2], [1, 2, 3]], "y": [[True], None, [True, False, True]] }) # 处理y列的Null值,生成与x长度匹配的Null列表 processed_df = df.with_columns( pl.when(pl.col("y").is_null()) .then(pl.col("x").list.eval(pl.lit(None)).alias("y")) .otherwise(pl.col("y")) ) # 执行多列爆炸 result = processed_df.explode("x", "y") print(result)
代码解释
pl.col("x").list.eval(pl.lit(None)):对x列的每个列表,生成一个长度相同、元素全为Null的列表,完美匹配x的长度。- 通过
when/then/otherwise分支逻辑,仅处理y为Null的行,保留原有非Null的列表内容。 - 处理完成后,两列的列表长度完全对应,此时调用
explode即可得到期望结果。
内容的提问来源于stack exchange,提问作者Brian Braddock
相关产品推荐
相关产品推荐

