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 with two grouping variables and and one measurement variable .
You want to create a wide table with on axis 0, on axis 1, and 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¶
import pandas as pd
import seaborn as sns
healthexp = sns.load_dataset("healthexp")
healthexp.head()Choose the variables¶
a_g1 = 'Year'
a_g2 = 'Country'
a_m = 'Spending_USD'Check for uniqueness¶
Value counts returns results in descending order, so any values greater than 1 would appear first.
healthexp.value_counts([a_g1,a_g2]).head(1)Year Country
1970 Germany 1
Name: count, dtype: int64No values greater than 1, so unique.
Reshape¶
Method 1: Pivoting¶
healthexp.pivot(index=a_g1, columns=a_g2, values=a_m).head(10)Method 2: Unstacking¶
healthexp.set_index([a_g1, a_g2])[a_m].unstack().head(10)Example 2¶
Get the data¶
mpg = sns.load_dataset('mpg')
mpg.head()Choose the variables¶
b_g1 = 'model_year'
b_g2 = 'origin'
b_m = 'mpg'Check for uniqueness¶
Value counts returns results in descending order, so any values greater than 1 would appear first.
mpg.value_counts([b_g1,b_g2]).head(1)model_year origin
73 usa 29
Name: count, dtype: int64Not unique.
Aggregate and Reshape¶
Method 1: Pivoting with aggregation¶
mpg.pivot_table(index=b_g1, columns=b_g2, values=b_m, aggfunc='mean')Method 2: Aggregating then unstacking¶
mpg.groupby([b_g1, b_g2])[b_m].mean().unstack()General Function¶
We define a general function that takes a tidy dataframe as its first argument and returns a wide dataframe.
def tidy2wide(tidy, g1, g2, m, method='pivot', aggfunc='mean'):
unique = True if tidy.value_counts([g1,g2]).head(1).values[0] == 1 else False
if unique:
print("Group combos are unique.")
if method == 'pivot':
wide = tidy.pivot(index=g1, columns=g2, values=m)
elif method == 'unstack':
wide = tidy.set_index([g1,g2])[m].unstack()
else:
raise ValueError("Invalid method.")
else:
print("Group combos are not unique.")
if method == 'pivot':
wide = tidy.pivot_table(index=g1, columns=g2, values=m, aggfunc=aggfunc)
elif method == 'unstack':
wide = tidy.groupby([g1,g2])[m].mean().unstack()
else:
raise ValueError("Invalid method and/or aggfunc.")
return widetidy2wide(mpg, 'model_year', 'origin', 'mpg')Group combos are not unique.
tidy2wide(mpg, 'model_year', 'origin', 'mpg', method='unstack')Group combos are not unique.
tidy2wide(healthexp, 'Year', 'Country', 'Spending_USD')Group combos are unique.
tidy2wide(healthexp, 'Year', 'Country', 'Spending_USD', method='unstack')Group combos are unique.