Create Pivot Table
Tags: #pandas #pivot
Author: Jeremy Ravenel

Input

Import library

1
import pandas as pd
Copied!

Variables

1
df = pd.DataFrame(
2
{
3
"item": ["apple", "apple", "apple", "apple", "apple"],
4
"size": ["small", "small", "large", "large", "large"],
5
"location": ["Walmart", "Aldi", "Walmart", "Aldi", "Aldi"],
6
"price": [3, 2, 4, 3, 2.5],
7
}
8
)
9
df
Copied!

Model

Function

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

Output

Display result

1
pivot
Copied!
Copy link
Edit on GitHub