Skip to content
Exercises · Q2

Q.Explain the difference between pivot() and pivot_table() function?

Puducherry TnboardTextbookSubjective· 3mImportance★★★★★est
42% · 22/53 Questions
✓ Free question

The pivot() function reshapes a DataFrame based on unique index/column pairs, requiring no duplicate entries for the specified index and column combination. The pivot_table() function, on the other hand, is more flexible, allowing for aggregation of duplicate entries using an aggfunc parameter, making it suitable for summarizing data.

Pandas provides powerful functions to reshape and summarize data, and pivot() and pivot_table() are two fundamental tools for this. While both can transform data from a "long" format to a "wide" format, they differ significantly in how they handle duplicate entries and their overall flexibility. Understanding these differences is crucial for effective data manipulation.

pivot() Function

The pivot() function is used to reshape a DataFrame based on column values. It takes three main arguments: index, columns, and values. It essentially creates a new DataFrame where:

  • The unique values from the index column become the new DataFrame's index.
  • The unique values from the columns column become the new DataFrame's columns.
  • The values from the values column populate the cells of the new DataFrame.

The critical characteristic of pivot() is that it requires the combination of index and columns to be unique. If there are duplicate entries for any given (index, columns) pair, pivot() will raise a ValueError. This means pivot() is best suited for situations where you have a one-to-one mapping between your chosen index and column values.

Let's illustrate with an example.

import pandas as pd
import numpy as np

# Sample DataFrame
data = {
    'Date': ['2023-01-01', '2023-01-01', '2023-01-02', '2023-01-02', '2023-01-03'],
    'Region': ['North', 'South', 'North', 'South', 'North'],
    'Product': ['A', 'B', 'A', 'B', 'C'],
    'Sales': [100, 150, 120, 180, 200]
}
df = pd.DataFrame(data)
print("Original DataFrame:")
print(df)
Original DataFrame:
         Date Region Product  Sales
0  2023-01-01  North       A    100
1  2023-01-01  South       B    150
2  2023-01-02  North       A    120
3  2023-01-02  South       B    180
4  2023-01-03  North       C    200

Now, let's use pivot() to reshape this DataFrame, with Date as the index, Region as columns, and Sales as values.

# Using pivot()
df_pivot = df.pivot(index='Date', columns='Region', values='Sales')
print("\nDataFrame after pivot(index='Date', columns='Region', values='Sales'):")
print(df_pivot)
DataFrame after pivot(index='Date', columns='Region', values='Sales'):
Region        North  South
Date                      
2023-01-01    100.0  150.0
2023-01-02    120.0  180.0
2023-01-03    200.0    NaN

Notice that for '2023-01-03', there was no 'South' region entry, so NaN is filled in. This is expected behavior.

Watch out

The pivot() function will raise a ValueError: Index contains duplicate entries, cannot reshape if the combination of index and columns values is not unique. For example, if our original DataFrame had two entries for ('2023-01-01', 'North'), pivot() would fail.

pivot_table() Function

The pivot_table() function is a more general and powerful version of pivot(). It is designed to summarize and aggregate data, making it suitable for situations where there might be duplicate entries for the (index, columns) combination.

Key features of pivot_table():

  • Aggregation: It automatically aggregates values for duplicate (index, columns) pairs using a specified aggregation function (aggfunc). The default aggfunc is numpy.mean.
  • Flexibility: It can handle multiple index columns, multiple column columns, and multiple value columns.
  • Missing Values: It handles missing values gracefully, filling them with NaN by default, or a specified fill_value.

The main arguments for pivot_table() are similar to pivot() but with added flexibility: index, columns, values, and crucially, aggfunc.

Let's modify our sample DataFrame to include duplicate entries to demonstrate pivot_table()'s strength.

# Sample DataFrame with duplicate entries
data_with_duplicates = {
    'Date': ['2023-01-01', '2023-01-01', '2023-01-01', '2023-01-02', '2023-01-02', '2023-01-03'],
    'Region': ['North', 'North', 'South', 'North', 'South', 'North'],
    'Product': ['A', 'A', 'B', 'A', 'B', 'C'],
    'Sales': [100, 110, 150, 120, 180, 200]
}
df_dup = pd.DataFrame(data_with_duplicates)
print("\nOriginal DataFrame with duplicates:")
print(df_dup)
Original DataFrame with duplicates:
         Date Region Product  Sales
0  2023-01-01  North       A    100
1  2023-01-01  North       A    110
2  2023-01-01  South       B    150
3  2023-01-02  North       A    120
4  2023-01-02  South       B    180
5  2023-01-03  North       C    200

Notice that for ('2023-01-01', 'North'), there are two sales entries (100 and 110). If we tried df_dup.pivot(index='Date', columns='Region', values='Sales'), it would raise a ValueError.

Now, let's use pivot_table() with an aggregation function.

# Using pivot_table() with sum aggregation
df_pivot_table_sum = df_dup.pivot_table(index='Date', columns='Region', values='Sales', aggfunc='sum')
print("\nDataFrame after pivot_table(index='Date', columns='Region', values='Sales', aggfunc='sum'):")
print(df_pivot_table_sum)
DataFrame after pivot_table(index='Date', columns='Region', values='Sales', aggfunc='sum'):
Region        North  South
Date                      
2023-01-01    210.0  150.0
2023-01-02    120.0  180.0
2023-01-03    200.0    NaN

Here, for ('2023-01-01', 'North'), the sales values (100 and 110) have been summed up to 210. We could also use other aggregation functions like mean, count, min, max, median, or even a custom function.

# Using pivot_table() with mean aggregation
df_pivot_table_mean = df_dup.pivot_table(index='Date', columns='Region', values='Sales', aggfunc='mean')
print("\nDataFrame after pivot_table(index='Date', columns='Region', values='Sales', aggfunc='mean'):")
print(df_pivot_table_mean)
DataFrame after pivot_table(index='Date', columns='Region', values='Sales', aggfunc='mean'):
Region        North  South
Date                      
2023-01-01    105.0  150.0
2023-01-02    120.0  180.0
2023-01-03    200.0    NaN

For ('2023-01-01', 'North'), the mean of 100 and 110 is 105.

Key Differences

Featurepivot()pivot_table()
PurposeReshapes data based on unique combinations.Summarizes and aggregates data, handling duplicates.
Duplicate EntriesRaises ValueError if (index, columns) pairs are not unique.Handles duplicates by aggregating them using aggfunc.
AggregationNo aggregation performed.Requires an aggfunc (default is mean) to aggregate values.
InputWorks only on DataFrames.Works on DataFrames.
FlexibilityLess flexible; strict requirement for unique pairs.More flexible; can handle multiple index, columns, values, and aggfunc.
Use CaseWhen you are certain that each (index, columns) pair has only one value.When you need to summarize data, especially when duplicates are present, or when you need to apply aggregation.

When to use which?

  • Use pivot() when you have data that is already in a "tidy" format where each combination of index and columns uniquely identifies a single value. This is often the case when you are simply changing the orientation of your data without needing to perform any calculations.
  • Use pivot_table() when you need to summarize data, perform calculations (like sum, mean, count) on groups of data, or when your data might have multiple entries for the same (index, columns) combination. It is the more commonly used function for data analysis and reporting.

✓Final answer

The pivot() function reshapes a DataFrame based on unique index/column pairs and will raise an error if duplicates are found, while the pivot_table() function is more versatile, allowing for aggregation of duplicate entries using an aggfunc parameter to summarize data.

Unlock everything free for 14 days

  • Full step-by-step solutions
  • Concept-first explanations
  • Methods, shortcuts & mistakes
  • PYQ mapping + timed mock tests

Full access for 14 days. No credit card required.