LazyGroupBy#
The LazyGroupBy class represents a grouped lazy computation. It is created by calling LazyFrame::groupBy() and provides methods to aggregate grouped data.
Methods#
agg#
Apply custom aggregation expressions.
- param array $expressions:
Array of
Polars\Exprobjects- returns:
LazyFrame
Example:
$result = $df->lazy()
->groupBy([Expr::col('group')])
->agg([
Expr::col('value')->sum(),
Expr::col('score')->mean(),
])
->collect();
all#
Aggregate all values of each group into lists.
Example:
$result = $df->lazy()
->groupBy([Expr::col('group')])
->all()
->collect();
count#
Count rows per group.
first#
Get the first row per group.
having#
Filter groups with predicates that are evaluated on the aggregated groups. Returns a new LazyGroupBy, so it can be chained before agg(); chained predicates are combined with AND.
- param array $predicates:
Array of
Polars\Exprobjects, typically aggregations (e.g.Expr::col('value')->sum()->gt(10))- returns:
LazyGroupBy
Example:
$result = $df->lazy()
->groupBy([Expr::col('group')])
->having([Expr::col('value')->sum()->gt(4)])
->agg([Expr::col('value')->sum()])
->collect();
head#
Get the first n rows per group.
last#
Get the last row per group.
len#
Return the number of rows in each group. The resulting column is named len, or $name when given.
- param string|null $name:
Assign a name to the resulting column
- returns:
LazyFrame
Example:
$result = $df->lazy()
->groupBy([Expr::col('group')])
->len('n')
->collect();
mapGroups#
Apply a custom function over each group as a new DataFrame. The callable receives a Polars\DataFrame per group and must return a Polars\DataFrame.
Warning
This method is much slower than the native expressions API: it materializes the whole DataFrame of each group and is opaque to the query optimizer. Prefer expressions when possible.
- param callable $function:
Function applied to each group, e.g.
fn(DataFrame $group) => $group->filter(...)- param array|null $schema:
Output schema as column name => dtype (dtype name string such as
'int64', or aPolars\DataTypeobject). If null, the input schema is assumed unchanged- returns:
LazyFrame
Example:
$result = $df->lazy()
->groupBy([Expr::col('group')])
->mapGroups(fn(DataFrame $group) => $group->filter(Expr::col('value')->gt(1)))
->collect();
max#
Maximum of all columns per group.
mean#
Mean of all numeric columns per group.
median#
Median of all numeric columns per group.
min#
Minimum of all columns per group.
nUnique#
Count the unique values per group.
quantile#
Compute the quantile per group.
- param int|float|string|bool|null|Expr $quantile:
Quantile between 0.0 and 1.0
- param QuantileMethod $interpolation:
Interpolation method (
QuantileMethod::Nearestby default)- returns:
LazyFrame
Example:
$result = $df->lazy()
->groupBy([Expr::col('group')])
->quantile(0.5, QuantileMethod::Linear)
->collect();
sum#
Sum all numeric columns per group.
tail#
Get the last n rows per group.