Эффективный повторный анализ серии строк (в кадре данных) в структуру, преобразование полей структуры и последующее ее вPython

Программы на Python
Anonymous
Эффективный повторный анализ серии строк (в кадре данных) в структуру, преобразование полей структуры и последующее ее в

Сообщение Anonymous »

Рассмотрим следующий игрушечный пример:

Код: Выделить всё

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   │
└──────┴───────┘
Я думаю, что было бы более эффективно выполнять операции с уникальной серией данных даты (я мог бы использовать map_dict, но я выбрал join для нет веской причины):

Код: Выделить всё

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

Вернуться в «Python»