Home »
Python »
Python Programs
Unpivot Pandas Data
Given a pandas dataframe, we have to unpivot pandas data.
By Pranit Sharma Last updated : October 03, 2023
Pandas is a special tool that allows us to perform complex manipulations of data effectively and efficiently. Inside pandas, we mostly deal with a dataset in the form of DataFrame. DataFrames are 2-dimensional data structures in pandas. DataFrames consist of rows, columns, and data.
Problem statement
Suppose we are given a DataFrame with years as index and months as column names where the values are some integer values. We need to unpivot this DataFrame.
Unpivoting Pandas Data
For this purpose, we will first use pandas.DataFrame.unstack() method which will spread the columns and for each value, the index will be repeated.
After this, we will use the pandas.DataFrame.reset_index() method so that all the values i.e., years, months, and integer values will fit into separate columns.
Let us understand with the help of an example,
Python program to unpivot pandas data
# Importing pandas package
import pandas as pd
# Importing numpy package
import numpy as np
# Creating two dictionary
d = {
'jan':[9,7],
'feb':[2,4]
}
# Creating a DataFrame
df = pd.DataFrame(d,index=[2001,2002])
# Display DataFrame
print("DataFrame:\n",df,"\n")
# using unstack method
res = df.unstack()
# resetting index
res = res.unstack().reset_index()
# Display result
print("Result:\n",res,"\n")
Output
The output of the above program is:
Python Pandas Programs »