Ниже приведен пример того, что я пробовал.
Код: Выделить всё
import polars as pl
df = pl.DataFrame(
{
"foo": [1, 3, -2, -1, 1, 2],
"bar": [1, 1, 1, 1, 2, 2],
}
)
foo_is_neg = pl.col("foo") < 0
df.with_columns(
pl.when(foo_is_neg)
.then(pl.col("foo") / pl.col("foo").filter(foo_is_neg).sum())
.otherwise(pl.col("foo") / pl.col("foo").filter(~foo_is_neg).sum())
.over("bar")
.alias("foo2")
)
df
Код: Выделить всё
shape: (6, 3)
┌─────┬─────┬──────────┐
│ foo ┆ bar ┆ foo2 │
│ --- ┆ --- ┆ --- │
│ i64 ┆ i64 ┆ f64 │
╞═════╪═════╪══════════╡
│ 1 ┆ 1 ┆ 0.25 │
│ 3 ┆ 1 ┆ 0.75 │
│ -2 ┆ 1 ┆ 0.666667 │
│ -1 ┆ 1 ┆ 0.333333 │
│ 1 ┆ 2 ┆ 0.333333 │
│ 2 ┆ 2 ┆ 0.666667 │
└─────┴─────┴──────────┘
Спасибо за помощь!
Подробнее здесь: https://stackoverflow.com/questions/752 ... -in-polars
Мобильная версия