How to Create a Pivot Table in Python using Pandas?
Last Updated :
18 Dec, 2023
A pivot table is a statistical table that summarizes a substantial table like a big dataset. It is part of data processing. This summary in pivot tables may include mean, median, sum, or other statistical terms. Pivot tables are originally associated with MS Excel but we can create a pivot table in Pandas using Python using the Pandas Dataframe pivot_table() method.
Creating a Sample DataFrame
Let's first create a dataframe that includes Sales of Fruits.
Python3
# importing pandas
import pandas as pd
# creating dataframe
df = pd.DataFrame({'Product': ['Carrots', 'Broccoli', 'Banana', 'Banana',
'Beans', 'Orange', 'Broccoli', 'Banana'],
'Category': ['Vegetable', 'Vegetable', 'Fruit', 'Fruit',
'Vegetable', 'Fruit', 'Vegetable', 'Fruit'],
'Quantity': [8, 5, 3, 4, 5, 9, 11, 8],
'Amount': [270, 239, 617, 384, 626, 610, 62, 90]})
df
Output

Create a Pivot Table in Pandas
Below are some examples to understand how we can create a pivot table in Pandas in Python:
Example 1: Get the Total Sales of Each Product
In this example, the DataFrame 'df' is transformed using a pivot table, aggregating the total 'Amount' for each unique 'Product' and displaying the result with the sum of amounts for each product.
Python3
pivot = df.pivot_table(index=['Product'],
values=['Amount'],
aggfunc='sum')
print(pivot)
Output

Example 2: Get the Total Sales of Each Category
In this example, a pivot table is created from the DataFrame 'df' to summarize the total 'Amount' sales for each unique 'Category,' employing the 'sum' aggregation function, and the result is printed.
Python3
# creating pivot table of total
# sales category-wise aggfunc = 'sum'
pivot = df.pivot_table(index=['Category'],
values=['Amount'],
aggfunc='sum')
print(pivot)
Output

Example 3: Get Total Sales by Category and Product Both
In this example, a pivot table is generated from the DataFrame 'df' to showcase the total 'Amount' sales for unique combinations of 'Product' and 'Category,' utilizing the 'sum' aggregation function. The resulting pivot table is then printed.
Python3
pivot = df.pivot_table(index=['Product', 'Category'],
values=['Amount'], aggfunc='sum')
print(pivot)
Output

Example 4: Get the Mean, Median, Minimum Sale by Category
In this example, a pivot table is created from the DataFrame 'df' to display the median, mean, and minimum 'Amount' values categorized by 'Category.' The aggregation functions 'median,' 'mean,' and 'min' are applied, and the resulting pivot table is printed.
Python3
# 'mean', 'min'} will get median, mean and
# minimum of sales respectively
pivot = df.pivot_table(index=['Category'], values=['Amount'],
aggfunc={'median', 'mean', 'min'})
print(pivot)
Output

Example 5: Get the Mean, Median, Minimum Sale by Product
In this example, a pivot table is generated from the DataFrame 'df' to showcase the median, mean, and minimum 'Amount' values for each unique 'Product.' The aggregation functions 'median,' 'mean,' and 'min' are applied, resulting in the pivot table, which is then printed.
Python3
pivot = df.pivot_table(index=['Product'], values=['Amount'],
aggfunc={'median', 'mean', 'min'})
print(pivot)
Output
Similar Reads
Creating Pivot Table with Multiple Columns using Python Pandas PythonPandas make data manipulation, representation and analysis easier. Pandas Pivot Tables are used to create spreadsheet-style pivot tables as a DataFrame. The levels in the pivot table will be stored in MultiIndex objects (hierarchical indexes) on the index and columns of the result DataFrame. P
4 min read
How to Create a Pivot table with multiple indexes from an excel sheet using Pandas in Python? The term Pivot Table can be defined as the Pandas function used to create a spreadsheet-style pivot table as a DataFrame. It can be created using the pivot_table() method. Syntax: pandas.pivot_table(data, index=None) Parameters: data : DataFrame index: column, Grouper, array, or list of the previous
2 min read
How to Make Arrays fit into Table in Python Pandas? To convert arrays into a table (DataFrame) in Python using the Pandas library, you can follow the steps depending on the structure of your array:1. One-Dimensional ArrayTo convert a one-dimensional NumPy array into a DataFrame, use the pd.DataFrame() method and specify column names for better readab
2 min read
Pandas.pivot_table() - Python pandas.pivot_table() function allows us to create a pivot table to summarize and aggregate data. This function is important when working with large datasets to analyze and transform data efficiently. In this article, we will see some examples to see how it works.Lets see a example:Pythonimport panda
3 min read
How to make a Table in Python? Creating a table in Python involves structuring data into rows and columns for clear representation. Tables can be displayed in various formats, including plain text, grids or structured layouts. Python provides multiple ways to generate tables, depending on the complexity and data size.Using Tabula
3 min read