我正在尝试使用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
?
作为列
您可以使用
agg
,您必须添加suffix
(或prefix
)来区分列名称:输出:
作为行
如果您想要多行,那么您需要
concat
:输出:
或者
filter
使用int_range
+over
:输出:
@mozway 的解决方案很有效!为了完整起见,我还想分享两个依赖于 的解决方案
pl.Expr.gather
。在选定上下文中
在 group-by 上下文中
性能注意事项
我还对这些方法进行了初步计时(在微小的示例数据集上)。
group_by
+concat
filter
group_by
+gather
select
+gather
有专用的第一个/最后一个方法。
.is_first_distinct()
.is_last_distinct()
如果组标识符是多列,则可以使用结构体。