How to Pivot a DataFrame in Pandas

Fariba Laiq Feb 15, 2024
How to Pivot a DataFrame in Pandas

This short article will discuss how to pivot a DataFrame in Pandas.

Use pivot() Function to Pivot a DataFrame in Pandas

A given DataFrame can be reshaped using the pivot() method using specified index and column values. The pivot() function does not support data aggregation; multiple values produce a MultiIndex in the columns.

Used column to create the index for a new frame. The pivot function generates a new derived table from a given one; if None, it uses the existing index.

The three arguments pivot accepts are index, columns, and values. A column name from the original table must be specified as a value for each parameter.

The pivot() function will generate a new table with unique values for the specified parameters as its row and column indices. The new table’s cell values come from the column given as the values parameter.

Example code:

from collections import OrderedDict
from pandas import DataFrame
import pandas as pd
import numpy as np

table = OrderedDict(
    (
        ("ID", ["ID1", "ID2", "ID3", "ID4"]),
        ("Std", ["Harry", "Ron", "Daniel", "Kelvin"]),
        ("Subject", ["Maths", "English", "Maths", "English"]),
        ("Marks", ["70", "50", "70", "50"]),
    )
)
d = DataFrame(table)
display(d)

Output:

Create a dataframe

The below example shows the subject value for each row in the original table moved to the new table, where its row and column correspond to the ID and Std of its original row. The NaN values are put in the new table’s cells that do not match any entries in the existing one.

Example code:

from collections import OrderedDict
from pandas import DataFrame
import pandas as pd
import numpy as np

table = OrderedDict(
    (
        ("ID", ["ID1", "ID1", "ID2", "ID2"]),
        ("Std", ["Harry", "Ron", "Daniel", "Kelvin"]),
        ("Subject", ["Maths", "English", "Maths", "English"]),
        ("Marks", ["70", "50", "70", "50"]),
    )
)
d = DataFrame(table)
display(d)
print("Pivoted table : ")
p = d.pivot(index="ID", columns="Std", values="Subject")
display(p)

Output:

pivot a dataframe

Author: Fariba Laiq
Fariba Laiq avatar Fariba Laiq avatar

I am Fariba Laiq from Pakistan. An android app developer, technical content writer, and coding instructor. Writing has always been one of my passions. I love to learn, implement and convey my knowledge to others.

LinkedIn

Related Article - Pandas DataFrame