Pandas melt() function is used to change the DataFrame format from wide to long. It’s used to create a specific format of the DataFrame object where one or more columns work as identifiers. All the remaining columns are treated as values and unpivoted to the row axis and only two columns – variable and value
This function can be applied when you have categorical variables in Python, such as an ID column with all unique values that identifies each observation in your dataset, but want a better understanding of what data belongs together by looking at their commonalities across categories instead of individually.
Table of Contents
Pandas melt: A Function for Reshaping Data in Table Form
Data is everywhere. The data can be found in many different formats such as tables, graphs and charts. When the data needs to be analyzed, it needs to be converted into a computer-friendly format for easy processing. Pandas provides functions that do this conversion process. One of those functions is Pandas.melt().
Pandas melt() function unpivots a DataFrame from wide format to long format and leaves just two non-identifier columns: variable and value after all other columns are considered measured variables..
This function is useful when we want one or more column as identifier variables while all other columns are considered measured variable; there will only two non-identifiers (variable and value) columns left on the row axis.
Syntax
pandas.melt(frame, id_vars=None, value_vars=None, var_name=None, value_name='value', col_level=None, ignore_index=True)
Parameters
id_vars: tuple, list, or ndarray, optional
To utilize as identifier variables, select one or more columns.
value_vars: tuple, list, or ndarray, optional
Unpivot column(s). If id vars isn’t supplied, all columns that aren’t set as id vars are used.
var_name: scalar
For the ‘variable’ column, give it a name. If None, frame.columns.name or ‘variable’ are used.
value_name: scalar, default ‘value’
For the ‘value’ column, give it a name.
col_level: int or str, optional
Use this level to melt whether the columns are MultiIndex.
ignore_index: bool, default True
The original index is ignored if True. The original index is kept if False. As needed, index labels will be repeated.
In version 1.1.0, there is a new feature.
Returns
DataFrame
Example 01: The Melt() Function in Python
The melt() function is a great way to convert a set of data into a dictionary that can be more easily transformed. In this blog post, we will look at an example where we have some tabular data and use the melt() function to create a new table.
Code
import pandas as pd
df = pd.DataFrame({'Name': {0: 'Anmol', 1: 'Sakshi', 2: 'Maryam'},
'Course': {0: 'Software', 1: 'Computer Systems', 2: 'Software'},
'Age': {0: 23, 1: 25, 2: 27}})
print("Default Table: \n", df)
df_melted = pd.melt(df, id_vars=['Age'], value_vars=["Name", "Course"])
print("\n Melted Table: \n", df_melted)
Output

Example 02: Pass Multiple Columns as the id_vars Parameter to See What Happens
If you have been using the id_vars parameter for some time, then I’m sure that you have had a few questions about what it does and how it works. This blog post will help you understand this important parameter better so that your queries run more smoothly.
We will also show a couple of examples to illustrate its usage with different data sets.
Code
import pandas as pd
df = pd.DataFrame({'Name': {0: 'Anmol', 1: 'Sakshi', 2: 'Maryam'},
'Course': {0: 'Software', 1: 'Computer Systems', 2: 'Software'},
'Age': {0: 23, 1: 25, 2: 27}})
print("Default Table: \n", df)
df_melted = pd.melt(df, id_vars=['Age', "Name"], value_vars=["Course"])
print("\n Melted Table: \n", df_melted)
Output

Example 03: Skipping a Column from the DataFrame
In the previous example, we used all the rows from a DataFrame. But it’s not required to use all of them. In this next example, let’s skip the “Age” column and see how it changes things:
Code
import pandas as pd
df = pd.DataFrame({'Name': {0: 'Anmol', 1: 'Sakshi', 2: 'Maryam'},
'Course': {0: 'Software', 1: 'Computer Systems', 2: 'Software'},
'Age': {0: 23, 1: 25, 2: 27}})
print("Default Table: \n", df)
df_melted = pd.melt(df, id_vars=["Name"], value_vars=["Course"])
print("\n Melted Table: \n", df_melted)

Example 04: Unmelt a DataFrame Object: Pivot() Function
DataFrame objects are useful for storing and analyzing data in a tabular format. Sometimes, however, we might want to “unmelt” a DataFrame object so that it is easier to analyze the raw data.
In this blog post, we’ll focus on how pivot() function can be used to unmelt a DataFrame object and get the original dataframe.
Code
import pandas as pd
df = pd.DataFrame({'Name': {0: 'Anmol', 1: 'Sakshi', 2: 'Maryam'},
'Course': {0: 'Software', 1: 'Computer Systems', 2: 'Software'},
'Age': {0: 23, 1: 25, 2: 27}})
print("Default Table: \n", df)
df_melted = pd.melt(df, id_vars=["Age"], value_vars=["Name", "Course"], var_name="Attribute", value_name="Value")
print("\n Melted Table: \n", df_melted)
df_unmelted = df_melted.pivot(index='Age', columns='Attribute')
print("\n Unmelted Table: \n: ", df_unmelted)

Conclusion
“Pandas melt” is a function for reshaping data in table form. This post has provided you with an introduction to pandas’ mechanics and how it can be used as one part of your arsenal when analyzing tabular datasets from different sources.