From Tidy to Wide Data
DS 2023 | Communicating with Data
We have seen that a tidy table is one in which:
Each row stands for a unique observation. The observation is the subject of the recorded fact.
Each column stands for a variable. The variable is the predicate of the recorded fact.
Each cell possesses the value of that variable for a given observation. The value is the object (so-called) of the recorded fact.
The complete data set¶
Let’s explore the properties of tidy data in more depth using the complete data set of health outcomes from countries over years.
We will import the Health Expenditure and Life Expectancy healthexp data set from Seaborn’s collection.
import pandas as pd
import seaborn as sns
healthexp = sns.load_dataset("healthexp")
healthexp.index.name = 'obs_id'
healthexp.info()
healthexp<class 'pandas.DataFrame'>
RangeIndex: 274 entries, 0 to 273
Data columns (total 4 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 Year 274 non-null int64
1 Country 274 non-null str
2 Spending_USD 274 non-null float64
3 Life_Expectancy 274 non-null float64
dtypes: float64(2), int64(1), str(1)
memory usage: 10.4 KB
Identify columns uses¶
group_cols = ['Country','Year']
measure_cols = ['Spending_USD','Life_Expectancy']Create a wide table¶
Move 1: Use the group columns to define the index¶
If the group columns form a unique key -- and here they do -- then can replace the index with them.
healthexp1 = healthexp.set_index(group_cols)
healthexp1Move 2: Unstack on a measurement variable¶
Here is how you unstack on Spending_USD.
First, notice what happens when we select a single column.
healthexp1['Spending_USD'] # Selecting one column produces a Series with a MultiIndexCountry Year
Germany 1970 252.311
France 1970 192.143
Great Britain 1970 123.993
Japan 1970 150.437
USA 1970 326.961
...
Germany 2020 6938.983
France 2020 5468.418
Great Britain 2020 5018.700
Japan 2020 4665.641
USA 2020 11859.179
Name: Spending_USD, Length: 274, dtype: float64When we unstack the series, we get a wide dataframe.
healthexp1['Spending_USD'].unstack().T.head(10) # Unstacking projects the second index column onto axis 1Similary, we can unstack on Life_Expectancy:
healthexp1['Life_Expectancy'].unstack().T.head(10)Or just use pivot¶
We can achieve the same effect using pivot:
healthexp_spending = healthexp.pivot(index='Country', columns='Year', values='Spending_USD')
healthexp_spending.T.head(10)