Reshape wide to long in pandas python with melt() function

Reshaping a data from wide to long in pandas python is done with melt() function. melt function in pandas is one of the efficient function to transform the data from wide to long format. melt() 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'],
    'population_in_million':[100,200,120],
    'gdp_percapita':[2000,7000,15000]
    }

df = pd.DataFrame(d,columns=['countries','population_in_million','gdp_percapita'])
df	

The dataframe will be like

Reshape wide to long in pandas python with melt() function 1

 

Reshape wide to long  in pandas python with melt() function:

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

Reshape wide to long in pandas python with melt() function 0

This can be accomplished with below code

# shape from wide to long with melt function in pandas

df2=pd.melt(df,id_vars=['countries'],var_name='metrics', value_name='values')
df2
  • data frame “df” is passed to melt() function
  • id_vars is the variable which need to be left unaltered which is “countries”
  • var_name are the column names so we named it as ‘metrics’
  • value_name are its values so we named it as ‘values’

so the reshaped dataframe will be

Reshape wide to long in pandas python with melt() function 2

previous-small Reshape wide to long in pandas python with melt function                                                                                                           next_small Reshape wide to long in pandas python with melt 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