让我们从这个 DataFrame 开始:
import polars as pl
df = pl.DataFrame(
{
"col1": [1, 2, 3, 4, 5],
}
)
print(df)
shape: (5, 1)
┌──────┐
│ col1 │
│ --- │
│ i64 │
╞══════╡
│ 1 │
├╌╌╌╌╌╌┤
│ 2 │
├╌╌╌╌╌╌┤
│ 3 │
├╌╌╌╌╌╌┤
│ 4 │
├╌╌╌╌╌╌┤
│ 5 │
└──────┘
添加标量(单个值)
Use polars.lit https://pola-rs.github.io/polars/py-polars/html/reference/api/polars.lit.html#polars.lit.
my_scalar = -1
df.with_column(pl.lit(my_scalar).alias("col_scalar"))
shape: (5, 2)
┌──────┬────────────┐
│ col1 ┆ col_scalar │
│ --- ┆ --- │
│ i64 ┆ i32 │
╞══════╪════════════╡
│ 1 ┆ -1 │
├╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌┤
│ 2 ┆ -1 │
├╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌┤
│ 3 ┆ -1 │
├╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌┤
│ 4 ┆ -1 │
├╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌┤
│ 5 ┆ -1 │
└──────┴────────────┘
您还可以使用以下命令选择新列的数据类型dtype
关键词。
df.with_column(pl.lit(my_scalar, dtype=pl.Float64).alias("col_scalar_float"))
shape: (5, 2)
┌──────┬──────────────────┐
│ col1 ┆ col_scalar_float │
│ --- ┆ --- │
│ i64 ┆ f64 │
╞══════╪══════════════════╡
│ 1 ┆ -1.0 │
├╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ 2 ┆ -1.0 │
├╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ 3 ┆ -1.0 │
├╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ 4 ┆ -1.0 │
├╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ 5 ┆ -1.0 │
└──────┴──────────────────┘
添加列表
要添加值列表(可能来自某些外部计算),请使用极地系列 https://pola-rs.github.io/polars/py-polars/html/reference/api/polars.Series.html#polars.Series构造函数并为 Series 构造函数提供名称。
my_list = [10, 20, 30, 40, 50]
df.with_column(pl.Series(name="col_list", values=my_list))
shape: (5, 2)
┌──────┬──────────┐
│ col1 ┆ col_list │
│ --- ┆ --- │
│ i64 ┆ i64 │
╞══════╪══════════╡
│ 1 ┆ 10 │
├╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┤
│ 2 ┆ 20 │
├╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┤
│ 3 ┆ 30 │
├╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┤
│ 4 ┆ 40 │
├╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┤
│ 5 ┆ 50 │
└──────┴──────────┘
您可以使用dtype
如果需要,关键字可以控制新系列的数据类型。
df.with_column(pl.Series(name="col_list", values=my_list, dtype=pl.Float64))
shape: (5, 2)
┌──────┬──────────┐
│ col1 ┆ col_list │
│ --- ┆ --- │
│ i64 ┆ f64 │
╞══════╪══════════╡
│ 1 ┆ 10.0 │
├╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┤
│ 2 ┆ 20.0 │
├╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┤
│ 3 ┆ 30.0 │
├╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┤
│ 4 ┆ 40.0 │
├╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┤
│ 5 ┆ 50.0 │
└──────┴──────────┘
添加系列
如果您已经有一个系列,您只需提供其参考即可。
my_series = pl.Series(name="my_series_name", values=[10, 20, 30, 40, 50])
df.with_column(my_series)
shape: (5, 2)
┌──────┬────────────────┐
│ col1 ┆ my_series_name │
│ --- ┆ --- │
│ i64 ┆ i64 │
╞══════╪════════════════╡
│ 1 ┆ 10 │
├╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ 2 ┆ 20 │
├╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ 3 ┆ 30 │
├╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ 4 ┆ 40 │
├╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ 5 ┆ 50 │
└──────┴────────────────┘
如果您的系列还没有名称,您可以使用alias
表达。
my_series_no_name = pl.Series(values=[10, 20, 30, 40, 50])
df.with_column(my_series_no_name.alias('col_no_name'))
shape: (5, 2)
┌──────┬─────────────┐
│ col1 ┆ col_no_name │
│ --- ┆ --- │
│ i64 ┆ i64 │
╞══════╪═════════════╡
│ 1 ┆ 10 │
├╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ 2 ┆ 20 │
├╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ 3 ┆ 30 │
├╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ 4 ┆ 40 │
├╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ 5 ┆ 50 │
└──────┴─────────────┘