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

如何在Polars中用.select()基于列表实现多列逐元素乘积

Polars批量生成对应列乘积的实现方法

给定如下Polars DataFrame:

import polars as pl

the_df = pl.DataFrame({'x1': [1,1,1], 'x2': [2,2,2], 'y1': [1,1,1], 'y2': [2,2,2]})

以及列名列表xs = ['x1', 'x2']和ys = ['y1', 'y2'],要通过.select()方法批量生成对应列的乘积列(z1=x1y1、z2=x2y2),无需手动逐个编写表达式,可按以下方式实现:

方法一:基于列名配对生成表达式

利用zip()将xs和ys中的对应列名配对,循环生成乘积表达式并指定别名,再结合pl.all()保留原列:

xs = ['x1', 'x2']
ys = ['y1', 'y2']

# 批量生成乘积表达式
product_exprs = [
    pl.col(x_col) * pl.col(y_col)
    .alias(f"z{x_col[-1]}")  # 从x列名提取后缀生成z列名,如x1→z1
    for x_col, y_col in zip(xs, ys)
]

# 保留原列并添加新的乘积列
result_df = the_df.select([pl.all()] + product_exprs)
print(result_df)

执行后输出结果符合预期:

┌─────┬─────┬─────┬─────┬─────┬─────┐
│ x1  ┆ x2  ┆ y1  ┆ y2  ┆ z1  ┆ z2  │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ i64 ┆ i64 ┆ i64 ┆ i64 ┆ i64 ┆ i64 │
╞═════╪═════╪═════╪═════╪═════╪═════╡
│ 1   ┆ 2   ┆ 1   ┆ 2   ┆ 1   ┆ 4   │
│ 1   ┆ 2   ┆ 1   ┆ 2   ┆ 1   ┆ 4   │
│ 1   ┆ 2   ┆ 1   ┆ 2   ┆ 1   ┆ 4   │
└─────┴─────┴─────┴─────┴─────┴─────┘

方法二:按索引生成z列名

如果x列名无统一后缀规则,可通过索引顺序命名z列:

product_exprs = [
    pl.col(x_col) * pl.col(y_col).alias(f"z{i+1}")
    for i, (x_col, y_col) in enumerate(zip(xs, ys))
]

result_df = the_df.select([pl.all()] + product_exprs)

这种方式会按配对顺序生成z1、z2、z3...,不受原列名格式限制。

核心逻辑说明

  • zip(xs, ys)确保x列和y列一一对应,适配任意数量的列配对;
  • pl.all()保留原DataFrame的所有列,避免手动列举原列名;
  • 循环生成表达式的方式可轻松扩展到几十上百列的批量处理场景,无需重复编写代码。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 12:44:55