Links
Comment on page

Create Pivot Table

Tags: #pandas #pivot #operations #snippet #dataframe
Author: Jeremy Ravenel
Last update: 2023-04-12 (Created: 2021-10-06)
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