Pandas: Data Manipulation - melt() function
melt() function
Unpivot a DataFrame from wide format to long format, optionally leaving identifier variables set.
This function is useful to massage a DataFrame into a format where one or more columns are identifier variables (id_vars), while all other columns, considered measured variables (value_vars), are “unpivoted” to the row axis, leaving just two non-identifier columns, ‘variable’ and ‘value’.
Syntax:
pandas.melt(frame, id_vars=None, value_vars=None, var_name=None, value_name='value', col_level=None)
Parameters:
Name | Description | Type | 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’ | Required |
col_level | If columns are a MultiIndex then use this level to melt. | int or string | Optional |
Returns: Unpivoted DataFrame.
Download the Pandas DataFrame Notebooks from here.
Previous: Data Manipulations
Next: pivot() function
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/pandas/melt.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics