Код: Выделить всё
import polars as pl
df = pl.DataFrame(
[
pl.Series(
"name", ["A", "B", "C", "D"], dtype=pl.Enum(["A", "B", "C", "D"])
),
pl.Series("month", [1, 2, 12, 1], dtype=pl.Int8()),
pl.Series(
"category", ["x", "x", "y", "z"], dtype=pl.Enum(["x", "y", "z"])
),
]
)
print(df)
Код: Выделить всё
shape: (4, 3)
┌──────┬───────┬──────────┐
│ name ┆ month ┆ category │
│ --- ┆ --- ┆ --- │
│ enum ┆ i8 ┆ enum │
╞══════╪═══════╪══════════╡
│ A ┆ 1 ┆ x │
│ B ┆ 2 ┆ x │
│ C ┆ 12 ┆ y │
│ D ┆ 1 ┆ z │
└──────┴───────┴──────────┘
Код: Выделить всё
from math import inf
binned_df = (
df.select(
pl.col.month.hist(
bins=[x + 1 for x in range(11)],
include_breakpoint=True,
).alias("binned"),
)
.unnest("binned")
.with_columns(
pl.col.breakpoint.map_elements(
lambda x: 12 if x == inf else x, return_dtype=pl.Float64()
)
.cast(pl.Int8())
.alias("month")
)
.drop("breakpoint")
.select("month", "count")
)
print(binned_df)
Код: Выделить всё
shape: (12, 2)
┌───────┬───────┐
│ month ┆ count │
│ --- ┆ --- │
│ i8 ┆ u32 │
╞═══════╪═══════╡
│ 1 ┆ 2 │
│ 2 ┆ 1 │
│ 3 ┆ 0 │
│ 4 ┆ 0 │
│ 5 ┆ 0 │
│ … ┆ … │
│ 8 ┆ 0 │
│ 9 ┆ 0 │
│ 10 ┆ 0 │
│ 11 ┆ 0 │
│ 12 ┆ 1 │
└───────┴───────┘
Предположим, я хочу сгруппировать данные по столбцу «Категория». Я могу сделать следующее:
Код: Выделить всё
# initialize an empty dataframe
category_binned_df = pl.DataFrame()
for cat in df["category"].unique():
# repeat the binning logic from earlier, except on a dataframe filtered for
# the particular category we are iterating over
binned_df = (
df.filter(pl.col.category.eq(cat)) #
Подробнее здесь: [url]https://stackoverflow.com/questions/79104005/using-hist-to-bin-data-while-grouping-with-over[/url]