Reshape long to wide in pandas python with pivot function

Reshaping a data from long to wide in python pandas is done with pivot() function. Pivot() function in pandas is one of the efficient function to transform the data from long to wide format. pivot() Function in python pandas depicted with an example.

Let’s create a simple data frame to demonstrate our reshape example in python pandas

Create dataframe:


import pandas as pd
import numpy as np

#Create a DataFrame
d = {
    'countries':['A','B','C','A','B','C'],
    'metrics':['population_in_million','population_in_million','population_in_million',
                             'gdp_percapita','gdp_percapita','gdp_percapita'],
    'values':[100,200,120,2000,7000,15000]
    }

df = pd.DataFrame(d,columns=['countries','metrics','values'])
df

The dataframe will be like

Reshape long to wide in pandas python with pivot function 1

 

 

Reshape long to wide in pandas python with pivot function:

We will reshape the above data frame from long to wide format in R. The above data frame is already in long format.

Reshape long to wide in pandas python with pivot function 0

 

 

 

 

This can be accomplished with below code

# reshape from long to wide in pandas python

df2=df.pivot(index='countries', columns='metrics', values='values')
df2
  • Pivot function() reshapes the data from long to wide in Pandas python. Countries column is used on index.
  • Values of Metrics column is used as column names and values of value column is used as its value.

So the resultant reshaped dataframe will be

Reshape long to wide in pandas python with pivot function 2

previous-small Reshape long to wide in pandas python with pivot function                                                                                                          next_small Reshape long to wide in pandas python with pivot function

Author

  • Sridhar Venkatachalam

    With close to 10 years on Experience in data science and machine learning Have extensively worked on programming languages like R, Python (Pandas), SAS, Pyspark.

    View all posts