
本文介绍使用 Polars 原生方法(如 with_columns() 配合 pl.lit())向现有 DataFrame 批量添加空列,避免低效的 cross join 操作,提升代码可读性与执行性能。
本文介绍使用 polars 原生方法(如 `with_columns()` 配合 `pl.lit()`)向现有 dataframe 批量添加空列,避免低效的 cross join 操作,提升代码可读性与执行性能。
在 Polars 中为已有 DataFrame 添加多个新列(尤其是空值或默认值列),最直观但不推荐的做法是构造一个新 DataFrame 并执行 join(how='cross') —— 这不仅语义不清(cross join 本意是笛卡尔积),还会引入冗余计算和内存开销,且当原 DataFrame 行数较多时极易导致性能陡降。
更符合 Polars 函数式、惰性求值设计哲学的方式是使用 .with_columns() 方法配合字面量表达式 pl.lit()。pl.lit() 可将 Python 字面量(如 ''、None、0、False 等)封装为 Polars 表达式(Expression),再通过 .alias() 指定列名,从而实现“零成本”列扩展。
以下是最简洁、推荐的写法:
import polars as pl
df = pl.DataFrame({'a': [1, 2, 3]})
mylist = [f'col{i}' for i in range(1, 4)]
# ✅ 推荐:一行完成多列添加,类型自动推断
result = df.with_columns(
pl.lit('').alias(col) for col in mylist
)
print(result)
输出:
shape: (3, 4) ┌─────┬──────┬──────┬──────┐ │ a ┆ col1 ┆ col2 ┆ col3 │ │ --- ┆ --- ┆ --- ┆ --- │ │ i64 ┆ str ┆ str ┆ str │ ╞═════╪══════╪══════╪══════╡ │ 1 ┆ ┆ ┆ │ │ 2 ┆ ┆ ┆ │ │ 3 ┆ ┆ ┆ │ └─────┴──────┴──────┴──────┘
? 类型说明:pl.lit('') 默认推断为 StringType;若需显式控制类型(例如添加 null 列并指定为 Int64),可结合 pl.lit(None).cast(pl.Int64) 使用。
你也可以用 map() 替代生成器表达式(功能等价,风格略有差异):
df.with_columns(map(lambda col: pl.lit('').alias(col), mylist))
# 或更函数式写法(需注意 map 返回迭代器,在 with_columns 中需确保被消费)
df.with_columns(*map(lambda col: pl.lit('').alias(col), mylist)) # 加 * 展开
⚠️ 注意事项:
- pl.lit() 生成的是标量广播表达式:其值会自动广播至 DataFrame 的每一行,无需手动构造长度匹配的列表;
- 避免使用 pl.Series 或 pl.DataFrame 构造后再 join —— 这违背了 Polars “列优先” 和“表达式驱动”的核心范式;
- 若需添加不同默认值(如 col1 → 0, col2 → 'N/A'),可改用字典映射 + 解包:
defaults = {'col1': 0, 'col2': 'N/A', 'col3': None} df.with_columns(pl.lit(v).alias(k) for k, v in defaults.items())
总之,df.with_columns(pl.lit(...).alias(...)) 是 Polars 中添加空列/默认列的标准、高效且语义清晰的方式,应作为首选方案。










