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.

Two Ways from Tidy to Wide

DS 2023 | Communicating with Data

Overview

This notebook introduces a recipe for create a wide table from a tidy table.

It assumens the following:

  • You have a tidy DataFrame DD with two grouping variables g1g_1 and g2g_2 and one measurement variable mm.

  • You want to create a wide table WW with g1g_1 on axis 0, g2g_2 on axis 1, and mm data in the cells.

It describes two method for doing so under two conditions.

  • Conditions: Do the two grouping variables combine to produce a unique set over the observations or not?

  • Methods: Using pivoting or using unstacking.

Flowchart

This flowchart summarizes the pattern.

Example 1

Get the data

Loading...

Choose the variables

Check for uniqueness

Value counts returns results in descending order, so any values greater than 1 would appear first.

Year Country 1970 Germany 1 Name: count, dtype: int64

No values greater than 1, so unique.

Reshape

Method 1: Pivoting

Loading...

Method 2: Unstacking

Loading...

Example 2

Get the data

Loading...

Choose the variables

Check for uniqueness

Value counts returns results in descending order, so any values greater than 1 would appear first.

model_year origin 73 usa 29 Name: count, dtype: int64

Not unique.

Aggregate and Reshape

Method 1: Pivoting with aggregation

Loading...

Method 2: Aggregating then unstacking

Loading...

General Function

We define a general function that takes a tidy dataframe as its first argument and returns a wide dataframe.

Group combos are not unique.
Loading...
Group combos are not unique.
Loading...
Group combos are unique.
Loading...
Group combos are unique.
Loading...