w3resource

Pandas DataFrame: melt() function

DataFrame - melt() function

The melt() function is used to unpivot a given DataFrame from wide format to long format, optionally leaving identifier variables set.

Syntax:

DataFrame.melt(self, id_vars=None, value_vars=None, var_name=None, value_name='value', col_level=None)

Parameters:

Name Description Type/Default Value Required / Optional
frame      DataFrame Required
id_vars  Column(s) to use as identifier variables. tuple, list, or ndarray Optional
value_vars  Column(s) to unpivot. If not specified, uses all columns that are not set as id_vars. tuple, list, or ndarray Optional
var_name  Name to use for the ‘variable’ column. If None it uses frame.columns.name or ‘variable’. scalar Required
value_name  Name to use for the ‘value’ column. scalar
Default Value: ‘value’
Required
col_level  If columns are a MultiIndex then use this level to melt. int or string Optional

Returns: DataFrame
Unpivoted DataFrame.

Example:


Download the Pandas DataFrame Notebooks from here.

Previous: DataFrame - unstack() function
Next: DataFrame - explode() function



Share this Tutorial / Exercise on : Facebook and Twitter