Пример фрейма данных:
Код: Выделить всё
data = {
"ID" : [1, 1, 2,2,3,3],
"Action" : ["A", "A", "B", "B", "A", "A"],
"Where" : ["Office", "Home", "Home", "Office", "Home", "Home"],
"Value" : [1, 2, 3, 4, 5, 6]
}
df = pl.DataFrame(data)
Я использую следующий подход:
Код: Выделить всё
(
df
.select(
pl.col("ID"),
pl.col("Action"),
pl.col("Where"),
TOP = pl.col("Value").max().over(["ID", "Action"]))
)
Код: Выделить всё
(
df
.select(
pl.col("ID"),
pl.col("Action"),
pl.col("Where"),
TOP = pl.col("Value").max().over(["ID", "Action"]))
.sort(
pl.col("*"), descending =True
)
.unique(
subset = ["ID", "Action"],
maintain_order = True,
keep = "first"
)
)
Код: Выделить всё
shape: (3, 4)
┌─────┬────────┬────────┬─────┐
│ ID ┆ Action ┆ Where ┆ TOP │
│ --- ┆ --- ┆ --- ┆ --- │
│ i64 ┆ str ┆ str ┆ i64 │
╞═════╪════════╪════════╪═════╡
│ 3 ┆ A ┆ Home ┆ 6 │
│ 2 ┆ B ┆ Office ┆ 4 │
│ 1 ┆ A ┆ Office ┆ 2 │
└─────┴────────┴────────┴─────┘
Код: Выделить всё
shape: (3, 4)
┌─────┬────────┬────────┬─────┐
│ ID ┆ Action ┆ Where ┆ TOP │
│ --- ┆ --- ┆ --- ┆ --- │
│ i64 ┆ str ┆ str ┆ i64 │
╞═════╪════════╪════════╪═════╡
│ 3 ┆ A ┆ Home ┆ 6 │
│ 2 ┆ B ┆ Office ┆ 4 │
│ 1 ┆ A ┆ Home ┆ 2 │
└─────┴────────┴────────┴─────┘
Подробнее здесь: https://stackoverflow.com/questions/789 ... categories