Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
pola-rs
GitHub Repository: pola-rs/polars
Path: blob/main/docs/source/src/python/user-guide/transformations/time-series/rolling.py
7891 views
1
# --8<-- [start:setup]
2
from datetime import date, datetime
3
4
import polars as pl
5
6
# --8<-- [end:setup]
7
8
# --8<-- [start:df]
9
df = pl.read_csv("docs/assets/data/apple_stock.csv", try_parse_dates=True)
10
df = df.sort("Date")
11
print(df)
12
# --8<-- [end:df]
13
14
# --8<-- [start:group_by]
15
annual_average_df = df.group_by_dynamic("Date", every="1y").agg(pl.col("Close").mean())
16
17
df_with_year = annual_average_df.with_columns(pl.col("Date").dt.year().alias("year"))
18
print(df_with_year)
19
# --8<-- [end:group_by]
20
21
# --8<-- [start:group_by_dyn]
22
df = (
23
pl.date_range(
24
start=date(2021, 1, 1),
25
end=date(2021, 12, 31),
26
interval="1d",
27
eager=True,
28
)
29
.alias("time")
30
.to_frame()
31
)
32
33
out = df.group_by_dynamic("time", every="1mo", period="1mo", closed="left").agg(
34
pl.col("time").cum_count().reverse().head(3).alias("day/eom"),
35
((pl.col("time") - pl.col("time").first()).last().dt.total_days() + 1).alias(
36
"days_in_month"
37
),
38
)
39
print(out)
40
# --8<-- [end:group_by_dyn]
41
42
# --8<-- [start:group_by_roll]
43
df = pl.DataFrame(
44
{
45
"time": pl.datetime_range(
46
start=datetime(2021, 12, 16),
47
end=datetime(2021, 12, 16, 3),
48
interval="30m",
49
eager=True,
50
),
51
"groups": ["a", "a", "a", "b", "b", "a", "a"],
52
}
53
)
54
print(df)
55
# --8<-- [end:group_by_roll]
56
57
# --8<-- [start:group_by_dyn2]
58
out = df.group_by_dynamic(
59
"time",
60
every="1h",
61
closed="both",
62
group_by="groups",
63
include_boundaries=True,
64
).agg(pl.len())
65
print(out)
66
# --8<-- [end:group_by_dyn2]
67
68