To make the analysis of data in a table easier, we can reshape the data into a more computer-friendly form using Pandas in Python. Pandas.melt() is one of the functions to do so.. Pandas.melt() unpivots a DataFrame from wide format to long format.
Pandas melt() function is useful to massage a DataFrame into a format where one or more columns are identifier variables, while all other columns, considered measured variables, are unpivoted to the row axis, leaving just two non-identifier columns, variable and value.
Python Pandas.melt() Function Syntax
Syntax: pandas.melt(frame, id_vars=None, value_vars=None,
var_name=None, value_name=’value’, col_level=None)
Parameters:
- frame : DataFrame
- id_vars[tuple, list, or ndarray, optional] : Column(s) to use as identifier variables.
- value_vars[tuple, list, or ndarray, optional]: Column(s) to unpivot. If not specified, uses all columns that are not set as id_vars.
- var_name[scalar]: Name to use for the ‘variable’ column. If None it uses frame.columns.name or ‘variable’.
- value_name[scalar, default ‘value’]: Name to use for the ‘value’ column.
- col_level[int or string, optional]: If columns are a MultiIndex then use this level to melt.
Creating a Sample DataFrame
Here, we have created a sample DataFrame that we will use in this article.
Python3
import pandas as pd
df = pd.DataFrame({ 'Name' : { 0 : 'John' , 1 : 'Bob' , 2 : 'Shiela' },
'Course' : { 0 : 'Masters' , 1 : 'Graduate' , 2 : 'Graduate' },
'Age' : { 0 : 27 , 1 : 23 , 2 : 21 }})
df
|

melt () do in Pandas Example
Below are the example of how we can use Pandas melt() Function in different ways in Pandas:
Example 1: Pandas melt() Example
In this example, the pd.melt
function is used to unpivot the ‘Course’ column while keeping ‘Name’ as the identifier variable. The resulting DataFrame has three columns: ‘Name’, ‘variable’ (containing the column name ‘Course’), and ‘value’ (containing corresponding values from the ‘Course’ column).
Python3
pd.melt(df, id_vars = [ 'Name' ], value_vars = [ 'Course' ])
|
Output:
Name variable value
0 John Course Masters
1 Bob Course Graduate
2 Shiela Course Graduate
Example 2: Using id_vars and value_vars to melt() of a Pandas DataFrame
In this example, the pd.melt
function is employed to unpivot the ‘Course’ and ‘Age’ columns while using ‘Name’ as the identifier variable.
Python3
pd.melt(df, id_vars = [ 'Name' ], value_vars = [ 'Course' , 'Age' ])
|
Output:
Name variable value
0 John Course Masters
1 Bob Course Graduate
2 Shiela Course Graduate
3 John Age 27
4 Bob Age 23
5 Shiela Age 21
Example 3: Using var_name and value_name to melt() of a Pandas DataFrame
In this example, the pd.melt
function is utilized with customized column names. The ‘Course’ column is unpivoted while preserving ‘Name’ as the identifier. The resulting DataFrame has columns ‘Name’, ‘ChangedVarname’ (for the melted column name, set to ‘Course’), and ‘ChangedValname’ (containing corresponding values from the ‘Course’ column).
Python3
pd.melt(df, id_vars = [ 'Name' ], value_vars = [ 'Course' ],
var_name = 'ChangedVarname' , value_name = 'ChangedValname' )
|
Output:
Name ChangedVarname ChangedValname
0 John Course Masters
1 Bob Course Graduate
2 Shiela Course Graduate
Example 4: Using ignore_index with Pandas.melt() Function
In this example, the pd.melt
function is applied to unpivot the ‘Course’ and ‘Age’ columns while using ‘Name’ as the identifier variable. The original index is ignored due to the ignore_index=True
parameter.
Python3
result = pd.melt(df, id_vars = [ 'Name' ], value_vars = [ 'Course' , 'Age' ], ignore_index = True )
print (result)
|
Output:
Name variable value
0 John Course Masters
1 Bob Course Graduate
2 Shiela Course Graduate
3 John Age 27
4 Bob Age 23
5 Shiela Age 21
Similar Reads
Python | Pandas dataframe.melt()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas dataframe.melt() function unpivots a DataFrame from wide format to long format,
2 min read
Python | Pandas Series.mul()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Python Series.mul() is used to multiply series or list like objects with same length w
3 min read
Python | Pandas dataframe.eval()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas dataframe.eval() function is used to evaluate an expression in the context of t
2 min read
Python | Pandas dataframe.eq()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas dataframe.eq() is a wrapper used for the flexible comparison. It provides a con
3 min read
Python | Pandas Series.le()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas series.le() is used to compare every element of Caller series with passed serie
3 min read
Python | Pandas Dataframe.at[ ]
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas at[] is used to return data in a dataframe at the passed location. The passed l
2 min read
Python | Pandas dataframe.ffill()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.Pandas dataframe.ffill() function is used to fill the missing value in the dataframe. '
3 min read
Python | Pandas Series.multiply()
Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index. Pandas Series.multiply() function perform t
2 min read
Python | Pandas dataframe.sub()
DataFrame.sub() allows for element-wise subtraction between a DataFrame and another object, with added support for handling missing data. The DataFrame.sub() function is essentially equivalent to performing DataFrame - other, but with additional options to manage missing values in one of the inputs.
2 min read
Python | Pandas dataframe.div()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.Pandas dataframe.div() is used to find the floating division of the dataframe and other
3 min read