所以在Python Polars中
我可以使用类似的表达式添加一列或多列来创建新列
frame.with_columns((pl.col('colname1') + pl.col('colname2').alias('new_colname')))
但是,如果我在列表中包含所有列名称,有没有办法对该列表中的所有列求和并根据结果创建一个新列?
谢谢
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 │
└─────┴──────┴─────┴───────┘