Код: Выделить всё
data = {'id': [1, 1, 1, 2, 2, 2],
'd': [1, 2, 3, 1, 2, 3],
'sales': [1, 4, 2, 3, 1, 2]}
С помощью SQL я могу это сделать:< /p>
Код: Выделить всё
duckdb.sql("""
select *, sum(sales) over w as rolling_sales
from df
window w as (partition by id order by d rows between 1 preceding and current row)
""")
Out[21]:
┌───────┬───────┬───────┬───────────────┐
│ id │ d │ sales │ rolling_sales │
│ int64 │ int64 │ int64 │ int128 │
├───────┼───────┼───────┼───────────────┤
│ 1 │ 1 │ 1 │ 1 │
│ 1 │ 2 │ 4 │ 5 │
│ 1 │ 3 │ 2 │ 6 │
│ 2 │ 1 │ 3 │ 3 │
│ 2 │ 2 │ 1 │ 4 │
│ 2 │ 3 │ 2 │ 3 │
└───────┴───────┴───────┴───────────────┘
Я дошел до
Код: Выделить всё
rel = duckdb.sql('select * from df')
rel.sum(
'sales',
projected_columns='*',
window_spec='over (partition by id order by d rows between 1 preceding and current row)'
)
Код: Выделить всё
┌───────────────────────────────────────────────────────────────────────────────────────┐
│ sum(sales) OVER (PARTITION BY id ORDER BY d ROWS BETWEEN 1 PRECEDING AND CURRENT ROW) │
│ int128 │
├───────────────────────────────────────────────────────────────────────────────────────┤
│ 3 │
│ 4 │
│ 3 │
│ 1 │
│ 5 │
│ 6 │
└───────────────────────────────────────────────────────────────────────────────────────┘
Подробнее здесь: https://stackoverflow.com/questions/791 ... tional-api