Ich möchte mit pl.when.then.otherwise eine neue Spalte zu einem Datenrahmen hinzufügen, aber ich bin verwirrt, wenn die neue Spalte den Typ einer vorhandenen Spalte „erbt“ und wenn nicht.
Ein Beispieldatenrahmen:
Code: Select all
import polars as pl
df = pl.DataFrame({"a": ["x", "y"], "b": [1, 2]}, schema={"a": pl.String, "b": pl.String})
df
Out:
┌─────┬─────┐
│ a ┆ b │
│ --- ┆ --- │
│ str ┆ u8 │
╞═════╪═════╡
│ x ┆ 1 │
│ y ┆ 2 │
└─────┴─────┘
Code: Select all
df.with_columns(
pl.when(pl.col("a") == "x")
.then(pl.col("b"))
.otherwise(5)
)
Out:
┌─────┬─────┐
│ a ┆ b │
│ --- ┆ --- │
│ str ┆ u8 │
╞═════╪═════╡
│ x ┆ 1 │
│ y ┆ 5 │
└─────┴─────┘
Code: Select all
df.with_columns(
pl.when(pl.col("a") == "x")
.then(pl.col("b"))
.when(pl.col("a") == "y")
.then(0)
.otherwise(5)
)
Out:
┌─────┬─────┐
│ a ┆ b │
│ --- ┆ --- │
│ str ┆ i32 │ #
Mobile version