Code: Select all
import polars as pl
df = pl.DataFrame({
'g': [0, 0, 0, 1, 1, 1, 2, 2, 2, 3],
'j': [37, 87, 56, 28, 49, 65, 37, 91, 45, 95]
})
df = (
df.with_columns(rn=1)
.with_columns(
rn=pl.col('rn').shift().fill_null(0).cum_sum().over('g')
)
)
Code: Select all
┌─────┬─────┬─────┐
│ g ┆ j ┆ rn │
│ --- ┆ --- ┆ --- │
│ u32 ┆ i64 ┆ i32 │
╞═════╪═════╪═════╡
│ 0 ┆ 37 ┆ 0 │
│ 0 ┆ 87 ┆ 1 │
│ 0 ┆ 56 ┆ 2 │
│ 1 ┆ 28 ┆ 0 │
│ 1 ┆ 49 ┆ 1 │
│ 1 ┆ 65 ┆ 2 │
│ 2 ┆ 37 ┆ 0 │
│ 2 ┆ 91 ┆ 1 │
│ 2 ┆ 45 ┆ 2 │
│ 3 ┆ 95 ┆ 0 │
└─────┴─────┴─────┘
Code: Select all
.with_columns(rn=1)
.with_columns(
rn=pl.col('rn').shift().fill_null(0).cum_sum().over('g')
)
Code: Select all
.with_columns(rn=1)
Oder gibt es eine andere/bessere Möglichkeit, eine Zeilennummer pro Gruppe hinzuzufügen?
Mobile version