How to melt multiple columns in Pandas Python

In the Pandas DataFrame, you can melt multiple columns of the entire DataFrame with the help of the pd.melt() function and in this Python article, we will see how to implement this function to get a melted Pandas DataFrame. This method gives a DataFrame in which all the variables are in one common column and all the values are in another column. This concept will be clear after you read the text completely.

install the Pandas module using the following syntax:

pip install pandas

Example 1:

In this example, we will first print a standard Pandas DataFrame and then later we will use the pd.melt() method to melt the columns of the same Pandas dataframe to see the difference between the two dataframes.

# import the module
import pandas as pd
# create the raw dataframe
dataframe={'Items':['Books','Pencils','Pens','Notebooks','Erasers'],
'Total':['200','1000','2000','500','1000'],
'Total Cost':['RS.4000','RS.800','RS.2000','RS.3000','RS.500'],
'Brand':['Madhuban','Apsara','Cello','Crazy Rider','Nippon'],
'Sold':['150','800','1500','400','900']}
# Convert to pandas dataframe 
df=pd.DataFrame(dataframe)
# display the pandas dataframe
display(df)
Output:

This is a standard Pandas DataFrame in which all the variables and their values are on different columns as shown clearly.

Now, we will use the pd.melt() method to melt the columns of the dataframe.

# import the module
import pandas as pd
# create a raw dataframe
dataframe={'Items':['Books','Pencils','Pens','Notebooks','Erasers'],
'Total':['200','1000','2000','500','1000'],
'Total Cost':['RS.4000','RS.800','RS.2000','RS.3000','RS.500'],
'Brand':['Madhuban','Apsara','Cello','Crazy Rider','Nippon'],
'Sold':['150','800','1500','400','900']}
# create the Pandas dataframe
df=pd.DataFrame(dataframe)
# melt the dataframe
df2=pd.melt(df)
# Display the melted dataframe
display(df2)
Output:

We can clearly see that with the help of pd.melt() method we are able to print all the variables in one common column and all the values on another column.

Example 2:

# import the library
import pandas as pd
# create data
data={'Students':['Vivek','Nimish','John','Noah','Dnny'],
'Country':['India','South Africa','France','Germany','Poland'],
'Age':['22','24','28','30','26'],
'Height':['174 cm','180 cm','193 cm','153 cm','196 cm'],
'Weight':['52 kg','90 kg','89 kg','77 kg','78 kg'],
'Blood type':['AB+','B+','O-','A+','B-']}
# Create the Pandas DataFrame
Dataframe=pd.DataFrame(data)
# print the DataFrame
print(Dataframe)
# melt the dataframe
df2=pd.melt(Dataframe)
# display the melted dataframe
display(df2)
Output:

Leave a Reply

Your email address will not be published. Required fields are marked *