我正在尝试使用polars
数据框来选择每组的first
第一last
行。这是一个选择每组第一行的简单示例:
import polars as pl
df = pl.DataFrame(
{
"a": [1, 2, 2, 3, 4, 5],
"b": [0.5, 0.5, 4, 10, 14, 13],
"c": [True, True, True, False, False, True],
"d": ["Apple", "Apple", "Apple", "Banana", "Banana", "Banana"],
}
)
result = df.group_by("d", maintain_order=True).first()
print(result)
输出:
shape: (2, 4)
┌────────┬─────┬──────┬───────┐
│ d ┆ a ┆ b ┆ c │
│ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ i64 ┆ f64 ┆ bool │
╞════════╪═════╪══════╪═══════╡
│ Apple ┆ 1 ┆ 0.5 ┆ true │
│ Banana ┆ 3 ┆ 10.0 ┆ false │
└────────┴─────┴──────┴───────┘
这个方法很好,我们可以用.last
它来处理最后一行。但是我们如何将它们合并在一起呢group_by
?