Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

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.

<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
Loading...

Identify columns uses

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.

Loading...

Move 2: Unstack on a measurement variable

Here is how you unstack on Spending_USD.

First, notice what happens when we select a single column.

Country 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: float64

When we unstack the series, we get a wide dataframe.

Loading...

Similary, we can unstack on Life_Expectancy:

Loading...

Or just use pivot

We can achieve the same effect using pivot:

Loading...