根据极坐标列表中的列名称对列求和

问题描述 投票:0回答:1

所以在Python Polars中

我可以使用类似的表达式添加一列或多列来创建新列

frame.with_columns((pl.col('colname1') + pl.col('colname2').alias('new_colname')))

但是,如果我在列表中包含所有列名称,有没有办法对该列表中的所有列求和并根据结果创建一个新列?

谢谢

python-polars
1个回答
3
投票

您可以使用

pl.sum_horizontal()

import polars as pl

df = pl.DataFrame({"a": [1, 2, 3], "b": [1, 2, None], "c": [4, 5, 6]})
cols = ["a", "b"]

df.with_columns(pl.sum_horizontal(cols).alias("a + b"))
shape: (3, 4)
┌─────┬──────┬─────┬───────┐
│ a   ┆ b    ┆ c   ┆ a + b │
│ --- ┆ ---  ┆ --- ┆ ---   │
│ i64 ┆ i64  ┆ i64 ┆ i64   │
╞═════╪══════╪═════╪═══════╡
│ 1   ┆ 1    ┆ 4   ┆ 2     │
│ 2   ┆ 2    ┆ 5   ┆ 4     │
│ 3   ┆ null ┆ 6   ┆ 3     │
└─────┴──────┴─────┴───────┘
© www.soinside.com 2019 - 2024. All rights reserved.