如何在Polars LazyFrame中拼接含NULL的pl.List[str]列?
解决Polars LazyFrame中列表列NULL填充与多列表拼接问题
一、为List[str]类型列的NULL填充空列表
你之前的尝试错误在于使用了pl.List("")或pl.List([])作为填充值——pl.List是类型构造器,并非创建空列表字面量的方法。正确的做法是用pl.lit([])生成空列表字面量,若需明确类型可搭配cast:
import polars as pl # 示例LazyFrame lf = pl.LazyFrame({ "col1": [["a", "b"], None, ["c"]], "col2": [None, ["d"], None], "col3": [["e"], ["f", "g"], None] }).with_columns( # 为每个列表列填充空列表 pl.col("col1").fill_null(pl.lit([])).alias("col1_filled"), pl.col("col2").fill_null(pl.lit([])).cast(pl.List(str)).alias("col2_filled"), # 显式指定类型 pl.col("col3").fill_null(pl.lit([])).alias("col3_filled") )
二、多列表拼接的最优方式
处理完NULL值后,有三种常用的拼接方式:
1. 使用pl.concat_list(简洁直观)
直接将填充后的列传入pl.concat_list,即可得到无NULL干扰的拼接结果:
lf = lf.with_columns( pl.concat_list(["col1_filled", "col2_filled", "col3_filled"]).alias("combined") )
2. 使用arr.concat链式调用(灵活扩展)
若需逐步拼接或处理复杂逻辑,可使用列表列的arr.concat方法:
lf = lf.with_columns( pl.col("col1_filled") .arr.concat(pl.col("col2_filled")) .arr.concat(pl.col("col3_filled")) .alias("combined") )
3. 使用pl.fold(适合大量列拼接)
当需要拼接的列数量较多时,pl.fold可避免重复代码,还能在拼接过程中直接处理NULL:
lf = lf.with_columns( pl.fold( acc=pl.lit([]), function=lambda acc, x: acc.arr.concat(x.fill_null(pl.lit([]))), exprs=["col1", "col2", "col3"] ).alias("combined") )
完整合并示例
将填充与拼接逻辑合并,一步到位:
import polars as pl lf = pl.LazyFrame({ "col1": [["a", "b"], None, ["c"]], "col2": [None, ["d"], None], "col3": [["e"], ["f", "g"], None] }).with_columns( pl.concat_list( pl.col(col).fill_null(pl.lit([])) for col in ["col1", "col2", "col3"] ).alias("combined") ) # 执行并查看结果 print(lf.collect())
输出结果:
shape: (3, 4) ┌───────────┬───────────┬───────────┬─────────────────────┐ │ col1 ┆ col2 ┆ col3 ┆ combined │ │ --- ┆ --- ┆ --- ┆ --- │ │ list[str] ┆ list[str] ┆ list[str] ┆ list[str] │ ╞═══════════╪═══════════╪═══════════╪═════════════════════╡ │ ["a", "b"]┆ null ┆ ["e"] ┆ ["a", "b", "e"] │ │ null ┆ ["d"] ┆ ["f", "g"]┆ ["d", "f", "g"] │ │ ["c"] ┆ null ┆ null ┆ ["c"] │ └───────────┴───────────┴───────────┴─────────────────────┘
内容的提问来源于stack exchange,提问作者SysRIP
相关产品推荐
相关产品推荐

