Ich verwende .map_elements< /code>, um eine komplexe Python-Funktion auf jedes Element einer Polarenreihe anzuwenden. Dies ist ein Spielzeugbeispiel:
Code: Select all
import polars as pl
df = pl.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]})
def sum_cols(row):
return row["A"] + row["B"]
df.with_columns(
pl.struct(pl.all())
.map_elements(sum_cols, return_dtype=pl.Int32).alias("summed")
)
shape: (3, 3)
┌─────┬─────┬────────┐
│ A ┆ B ┆ summed │
│ --- ┆ --- ┆ --- │
│ i64 ┆ i64 ┆ i32 │
╞═════╪═════╪════════╡
│ 1 ┆ 4 ┆ 5 │
│ 2 ┆ 5 ┆ 7 │
│ 3 ┆ 6 ┆ 9 │
└─────┴─────┴────────┘
Code: Select all
def sum_cols(row):
raise Exception
return row["A"] + row["B"]
df.with_columns(
pl.struct(pl.all())
.map_elements(sum_cols, return_dtype=pl.Int32).alias("summed")
)
shape: (3, 3)
┌─────┬─────┬────────┐
│ A ┆ B ┆ summed │
│ --- ┆ --- ┆ --- │
│ i64 ┆ i64 ┆ i32 │
╞═════╪═════╪════════╡
│ 1 ┆ 4 ┆ null │
│ 2 ┆ 5 ┆ null │
│ 3 ┆ 6 ┆ null │
└─────┴─────┴────────┘