Код: Выделить всё
import polars as pl
df = pl.DataFrame(
[
pl.Series("start", ["2023-01-01"], dtype=pl.Date).str.to_date(),
pl.Series("end", ["2024-01-01"], dtype=pl.Date).str.to_date(),
]
)
Код: Выделить всё
shape: (1, 2)
┌────────────┬────────────┐
│ start ┆ end │
│ --- ┆ --- │
│ date ┆ date │
╞════════════╪════════════╡
│ 2023-01-01 ┆ 2024-01-01 │
└────────────┴────────────┘
Код: Выделить всё
df = df.with_columns(
pl.date_range(pl.col("start"), pl.col("end"), "1mo", closed="left")
.implode()
.alias("date_range")
)
Код: Выделить всё
shape: (1, 3)
┌────────────┬────────────┬─────────────────────────────────┐
│ start ┆ end ┆ date_range │
│ --- ┆ --- ┆ --- │
│ date ┆ date ┆ list[date] │
╞════════════╪════════════╪═════════════════════════════════╡
│ 2023-01-01 ┆ 2024-01-01 ┆ [2023-01-01, 2023-02-01, … 202… │
└────────────┴────────────┴─────────────────────────────────┘
Код: Выделить всё
df = df.with_columns(
pl.col("date_range")
.list.eval(
pl.struct(
{
"year": pl.element().dt.year(),
"month": pl.element().dt.month(),
}
)
)
.alias("years_months")
)
Возможно, мне не следует включать вывод date_range в список , но я также не уверен, как создать структуру непосредственно из ее результата.
Моя лучшая идея — та, которая мне не нравится, потому что мне приходится неоднократно вызывать pl.list.eval< /code>:
Код: Выделить всё
df = (
df.with_columns(
pl.col("date_range").list.eval(pl.element().dt.year()).alias("year"),
pl.col("date_range").list.eval(pl.element().dt.month()).alias("month"),
)
.drop("start", "end", "date_range")
.explode("year", "month")
.select(pl.struct("year", "month"))
)
df
Подробнее здесь: https://stackoverflow.com/questions/787 ... ing-a-list
Мобильная версия