pandas melt method Implementation with Examples

pandas melt implementation

Pandas is the best Python library for manipulating large or small datasets. These datasets are known as data frames in pandas. There are many inbuilt methods in pandas that allow you to manipulate them easily. The pandas.melt() method is one of them. In this entire tutorial, you will know how to implement the method pandas.melt()  through steps.

What does Pandas’s melt method do?

If you have dataframe or dataset that has a large number of columns of variables then the panda’s melt method transforms the shape of the dataset. It unpivots a DataFrame from wide to long format, optionally leaving identifiers set. Unpivoting means converting wide format ( many columns ) to long format( few columns but many rows).  It helps you to easily analyze large datasets.

In the coming section, you will know the syntax of this method and the steps to implement it.

The syntax for the Pandas melt()

pandas.melt(frame, id_vars=None, value_vars=None, var_name=None, value_name='value', col_level=None, ignore_index=True)

Explanation of the parameters 

frame: Input dataset in the form of dataframe.

id_vars : Columns to use as identifier variables. It accepts tuple, list, or ndarray and is optional.

value_vars: Columns to unpivot. If not specified, use all columns that are not set as id_vars. It also accepts tuple, list, or ndarray and is optional.

var_name: Name to use for the ‘variable’ column. If None it uses frame.columns.name or ‘variable.

value_name: Name to use for the ‘value’ column.

col_level: f columns are a MultiIndex then use this level to melt.

ignore_index: If True, the original index is ignored. If False, the original index is retained. Index labels will be repeated as necessary.

It returns Unpivoted DataFrame.

Steps to implement Pandas Melt method

In this section, you will know all the steps to implement the panda’s melt method. Just follow the steps for deep understanding.

Step 1: Import all the necessary libraries

The first step is to import all the required libraries that I want to implement. In my example, I am using only the pandas’ python package. So let’s import it using the import statement.

import pandas as pd

Step 2: Create a Sample Dataframe

The next step is to create a dummy data frame where I will apply the pandas melt() method. However, you can use your own dataset. I am creating a sample dataframe for demonstration purposes only. Execute the below lines of code to create it.

import pandas as pd
data = {"Name":["Sahil","Ron","Michel","Peter"],"Cars":["Audi","BMW","Audi","Ford"],"Age":[30,27,24,50]}
df = pd.DataFrame(data)
print(df)

Output

Sample dataframe for melt() method
Sample dataframe for melt() method

Step 3: Apply the Pandas melt() method

After the creation of the sample, dataframe let’s apply the pandas.melt() method on it.

Unpivot Single Column

In the first example, I will unpivot dataframe on a single column that is Cars. Execute the below lines of code.

import pandas as pd
data = {"Name":["Sahil","Ron","Michel","Peter"],"Cars":["Audi","BMW","Audi","Ford"],"Age":[30,27,24,50]}
df = pd.DataFrame(data)

print(pd.melt(df,id_vars=["Name"],value_vars=["Cars"]))

Output

Unpivoting single column in dataframe
Unpivoting a single column in dataframe

Unvpiovting dataframe on Multiple Columns

In the same way, you can unpivote dataframe on more than one columns. You have to just use columns name as the list in value_vars. Just run the below lines of code and see the output.

import pandas as pd
data = {"Name":["Sahil","Ron","Michel","Peter"],"Cars":["Audi","BMW","Audi","Ford"],"Age":[30,27,24,50]}
df = pd.DataFrame(data)

print(pd.melt(df,id_vars=["Name"],value_vars=["Cars","Age"]))

Output

Unpivoting multiple columns in dataframe
Unpivoting multiple columns in dataframe

You can see how the dataframe has reshaped.

Conclusion

Pandas melt method is very useful if you want to lower the number of variables in the datasets. As it unpivots the dataframe it gives you a bigger picture of the dataframe. These are steps for implementing melt() method. I hope you have liked this tutorial. If you have any queries then you can contact us for more help.

Source:

Pandas Documentation

 

Join our list

Subscribe to our mailing list and get interesting stuff and updates to your email inbox.

Thank you for signup. A Confirmation Email has been sent to your Email Address.

Something went wrong.

Share via
 
Thank you For sharing.We appreciate your support. Don't Forget to LIKE and FOLLOW our SITE to keep UPDATED with Data Science Learner