Pulse Data Hub

Pandas GroupBy Explained with Real Health Data

Pandas groupby splits a table into groups, applies a calculation to each group and puts the results back together. It is the pandas version of SQL’s GROUP BY, and most real analysis questions (“which country…”, “what is the average per…”) end up using it. This guide runs every example on a real dataset and prints what comes back.

The data is the health expenditure table from the seaborn sample data: health spending per person (US dollars) and life expectancy for six rich countries, one row per country and year. Code was run with pandas 3.0.5. The question we keep asking is simple: which country gained the most years of life, and what did it spend?

Horizontal bar chart of life expectancy gain between 1970 and 2020: Japan 12.7 years, Germany 10.5, France 10.1, Canada 8.9, Great Britain 8.5, USA 6.1.
Gain in life expectancy from first to last year in the data, by country, from a pandas groupby.

Load the data and look at its shape

import pandas as pd

url = "https://raw.githubusercontent.com/mwaskom/seaborn-data/master/healthexp.csv"
df = pd.read_csv(url).sort_values(["Country", "Year"])
print(df.shape)
print(df.Country.value_counts().to_dict())
print(df.Year.min(), df.Year.max())

Output:

(274, 4)
{'Japan': 51, 'USA': 51, 'Germany': 50, 'Canada': 44, 'Great Britain': 43, 'France': 35}
1970 2020

There are 274 rows, but the countries do not have the same number of rows. Japan and the USA have 51, Germany 50, Canada 44, Great Britain 43 and France 35, so some years are missing. That matters for every average below: a mean over the rows is a mean over the years that happen to be present.

The basic pandas groupby: one column, one statistic

Pick the column to group by, pick the column to summarise, then name the statistic. Sorting the result is a separate step.

print(df.groupby("Country")["Life_Expectancy"].mean().round(2).sort_values(ascending=False))

Output:

Country
France           79.57
Japan            79.55
Canada           78.71
Great Britain    77.62
Germany          76.73
USA              75.84
Name: Life_Expectancy, dtype: float64

France and Japan lead on average life expectancy, the USA is last. This is the pattern you will use most: groupby(key)[column].statistic(). By default the group key becomes the index of the result. Pass as_index=False to keep it as a normal column instead.

Several statistics at once with named aggregation

agg with named arguments gives each output column a clear name, and each can use a different source column and function.

summary = df.groupby("Country").agg(
    first_year=("Year", "min"),
    spend_2020=("Spending_USD", "last"),
    avg_life=("Life_Expectancy", "mean"),
    max_life=("Life_Expectancy", "max"),
).round(1)
print(summary)

Output:

               first_year  spend_2020  avg_life  max_life
Country                                                  
Canada               1971      5828.3      78.7      82.2
France               1970      5468.4      79.6      82.9
Germany              1970      6939.0      76.7      81.3
Great Britain        1970      5018.7      77.6      81.4
Japan                1970      4665.6      79.6      84.7
USA                  1970     11859.2      75.8      78.9

Because the frame is sorted by year first, last returns the 2020 value. That is easy to get wrong: first and last follow the row order, not the dates, so sort before you use them. The table also shows Canada’s data starts in 1971, and that the USA spent $11,859 per person in 2020 against $4,666 in Japan.

Compare each row to its own group with transform

agg shrinks each group to one row. transform returns a value for every original row, so you can put a group statistic next to the raw data. Here we subtract each country’s own average life expectancy.

df["life_vs_country_avg"] = df.Life_Expectancy - df.groupby("Country")["Life_Expectancy"].transform("mean")
print(df.head(3)[["Country", "Year", "Life_Expectancy", "life_vs_country_avg"]].round(2))

Output:

   Country  Year  Life_Expectancy  life_vs_country_avg
5   Canada  1971             72.8                -5.91
23  Canada  1976             73.8                -4.91
33  Canada  1979             75.1                -3.61

Canada’s 1971 life expectancy was 5.91 years below Canada’s own average for the whole period. Use transform whenever you need a per-group mean, share of total or z-score on the same rows (see our pandas cheat sheet for other row-level tricks).

Answer the real question: life gained versus spending

Now the question from the start. For each country, take the first and last row, then compute the gain and the spending multiple.

g = df.groupby("Country").agg(
    y0=("Year", "first"), y1=("Year", "last"),
    l0=("Life_Expectancy", "first"), l1=("Life_Expectancy", "last"),
    s0=("Spending_USD", "first"), s1=("Spending_USD", "last"),
)
g["life_gain"] = (g.l1 - g.l0).round(1)
g["spend_x"] = (g.s1 / g.s0).round(1)
print(g[["y0", "y1", "life_gain", "spend_x"]].sort_values("life_gain"))

Output:

                 y0    y1  life_gain  spend_x
Country                                      
USA            1970  2020        6.1     36.3
Great Britain  1970  2020        8.5     40.5
Canada         1971  2020        8.9     18.6
France         1970  2020       10.1     28.5
Germany        1970  2020       10.5     27.5
Japan          1970  2020       12.7     31.0

Japan gained 12.7 years and the USA gained 6.1. The USA also multiplied its spending 36.3 times, more than France (28.5), Germany (27.5) or Japan (31.0), though Great Britain’s multiple was higher at 40.5 because it started from the lowest spending level. This data cannot say that spending caused anything, since countries differ in many other ways. What groupby does show is that more spending and a bigger gain did not go together here.

Filter whole groups, rank within a year and pivot

filter keeps or drops entire groups with a test that returns True or False. Ranking inside a group uses groupby().rank(). pivot_table is a groupby with the result laid out as a grid.

full = df.groupby("Country").filter(lambda x: x.Year.min() == 1970)
print(sorted(full.Country.unique()))

df["rank_in_year"] = df.groupby("Year")["Life_Expectancy"].rank(ascending=False)
print(df[df.Year == 2020][["Country", "Life_Expectancy", "rank_in_year"]].sort_values("rank_in_year"))

df["decade"] = df.Year // 10 * 10
print(df.pivot_table(index="decade", columns="Country", values="Life_Expectancy", aggfunc="mean").round(1))

Output:

['France', 'Germany', 'Great Britain', 'Japan', 'USA']
           Country  Life_Expectancy  rank_in_year
272          Japan             84.7           1.0
270         France             82.3           2.0
268         Canada             81.7           3.0
269        Germany             81.1           4.0
271  Great Britain             80.4           5.0
273            USA             77.0           6.0
Country  Canada  France  Germany  Great Britain  Japan   USA
decade                                                      
1970       73.9    72.6     71.6           71.9   74.2  72.3
1980       76.2    74.8     74.5           74.5   77.5  74.6
1990       78.0    78.0     76.9           76.6   79.8  75.9
2000       80.0    80.3     79.3           79.0   82.1  77.5
2010       81.8    82.5     80.8           81.1   83.7  78.7
2020       81.7    82.3     81.1           80.4   84.7  77.0

Canada drops out of the filter because its data starts in 1971. In 2020 Japan ranks first and the USA sixth. The decade table shows the USA at 78.7 in the 2010s and 77.0 in 2020, the only country whose figure fell by a full year or more between those two rows (Great Britain slipped from 81.1 to 80.4). The 2020 row is a single year, and the data does not explain why.

Common pandas groupby mistakes

Sorting before first and last is the first one. The second is forgetting missing groups: by default rows whose key is NaN are dropped, and dropna=False keeps them. The third is averaging averages: a mean of country means is not the mean of all rows when countries have different row counts, as they do here. If you are still cleaning the input, start with how to clean and preprocess data, and for a first look at a new table see exploratory data analysis in Python. The same questions in SQL are covered in SQL for data analysis.

The full reference for every option is in the official pandas groupby user guide. The dataset comes from the seaborn-data repository.

FAQ

What does groupby return in pandas?

A GroupBy object, which holds the groups but computes nothing until you call a statistic such as mean(), agg() or transform().

What is the difference between agg and transform?

agg returns one row per group. transform returns one value per original row, aligned to the original index, so it can be assigned back as a new column.

How do I group by several columns?

Pass a list: df.groupby(["Country", "decade"]). The result has a multi-level index; call reset_index() or use as_index=False to get a flat table.

How do I sort the result of a groupby?

Call sort_values() on the result. The sort= argument of groupby only controls the order of the group keys, not the values.

Newsletter Signup Form

Latest tutorials

Latest articles

On this page
Verified by MonsterInsights