Pandas DataFrame melt() Method
Example
Stack the DataFrame from a table where each index had 4 columns, into a table with one row for each column:
In this example we use a .csv file called data.csv
import pandas as pd
df = pd.read_csv('data.csv')
newdf =
df.melt()
Try it Yourself »
Definition and Usage
The melt()
method reshapes the DataFrame
into a long table with one row for each each column.
Syntax
dataframe.melt(id_vars, value_vars, var_name, value_name, col_level,
ignore_index)
Parameters
The id_vars
,
value_vars
, var_name
,
value_name
, col_level
,
ignore_index
parameters are
keyword arguments.
Parameter | Value | Description |
---|---|---|
id_vars | Tuple List Array |
Optional, specifies the column, or columns, to use as identifiers |
value_vars | Tuple List Array |
Optional, specifies columns to unpivot. |
var_name | String | Optional, specifies the label of the 'variable' column, default 'variable' |
col_level | Number String |
Optional, for MultiIndex DataFrames, specifies the level to melt |
ignore_index | True |
Optional, default True. Specifies whether to ignore the original index or not |
Return Value
A reshaped DataFrame object.
This method does not change the original DataFrame.
Copyright 1999-2023 by Refsnes Data. All Rights Reserved.