# groupBy

> For the complete documentation index, see [llms.txt](https://kotlin.github.io/dataframe/llms.txt).

Splits the rows of [DataFrame](dataframe.html) into groups using one or several columns as grouping keys.

API reference: [groupBy](https://kotlin.github.io/dataframe/api-docs/core/org.jetbrains.kotlinx.dataframe.api/group-by.html), [GroupBy](https://kotlin.github.io/dataframe/api-docs/core/org.jetbrains.kotlinx.dataframe.api/-group-by/index.html)

The `groupBy` function returns a `GroupBy` object. A `GroupBy` is a dataframe-like structure that contains one or more key columns and a `group` [FrameColumn](datacolumn.html#framecolumn). Key columns contain all unique combinations of key values, and the `group` [FrameColumn](datacolumn.html#framecolumn) contains the corresponding groups of rows (each represented as a [DataFrame](dataframe.html)). Each row in a `GroupBy` corresponds to a keys/group combination.

```TEXT
groupBy(moveToTop = true) { columns }
      [ transformations ]
      reducer | aggregator | pivot | mapper

transformations = [ .sortByGroup { expression } | .sortByGroupDesc { expression } | .sortByCount() | .sortByCountAsc() | .sortByKey() | .sortByKeyDesc() | .sortBy { columns } | .sortByDesc { columns } ]
                  [ .updateGroups { frameExpression } ]
                  [ .filter { rowExpression } ]
                  [ .add(column) { rowExpression } ]
    
reducer = .minBy { column } | .maxBy { column } | .medianBy { rowExpression } | .percentileBy(percentile) { rowExpression } | .first [ { rowCondition } ] | .last [ { rowCondition } ] 
          .concat() | .into([column]) [{ rowExpression }] | .values { valueColumns } 

aggregator = .count() | .countDistinct() | .concat() | .concatWithKeys() | .toDataFrame() | .into([column]) [{ rowExpression }] | .values { valueColumns } | .aggregate { aggregations } | .<stat> [ { columns } ]

mapper = .map { GroupWithKey -> value } | .mapToRows { GroupWithKey -> DataRow? } | .mapToFrames { GroupWithKey -> DataFrame }

pivot = .pivot { columns }
      [ .default(defaultValue) ]
         pivotReducer | pivotAggregator
```

See [column selectors](columnselectors.html) for how to select the columns for this operation, [groupBy transformations](#transformation), [groupBy reducing](#reducing), [groupBy aggregations](#aggregation), [groupBy mapping](#mapping), and [pivot+groupBy](pivot.html#pivot-groupby).

```KOTLIN
df
```

[Embedded content](./resources/groupByDf.html)

Properties:

```KOTLIN
df.groupBy { isHappy }
```

Strings:

```KOTLIN
df.groupBy("isHappy")
```

[Embedded content](./resources/groupByDfGrouped.html)

Properties:

```KOTLIN
df.groupBy { name.firstName and isHappy }
```

Strings:

```KOTLIN
df.groupBy { "name"["firstName"]<String>() and "isHappy" }
```

[Embedded content](./resources/groupByTwoColumns.html)

Properties:

```KOTLIN
df.groupBy { age / 10 named "ageDecade" }
```

Strings:

```KOTLIN
df.groupBy { "age"<Int>() / 10 named "ageDecade" }
```

[Embedded content](./resources/groupByNewColumn.html)

Grouping columns can be created inplace:

Properties:

```KOTLIN
df.groupBy { expr { name.firstName.length + name.lastName.length } named "nameLength" }
```

Strings:

```KOTLIN
df.groupBy {
    expr { "name"["firstName"]<String>().length + "name"["lastName"]<String>().length } named
        "nameLength"
}
```

[Embedded content](./resources/groupByExpr.html)

With the optional `moveToTop` parameter, you can choose whether to make a selected nested column a top-level column:

Properties:

```KOTLIN
df.groupBy(moveToTop = true) { name.firstName }
```

Strings:

```KOTLIN
df.groupBy(moveToTop = true) { "name"["firstName"]<String>() }
```

[Embedded content](./resources/groupByMoveToTop.html)

or to keep it inside a `ColumnGroup`:

Properties:

```KOTLIN
df.groupBy(moveToTop = false) { name.firstName }
```

Strings:

```KOTLIN
df.groupBy(moveToTop = false) { "name"["firstName"]<String>() }
```

[Embedded content](./resources/groupByMoveToTopFalse.html)

Returns `GroupBy` object.

## Transformation

A `GroupBy` can be transformed into a new `GroupBy` using one of the following methods:

* `sortByGroup` / `sortByGroupDesc` — sorts the order of groups (and their corresponding keys) by values computed with a `DataFrameExpression` applied to each group;

* `sortByCount` / `sortByCountAsc` — sorts the order of groups (and their corresponding keys) by the number of rows they contain;

* `sortByKey` / `sortByKeyDesc` — sorts the order of groups (and their corresponding keys) by the grouping key values;

* [sortBy](sortby.html) / [sortByDesc](sortby.html#sortbydesc) — sorts the order of rows within each group by one or more column values, preserving the order of groups and their corresponding keys;

* `updateGroups` — transforms each group into a new one using the provided transforming function;

* [filter](filter.html) — filters out keys and corresponding groups that do not satisfy the given key-group predicate;

* [add](add.html) — adds a new column to each group.

Any [DataFrame](dataframe.html) with [FrameColumn](datacolumn.html#framecolumn) can be reinterpreted as a `GroupBy`:

Properties:

```KOTLIN
val df = dataFrameOf(
    "key" to columnOf(1, 2),
    "data" to columnOf(df[0..3], df[4..6]),
) // create dataframe with two columns

df.asGroupBy { data } // convert dataframe to GroupBy by interpreting 'data' column as groups
```

Strings:

```KOTLIN
val df = dataFrameOf(
    "key" to columnOf(1, 2),
    "data" to columnOf(df[0..3], df[4..6]),
) // create dataframe with two columns

df.asGroupBy("data") // convert dataframe to GroupBy by interpreting 'data' column as groups
```

### Examples of transformation

#### sortByGroup

Properties:

```KOTLIN
df.groupBy { isHappy }.sortByGroup { mean { age } }
```

Strings:

```KOTLIN
df.groupBy("isHappy").sortByGroup { mean("age") }
```

[Embedded content](./resources/sortByGroupOnGroupBy.html)

#### sortByCount

Properties:

```KOTLIN
df.groupBy { age }.sortByCount()
```

Strings:

```KOTLIN
df.groupBy("age").sortByCount()
```

[Embedded content](./resources/sortByCountOnGroupBy.html)

#### sortByKey

Properties:

```KOTLIN
df.groupBy { age }.sortByKey()
```

Strings:

```KOTLIN
df.groupBy { age }.sortByKey()
```

[Embedded content](./resources/sortByKeyOnGroupBy.html)

#### sortBy

Properties:

```KOTLIN
df.groupBy { isHappy }.sortBy { age }
```

Strings:

```KOTLIN
df.groupBy("isHappy").sortBy("age")
```

[Embedded content](./resources/sortByOnGroupBy.html)

#### updateGroups

Properties:

```KOTLIN
df.groupBy { isHappy }.updateGroups { sortByDesc { age }.take(2) }
```

Strings:

```KOTLIN
df.groupBy("isHappy").updateGroups { sortByDesc("age").take(2) }
```

[Embedded content](./resources/updateGroupsOnGroupBy.html)

#### filter

Properties:

```KOTLIN
df.groupBy { isHappy }.filter { group.median { age } > 20 }
```

Strings:

```KOTLIN
df.groupBy("isHappy").filter { group.median { "age"<Int>() } > 20 }
```

[Embedded content](./resources/filterOnGroupBy.html)

#### add

Properties:

```KOTLIN
df.groupBy { isHappy }.add("isAdult") { age >= 18 }
```

Strings:

```KOTLIN
df.groupBy("isHappy").add("isAdult") { "age"<Int>() >= 18 }
```

[Embedded content](./resources/addOnGroupBy.html)

## Reducing

A `GroupBy` can be reduced into a [DataFrame](dataframe.html). It means that each group in this `GroupBy` is collapsed into a single representative row, and these rows are concatenated into a new [DataFrame](dataframe.html).

Reducing is a specific case of aggregation.

This mechanism includes two steps.

### Step 1: use a reducing function to make a single row from each group

To perform a reducing operation, use the following functions:

* [first](first.html) / [last](last.html) – to get the first / last [row](datarow.html) (optionally, the first or last one that satisfies a predicate) of each group.

* [minBy](minby.html) / [maxBy](maxby.html) – to get from each group the row with the smallest / largest result of the [row expression](datarow.html#row-expressions) supplied to the function.

* [medianBy](median.html) / [percentileBy](percentile.html) – to get the row at the position closest to the estimated median/percentile index of the [row expression](datarow.html#row-expressions)'s results calculated on rows within each group.

These functions return an instance of `ReducedGroupBy`, which is a class serving as a transitional step between performing a reduction on groups and specifying how the resulting reduced rows (either original or transformed) should be represented in a new [DataFrame](dataframe.html).

#### Examples of reducing

##### df.groupBy

Properties:

```KOTLIN
df.groupBy { isHappy }
```

Strings:

```KOTLIN
df.groupBy("isHappy")
```

[Embedded content](./resources/groupByDfGroupedReducing.html)

##### first

Properties:

```KOTLIN
df.groupBy { isHappy }.first { age == 30 }
```

Strings:

```KOTLIN
df.groupBy("isHappy").first { it["age"] == 30 }
```

[Embedded content](./resources/groupByFirst.html)

##### last

Properties:

```KOTLIN
df.groupBy { isHappy }.last { weight == null }
```

Strings:

```KOTLIN
df.groupBy("isHappy").last { it["weight"] == null }
```

[Embedded content](./resources/groupByLast.html)

##### minBy

Properties:

```KOTLIN
df.groupBy { isHappy }.minBy { weight }
```

Strings:

```KOTLIN
df.groupBy("isHappy").minBy("weight")
```

[Embedded content](./resources/groupByMinBy.html)

##### maxBy

Properties:

```KOTLIN
df.groupBy { isHappy }.maxBy { age }
```

Strings:

```KOTLIN
df.groupBy("isHappy").maxBy("age")
```

[Embedded content](./resources/groupByMaxBy.html)

##### medianBy

Properties:

```KOTLIN
df.groupBy { isHappy }.medianBy { weight }
```

Strings:

```KOTLIN
df.groupBy("isHappy").medianBy("weight")
```

[Embedded content](./resources/groupByMedianBy.html)

##### percentileBy

Properties:

```KOTLIN
df.groupBy { isHappy }.percentileBy(25.0) { weight }
```

Strings:

```KOTLIN
df.groupBy("isHappy").percentileBy(25.0, "weight")
```

[Embedded content](./resources/groupByPercentileBy.html)

###  Step 2: transform the result to a [DataFrame](dataframe.html) 

A `ReducedGroupBy` can be transformed into a [DataFrame](dataframe.html) using the following functions:

* [concat](concat.html) – to concatenate all reduced rows into a single [DataFrame](dataframe.html).

* [values](values.html) – to create a [DataFrame](dataframe.html) that contains the values from the reduced rows in the selected columns.

* `into` – to add a new [column](datacolumn.html) to the resulting [DataFrame](dataframe.html) with values computed with a [row expression](datarow.html#row-expressions) on each row, or a new [column group](datacolumn.html) containing each group reduced to a single row.

Each method returns a new [DataFrame](dataframe.html) that includes the grouping key columns, containing all unique grouping key values (or value combinations for multiple keys) along with their corresponding reduced rows.

#### Examples of transforming

##### concat

Properties:

```KOTLIN
df.groupBy { isHappy }.minBy { age }.concat()
```

Strings:

```KOTLIN
df.groupBy("isHappy").minBy("age").concat()
```

[Embedded content](./resources/groupByConcat.html)

##### values

Properties:

```KOTLIN
df.groupBy { isHappy }.minBy { age }.values { name and age and city }
```

Strings:

```KOTLIN
df.groupBy("isHappy").minBy("age").values("name", "age", "city")
```

[Embedded content](./resources/groupByValues.html)

##### into

Properties:

```KOTLIN
df.groupBy { isHappy }.minBy { age }.into("youngest") { name }
```

Strings:

```KOTLIN
df.groupBy("isHappy").minBy("age").into("youngest") { getColumnGroup("name") }
```

[Embedded content](./resources/groupByInto.html)

## Aggregation

A `GroupBy` can be directly transformed into a new [DataFrame](dataframe.html) by applying one or more aggregation operations to its groups.

Aggregation is a generalization of [reducing](#reducing).

The following aggregation methods are available:

* [concat](concat.html) — concatenates all [rows](datarow.html) from all groups into a single [DataFrame](dataframe.html), without preserving grouping keys.

* [toDataFrame](createdataframe.html#todataframe) — returns this `GroupBy` as a [DataFrame](dataframe.html) with the grouping keys and corresponding groups in [FrameColumn](datacolumn.html#framecolumn).

* `concatWithKeys` — a variant of [concat](concat.html) that also includes grouping keys that were not present in the original [DataFrame](dataframe.html).

* `into` — creates a new [column](datacolumn.html) containing a list of values computed with a `RowExpression` for each group, or a new [FrameColumn](datacolumn.html#framecolumn) containing the groups themselves.

* [values](values.html) — collects all column values for every group without aggregation. For a [ValueColumn](datacolumn.html#valuecolumn) of type `T` it will gather group values into lists of type `List<T>`. For a [ColumnGroup](datacolumn.html#columngroup) it will gather group values into a [DataFrame](dataframe.html) and convert that [ColumnGroup](datacolumn.html#columngroup) into a [FrameColumn](datacolumn.html#framecolumn).

* [count](count.html) — creates a [DataFrame](dataframe.html) containing the grouping key columns and an additional [column](datacolumn.html) with the number of rows in each corresponding group.

* [countDistinct](countdistinct.html) — creates a [DataFrame](dataframe.html) containing the grouping key columns and an additional [column](datacolumn.html) with the number of distinct rows in each corresponding group.

* `aggregate` — performs a set of custom aggregations using `AggregateDsl`, allowing you to compute one or more [statistics](summarystatistics.html) per every group of `GroupBy`. The body if this function will be executed for every data group and has a receiver of type [DataFrame](dataframe.html) that represents the current data group being aggregated. To add a new column to the resulting [DataFrame](dataframe.html), pass the name of the new column to infix function `into`.

Each of these methods returns a new DataFrame that includes the grouping key columns (except for [concat](concat.html)) along with the columns of values aggregated from the corresponding groups.

### Examples of aggregation

#### concat on GroupBy

[concat](concat.html) can be used to union all data groups of `GroupBy` into the original [DataFrame](dataframe.html) preserving the new order of rows produced by grouping:

Properties:

```KOTLIN
df.groupBy { isHappy }.concat()
```

Strings:

```KOTLIN
df.groupBy("isHappy").concat()
```

[Embedded content](./resources/concatOnGroupBy.html)

#### toDataFrame on GroupBy

Any `GroupBy` can be reinterpreted as [DataFrame](dataframe.html) with [FrameColumn](datacolumn.html#framecolumn):

Properties:

```KOTLIN
df.groupBy { isHappy }.toDataFrame()
```

Strings:

```KOTLIN
df.groupBy("isHappy").toDataFrame()
```

[Embedded content](./resources/toDfOnGroupBy.html)

#### concatWithKeys on GroupBy

Properties:

```KOTLIN
df.groupBy { expr { age >= 18 } named "isAdult" }.concatWithKeys()
```

Strings:

```KOTLIN
df.groupBy { expr { "age"<Int>() >= 18 } named "isAdult" }.concatWithKeys()
```

[Embedded content](./resources/concatWithKeysOnGroupBy.html)

#### into on GroupBy

Properties:

```KOTLIN
df.groupBy { isHappy }.into("ages") { age }
```

Strings:

```KOTLIN
df.groupBy("isHappy").into("ages") { "age"<Int>() }
```

[Embedded content](./resources/intoOnGroupBy.html)

#### values on GroupBy

##### all columns

Properties:

```KOTLIN
df.groupBy { isHappy }.values()
```

Strings:

```KOTLIN
df.groupBy("isHappy").values()
```

[Embedded content](./resources/valuesOnGroupByAllColumns.html)

##### selected columns

Properties:

```KOTLIN
df.groupBy { isHappy }.values { name and age }
```

Strings:

```KOTLIN
df.groupBy("isHappy").values("name", "age")
```

[Embedded content](./resources/valuesOnGroupBySelectedColumns.html)

##### rename columns

Properties:

```KOTLIN
df.groupBy { isHappy }.values { age into "ages" }
```

Strings:

```KOTLIN
df.groupBy("isHappy").values { "age" into "ages" }
```

[Embedded content](./resources/valuesOnGroupByRenameColumns.html)

#### count on GroupBy

Properties:

```KOTLIN
df.groupBy { city }.count()
```

Strings:

```KOTLIN
df.groupBy("city").count()
```

[Embedded content](./resources/countOnGroupBy.html)

#### countDistinct on GroupBy

Properties:

```KOTLIN
df.groupBy { city }.countDistinct { name.firstName }
```

Strings:

```KOTLIN
df.groupBy("city").countDistinct { "name"["firstName"] }
```

[Embedded content](./resources/countDistinctOnGroupBy.html)

#### aggregate on GroupBy

Properties:

```KOTLIN
df.groupBy { city }.aggregate {
    count() into "total"
    count { age > 18 } into "adults"
    median { age } into "median age"
    min { age } into "min age"
    maxBy { age }.name into "oldest"
}
```

Strings:

```KOTLIN
df.groupBy("city").aggregate {
    count() into "total"
    count { "age"<Int>() > 18 } into "adults"
    median("age") into "median age"
    min("age") into "min age"
    maxBy("age")["name"] into "oldest"
}
// or
df.groupBy("city").aggregate {
    count() into "total"
    count { "age"<Int>() > 18 } into "adults"
    "age"<Int>().median() into "median age"
    "age"<Int>().min() into "min age"
    maxBy("age")["name"] into "oldest"
}
```

[Embedded content](./resources/aggregateOnGroupBy.html)

If only one aggregation function is used, the column name can be omitted:

Properties:

```KOTLIN
df.groupBy { city }.aggregate { maxBy { age }.name }
```

Strings:

```KOTLIN
df.groupBy("city").aggregate { maxBy("age")["name"] }
```

[Embedded content](./resources/aggregateOnGroupByWithoutInto.html)

### Aggregation statistics

[Aggregation statistics](summarystatistics.html) are predefined shortcuts for common statistical aggregations such as sum, mean, median, and others.

Each function computes a statistic across the [rows](datarow.html) of a group and returns the result as a new [column](datacolumn.html) (or several columns) in the resulting [DataFrame](dataframe.html).

The following aggregation statistics are available:

* [count](count.html);

* [countDistinct](countdistinct.html);

* [max / maxOf / maxFor](minmax.html);

* [min / minOf / minFor](minmax.html);

* [sum / sumOf / sumFor](sum.html);

* [mean / meanOf / meanFor](mean.html);

* [std / stdOf / stdFor](std.html);

* [median / medianOf / medianFor](median.html);

* [percentile / percentileOf / percentileFor](percentile.html).

To compute one or several [statistics](summarystatistics.html) per every group of `GroupBy`, use the [aggregate](#aggregate-on-groupby) function.

The functions `max`, `maxOf`, and `maxFor` differ as follows. They all calculate the maximum of values, but:

* `max` computes it on the selected columns. If more than one column is selected, for each group it computes one maximum value among all selected columns.

* `maxOf` computes it by a [row expression](datarow.html#row-expressions): the expression is calculated for each row of the group and the maximum value is returned.

* `maxFor` computes it for each of the selected columns within each group. If more than one column is selected, for each group it computes the maximum value for each selected column separately.

Similar logic applies to other statistics.

#### Direct aggregations

Most common aggregation functions can be computed directly on a `GroupBy`.

##### Examples of direct aggregations

###### max

Properties:

```KOTLIN
df.groupBy { city }.max() // max for every column with mutually comparable values
```

Strings:

```KOTLIN
df.groupBy("city").max() // max for every column with mutually comparable values
```

[Embedded content](./resources/maxOnGroupBy.html)

Properties:

```KOTLIN
df.groupBy { isHappy }.max { age and weight }
```

Strings:

```KOTLIN
df.groupBy("city").max("age", "weight")
```

[Embedded content](./resources/maxSelectedOnGroupBy.html)

Properties:

```KOTLIN
df.groupBy { isHappy }.maxFor { age and weight }
```

Strings:

```KOTLIN
df.groupBy("isHappy").maxFor("age", "weight")
```

[Embedded content](./resources/maxForOnGroupBy.html)

Properties:

```KOTLIN
df.groupBy { isHappy }.maxOf { if (age < 30) weight else null }
```

Strings:

```KOTLIN
df.groupBy("isHappy").maxOf { if ("age"<Int>() < 30) "weight"<Int>() else null }
```

[Embedded content](./resources/maxOfOnGroupBy.html)

Properties:

```KOTLIN
df.groupBy { city }
    .max {
        name.firstName.map {
            it.length
        } and name.lastName.map { it.length }
    } // maximum length of firstName or lastName into column "max"
```

Strings:

```KOTLIN
df.groupBy("city").max {
    "name"["firstName"]<String>().map { it.length } and "name"["lastName"]<String>().map { it.length }
} // maximum length of firstName or lastName into column "max"
```

[Embedded content](./resources/maxOnGroupByNameLength.html)

###### min

Properties:

```KOTLIN
df.groupBy { isHappy }.min { age }
```

Strings:

```KOTLIN
df.groupBy("isHappy").min("age")
```

[Embedded content](./resources/minOnGroupBy.html)

Properties:

```KOTLIN
df.groupBy { city }
    .minFor {
        (age into "minAge") and (weight into "minWeight")
    } // min age into column "min age", min weight into column "min weight"
```

Strings:

```KOTLIN
df.groupBy("city")
    .minFor {
        ("age"<Int>() into "minAge") and ("weight"<Int?>() into "minWeight")
    } // min age into column "min age", min weight into column "min weight"
```

[Embedded content](./resources/minForOnGroupBy.html)

###### sum

Properties:

```KOTLIN
df.groupBy { city }.sum("totalWeight") { weight } // sum of weights into column "total weight"
```

Strings:

```KOTLIN
df.groupBy("city").sum("weight", name = "totalWeight") // sum of weights into column "total weight"
```

[Embedded content](./resources/sumOnGroupBy.html)

###### mean

Properties:

```KOTLIN
df.groupBy { city }.mean() // mean for every numeric column
```

Strings:

```KOTLIN
df.groupBy("city").mean() // mean for every numeric column
```

[Embedded content](./resources/meanOnGroupBy.html)

Properties:

```KOTLIN
df.groupBy { city }.meanOf("meanRatio") { weight?.div(age) } // mean of weight/age into column "mean ratio"
```

Strings:

```KOTLIN
df.groupBy("city").meanOf("meanRatio") {
    "weight"<Int?>()?.div("age"<Int>())
} // mean of weight/age into column "mean ratio"
```

[Embedded content](./resources/meanOfOnGroupBy.html)

###### std

Properties:

```KOTLIN
df.groupBy { isHappy }.std { age }
```

Strings:

```KOTLIN
df.groupBy("isHappy").std("age")
```

[Embedded content](./resources/stdOnGroupBy.html)

###### median

Properties:

```KOTLIN
df.groupBy { isHappy }.median { age }
```

Strings:

```KOTLIN
df.groupBy("isHappy").median("age")
```

[Embedded content](./resources/medianOnGroupBy.html)

Properties:

```KOTLIN
df.groupBy { city }
    .medianFor { age and weight } // median age into column "age", median weight into column "weight"
```

Strings:

```KOTLIN
df.groupBy("city")
    .medianFor("age", "weight") // median age into column "age", median weight into column "weight"
```

[Embedded content](./resources/medianForOnGroupBy.html)

###### percentile

Properties:

```KOTLIN
df.groupBy { isHappy }.percentile(25.0) { age }
```

Strings:

```KOTLIN
df.groupBy("isHappy").percentile(25.0) { "age"<Int>() }
```

[Embedded content](./resources/percentileOnGroupBy.html)

## Mapping

Aggregation turns each group into values that end up next to the grouping keys. Mapping does not: it hands every keys/group combination to a lambda and collects whatever that lambda returns.

Every combination arrives as a `GroupWithKey`, so the key values are available as `key` (a [DataRow](datarow.html)) and the rows of the group as `group` (a [DataFrame](dataframe.html)).

The following mapping methods are available:

* [map](map.html#map-on-groupby) — returns a `List` with one computed value per keys/group combination.

* [mapToRows](map.html#map-on-groupby) — computes a [row](datarow.html) per combination and collects them into a [DataFrame](dataframe.html).

* [mapToFrames](map.html#map-on-groupby) — computes a [DataFrame](dataframe.html) per combination and collects them into a [FrameColumn](datacolumn.html#framecolumn).

Unlike the aggregation methods above, the result does not carry the grouping key columns: what the lambda returns is what you get. `map` and `mapToRows` leave out the combinations for which the lambda returns `null`, so their results can be shorter than the number of combinations.

### Examples of mapping

#### map on GroupBy

The number of people per city, as a `List` in the order of the groups:

Properties:

```KOTLIN
df.groupBy { city }.map { group.rowsCount() }
```

Strings:

```KOTLIN
df.groupBy("city").map { group.rowsCount() }
```

#### mapToRows on GroupBy

The oldest person of every city, one [row](datarow.html) per city:

Properties:

```KOTLIN
df.groupBy { city }.mapToRows { group.sortByDesc { age }.firstOrNull() }
```

Strings:

```KOTLIN
df.groupBy("city").mapToRows { group.sortByDesc("age").firstOrNull() }
```

[Embedded content](./resources/groupByMapToRows.html)

#### mapToFrames on GroupBy

The two oldest people for each first name, as a [FrameColumn](datacolumn.html#framecolumn). Every frame keeps all the columns of the original, including the one it was grouped by:

Properties:

```KOTLIN
df.groupBy { name.firstName }.mapToFrames { group.sortByDesc { age }.take(2) }
```

Strings:

```KOTLIN
df.groupBy { "name"["firstName"] }.mapToFrames { group.sortByDesc("age").take(2) }
```

[Embedded content](./resources/groupByMapToFrames.html)

## Pivot + GroupBy

A `GroupBy` can be pivoted with the [pivot](pivot.html#pivot-groupby) method. It produces a `PivotGroupBy` that combines vertical and horizontal grouping, enabling computation of cross-group, matrix-like statistics.

Properties:

```KOTLIN
df.groupBy { isHappy }.pivot { name.firstName }
```

Strings:

```KOTLIN
df.groupBy("isHappy").pivot { "name"["firstName"]<String>() }
```

[Embedded content](./resources/pivotOnGroupBy.html)

For more information, see [pivot + groupBy](pivot.html#pivot-groupby)

