Код: Выделить всё
import polars as pl
xs = pl.DataFrame(
[
pl.Series(
"date",
["2024 Jan", "2024 Feb", "2024 Jan", "2024 Jan"],
dtype=pl.String,
)
]
)
ys = (
xs.with_columns(
pl.col("date").str.split(" ").list.to_struct(fields=["year", "month"]),
)
.with_columns(
pl.col("date").struct.with_fields(pl.field("year").cast(pl.Int16()))
)
.unnest("date")
)
ys
Код: Выделить всё
shape: (4, 2)
┌──────┬───────┐
│ year ┆ month │
│ --- ┆ --- │
│ i16 ┆ str │
╞══════╪═══════╡
│ 2024 ┆ Jan │
│ 2024 ┆ Feb │
│ 2024 ┆ Jan │
│ 2024 ┆ Jan │
└──────┴───────┘
Код: Выделить всё
unique_dates = (
pl.DataFrame([xs["date"].unique()])
.with_columns(
pl.col("date")
.str.split(" ")
.list.to_struct(fields=["year", "month"])
.alias("struct_date")
)
.with_columns(
pl.col("struct_date").struct.with_fields(
pl.field("year").cast(pl.Int16())
)
)
)
unique_dates
Код: Выделить всё
shape: (2, 2)
┌──────────┬──────────────┐
│ date ┆ struct_date │
│ --- ┆ --- │
│ str ┆ struct[2] │
╞══════════╪══════════════╡
│ 2024 Jan ┆ {2024,"Jan"} │
│ 2024 Feb ┆ {2024,"Feb"} │
└──────────┴──────────────┘
Код: Выделить всё
zs = (
xs.join(unique_dates, on="date", left_on="date", right_on="struct_date")
.drop("date")
.rename({"struct_date": "date"})
.unnest("date")
)
zs
Код: Выделить всё
shape: (4, 2)
┌──────┬───────┐
│ year ┆ month │
│ --- ┆ --- │
│ i16 ┆ str │
╞══════╪═══════╡
│ 2024 ┆ Jan │
│ 2024 ┆ Feb │
│ 2024 ┆ Jan │
│ 2024 ┆ Jan │
└──────┴───────┘
Подробнее здесь: https://stackoverflow.com/questions/786 ... casting-th