lassence.net

Field notes from the AI frontier

Aggregate a pandas DataFrame on multiple functions

--- archive: codebook, 2020–2023 · topic: Pandas ---

Setup

# Import libraries
import pandas as pd
import seaborn as sns

# Load sample data in a DataFrame
df = sns.load_dataset('iris')[['species', 'sepal_length']]
df
speciessepal_length
0setosa5.1
1setosa4.9
2setosa4.7
3setosa4.6
4setosa5.0
………
145virginica6.7
146virginica6.3
147virginica6.5
148virginica6.2
149virginica5.9

Group and aggregate

If we want to get the minimum, average and maximum of sepal_length for each species, a classic way would be:

(
    df
    .groupby('species')
    .agg({'sepal_length': ['min', 'mean', 'max']})
)
sepal_length
min
species
setosa4.3
versicolor4.9
virginica4.9

An alternative style for aggregation allows to aggregate the same column on multiple functions, without having to suffer the pain of multi-index columns:

(
    df
    .groupby('species')
    .agg(
        sepal_length_min=('sepal_length', 'min'),
        sepal_length_mean=('sepal_length', 'mean'),
        sepal_length_max=('sepal_length', 'max'),
    )
)
sepal_length_minsepal_length_meansepal_length_max
species
setosa4.35.0065.8
versicolor4.95.9367.0
virginica4.96.5887.9