# `GeoFrame.GroupBy`
[🔗](https://github.com/CountlinkX-Solutions/geoframe/blob/v0.3.4/lib/geo_frame/group_by.ex#L1)

`group_by/2`, `ungroup/2`, `groups/1`, `summarise/3` and `group_map/4` for
`GeoFrame.GeoDataFrame`: grouped aggregation of attributes *and* geometry, and a function per group.

## Grouping state

`group_by/2` is `Explorer.DataFrame.group_by/2` on the attribute frame: the groups live in
`gdf.data` and `groups/1` reads them back. Grouped `head/2`, `tail/2`, `slice/3` and
`sample/2` act per group as Explorer's do (`head(grouped, 1)` is the first row of *each*
group; `head`, `tail` and `slice` return them in the original row order, as pandas'
`groupby.head` does, while `sample` lists group after group in an unspecified order) and the geometry always follows the rows Explorer picked. Geometry columns cannot be grouping keys.

## `summarise/3`

One row per group, in this order: the key columns, the aggregated attributes in the order
given, then the geometry (the active geometry column, aggregated by the `:geometry`
option) and any secondary geometry columns that were aggregated. The CRS of each geometry
column is kept. Rows are aligned by dense group ids computed once on the Elixir side, so
attribute and geometry row `i` always describe group `i`; every geometry aggregation runs
in a single NIF call over all groups.

`aggregations` is a keyword list (or map) `output_name: {function, source_column}`.

Attribute columns: `:sum`, `:mean`, `:median`, `:min`, `:max`, `:count` (non-null values),
`:first`, `:last` (the first / last *non-null* value, as pandas does; a group with only nulls
gives null), `:n_distinct` (distinct non-null values, as pandas `nunique`: unlike Explorer's `n_distinct`, a
null is not counted).

`:first` and `:last` skip nulls too (pandas semantics), which differs from
`Explorer.Series.first/1` and `Explorer.Series.last/1`: they return the first / last value even if it is
null.

Geometry columns (the active one or any secondary one): `:union_all`, `:intersection_all`,
`:collect` (`GeoFrame.GeoSeries.collect/2` of the group), `:envelope` (the box of the group's
total bounds), `:convex_hull` (of all the group's geometries), `:centroid` (the centroid of
the group's union: pandas has no grouped centroid, so it is defined this way; null when the
group mixes polygons, lines and points beyond what `union_all` supports), `:first`, `:last` (first / last non-null geometry)
produce a secondary geometry column named `output_name`; `:count` (non-null geometries)
produces an integer attribute. A group without geometries gives what the whole-series
method gives for none of them (`GEOMETRYCOLLECTION EMPTY` for the unions, intersection and
collect; null for the others).

Options:

  * `:geometry` - the aggregation of the active geometry column: any geometry function above
    except `:count`. Defaults to `:union_all`, so `summarise(group_by(gdf, by), [])` has the
    keys and geometry of `GeoFrame.Dissolve.dissolve/2`.
  * `:dropna` - `true` (default) drops rows with a null key; `false` keeps them as a group.
  * `:sort` - `true` (default) orders groups by key (nulls last), `false` by first appearance.

An ungrouped frame is one group. Raises `ArgumentError` for unknown columns or
aggregations, a geometry function on an attribute (or the reverse), or an output name that
repeats or clashes with a key or the geometry column.

## `group_map/4`

See `group_map/4`: the equivalent of pandas `groupby(by).apply(fun)`.

## Example

    gdf
    |> GeoFrame.GeoDataFrame.group_by("region")
    |> GeoFrame.GeoDataFrame.summarise(
      population: {:sum, "pop"},
      n: {:count, "pop"},
      hull: {:convex_hull, "geometry"}
    )

# `group_by`

```elixir
@spec group_by(GeoFrame.GeoDataFrame.t(), term()) :: GeoFrame.GeoDataFrame.t()
```

Marks the groups of `gdf`; see the module docs and `Explorer.DataFrame.group_by/2`.

# `group_map`

```elixir
@spec group_map(
  GeoFrame.GeoDataFrame.t(),
  term(),
  (GeoFrame.GeoDataFrame.t() -&gt;
     GeoFrame.GeoDataFrame.t() | Explorer.DataFrame.t()),
  keyword()
) :: GeoFrame.GeoDataFrame.t() | Explorer.DataFrame.t()
```

Calls `fun` once per group with the group's `GeoFrame.GeoDataFrame` and concatenates the
results, like pandas `groupby(by).apply(fun)`.

`by` is a column name or a list of names (as `group_by/2`); groups come in key order, with
the options of `summarise/3`:

  * `:sort` - `true` (default) orders groups by key (nulls last), `false` by first appearance.
  * `:dropna` - `true` (default) skips rows with a null key; `false` makes them a group.

The frame handed to `fun` is ungrouped, holds the rows of the group in their original order
and **keeps the key columns** (unlike pandas 3, which removes them and puts the keys in the
index). The result equals concatenating `fun` over `GeoFrame.GeoDataFrame.filter_with/2` per key.

`fun` returns a `GeoFrame.GeoDataFrame` or an `Explorer.DataFrame`, and every group must
return the same kind (a mix raises `ArgumentError`, as does any other value). GeoDataFrames must
share the first group's CRS and geometry column name (and the same secondary geometry
columns); a mismatch raises `ArgumentError` naming the group. The result is the
concatenation (`GeoFrame.GeoDataFrame.concat_rows/1`, or `Explorer.DataFrame.concat_rows/1`),
without groups.

There is no index, so pandas' `group_keys=True` (the keys prepended as an index) becomes:
key columns that `fun` dropped are **prepended as columns**, repeated for every row of
the group; key columns it kept are left where they are. Groups for which `fun` returns no
rows contribute nothing.

    GeoFrame.GeoDataFrame.group_map(gdf, "region", fn group ->
      GeoFrame.GeoDataFrame.head(group, 2)
    end)

# `groups`

```elixir
@spec groups(GeoFrame.GeoDataFrame.t()) :: [String.t()]
```

The names of the grouping columns, in grouping order.

# `summarise`

```elixir
@spec summarise(GeoFrame.GeoDataFrame.t(), keyword() | map(), keyword()) ::
  GeoFrame.GeoDataFrame.t()
```

Aggregates every group into one row; see the module docs.

# `ungroup`

```elixir
@spec ungroup(GeoFrame.GeoDataFrame.t(), term()) :: GeoFrame.GeoDataFrame.t()
```

Removes the groups (all, or the named ones); see `Explorer.DataFrame.ungroup/2`.

---

*Consult [api-reference.md](api-reference.md) for complete listing*
