Aggregating Data
DS 2023 | Communicating with Data
Overview¶
In this notebook, we will look at how to use grouping variables to aggregate measurement data and to generate wide tables.
We will work with the mpg dataset from Seaborn.
Set Up¶
import pandas as pd
import seaborn as sns
mpg = sns.load_dataset('mpg')
mpgWhat kinds of variables?¶
Get the column names and classify them into lists.
mpg.columnsIndex(['mpg', 'cylinders', 'displacement', 'horsepower', 'weight',
'acceleration', 'model_year', 'origin', 'name'],
dtype='str')id_cols = ['name']
group_cols = ['origin', 'model_year'] # Does not form a key
measure_cols = ['mpg', 'cylinders', 'displacement', 'horsepower', 'weight', 'acceleration']Re-order the dataframe.
mpg[id_cols + group_cols + measure_cols]Aggregate¶
Grouping columns and measurement columns have a complementary relationship to each other.
Let’s look at how we can use group variables to do aggregation on the measurement variables.
To do this, we use Pandas’ groupby function. This function takes a list of columns to group on, followed by a list of columns to which an aggregating function can be applied. If no columns are specified for the aggregation, then all columns are used.
Grouping by one variable¶
Here we group our table by the variable origin and get the mean value of each measurment variable.
mpg.groupby('origin')[measure_cols].mean()And here we group by model_year and get the means.
mpg.groupby('model_year')[measure_cols].mean()Grouping by two variables¶
We can also group by and aggregate on two variables.
mpg.groupby(group_cols)[measure_cols].mean()Split-Apply-Combine¶
The pattern we are using here is called “split-apply-combine” strategy for data analysis, a term coined by Hadley Wickham (2011). Recall that he also coined the expression “tidy data”.
It refers to the process of ...
SPLITTING a table in separate tables based on the domain of a group variable,
APPLYING an aggregate function, like mean or sum, to each group independenty,
and then taking the resulting rows and COMBINING them into a new table.
The resulting table has a row for each unique group value — i.e. the resulting table contains the domain of the grouping column.
Pandas indexes¶
Note the structure of the tables that result from aggregating with groupby: The all have indexes that consist of the domains of the group variables, or every combination of them if grouping on more than one variable.
Unstacking¶
One of the interesting things you can do with a dataframe that has at least two index columns and one measurement column is unstack it.
Let’s regenerate the aggregate table on our two group variables and save it to a new dataframe.
mpg_agg2 = mpg.groupby(group_cols)[measure_cols].mean()
mpg_agg2.head()Now let’s use the unstack method to project the domains of the two group variables onto the two axes.
We also use the transform function T to turn the table sideways, which gives us countries as columns.
mpg_agg2['mpg'].unstack().Tmpg_agg2['mpg'].unstack().T.plot(title="MPG");
mpg_agg2['horsepower'].unstack().Tmpg_agg2['horsepower'].unstack().T.plot(title="Horsepwer");
Another way to do it¶
We can use pivot_table to do an aggregated pivot.
This function is like pivot from the previous notebook, but requires an aggregate function.
mpg.pivot_table(index='model_year', columns='origin', values='mpg', aggfunc='mean')Why can’t we just use pivot?¶
We noted above that the group cols do not form a unique key.
Let’s demonstrate what this means by attempting to pivot the dataset on the group variables a measurement.
try:
mpg.pivot(index='model_year', columns='origin', values='mpg')
except ValueError as e:
print(e)Index contains duplicate entries, cannot reshape
What can you do with a wide table?¶
In either case, having a wide table is convenient for various reasons.
For one, it is easy to apply functions to it.
mpg_year_origin = mpg_agg2['mpg'].unstack().T
mpg_year_originmpg_year_origin.mean()origin
europe 28.401068
japan 29.025748
usa 20.682185
dtype: float64mpg_year_origin.mean(axis=1)model_year
70 21.990909
71 25.450000
72 20.825926
73 19.678161
74 24.888889
75 23.183333
76 23.893939
77 25.796296
78 25.470076
79 28.959420
80 32.867725
81 30.688034
82 34.779630
dtype: float64mpg_year_origin.mean(axis=0)origin
europe 28.401068
japan 29.025748
usa 20.682185
dtype: float64A wide table also let’s us visualize similar data.
mpg_year_origin.plot(title="MPG by Country and Year");
Group counting¶
Finally, group variables can be counted to produce aggregated tables.
mpg.value_counts('origin').to_frame('n')mpg.value_counts('model_year').to_frame('n').sort_index()Here, we count joint frequencies and unstack the results.
mpg.value_counts(group_cols).unstack().TWe can clearly see that the data are imbalanced relative to origin.