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
# Name is id_vars and Course is value_vars 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
# multiple unpivot columns 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
# Names of ‘variable’ and ‘value’ columns can be customized 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
# multiple unpivot columns with ignore_index 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
Python | Pandas.melt()
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.