Links

Create Pivot Table

Tags: #pandas #pivot #operations #snippet #dataframe
Author: Jeremy Ravenel​
Description: This notebook provides an example of how to use the Pandas library to create a pivot table.

Input

Import library

import pandas as pd

Variables

df = pd.DataFrame(
{
"item": ["apple", "apple", "apple", "apple", "apple"],
"size": ["small", "small", "large", "large", "large"],
"location": ["Walmart", "Aldi", "Walmart", "Aldi", "Aldi"],
"price": [3, 2, 4, 3, 2.5],
}
)
df

Model

Function

pivot = pd.pivot_table(
df, values="price", index=["item", "size"], columns=["location"], aggfunc="mean"
)

Output

Display result

pivot