DataFrame.melt() - ( Pandas DataFrame Basics )
Heading h2
Syntax
DataFrame.melt(id_vars=None, value_vars=None, var_name=None, value_name='value')
Example
import pandas as pd
df = pd.DataFrame({
'Country':['USA','Canada','Mexico'],
'2010':[1.2, 3.4, 2.1],
'2011':[2.4, 4.5, 2.8],
'2012':[3.5, 2.3, 4.5]
})
print(df.melt(id_vars=['Country'], value_vars=['2010', '2011', '2012'], var_name='year', value_name='population'))
Output
Country year population
0 USA 2010 1.2
1 Canada 2010 3.4
2 Mexico 2010 2.1
3 USA 2011 2.4
4 Canada 2011 4.5
5 Mexico 2011 2.8
6 USA 2012 3.5
7 Canada 2012 2.3
8 Mexico 2012 4.5
Explanation
Pandas melt
function is used to transform or reshape data frame. It is used to transform wide DataFrames into tall DataFrames and the opposite.
The id_vars
parameter is used to specify the columns that should remain in the resulting DataFrame. The value_vars
parameter is used to specify the columns that should be "unpivoted" or "melted down". The var_name
parameter specifies that the column name of the melted
column, and the value_name
parameter specifies the column name of the value
column.
Use
The melt
function is a powerful tool for data manipulation and wrangling. It is commonly used to reshape data frames by converting columns to rows, so that data can be easily further processed, analyzed, or visualized.
Important Points
- The
melt
function is used to transform or reshape data frames from wide to tall, and vice versa. - The
id_vars
parameter specifies the columns that should remain unchanged in the resulting DataFrame. - The
value_vars
parameter specifies the columns that should be "unpivoted" or "melted down". - The
var_name
parameter specifies the column name of the resulting dataframe's column and thevalue_name
specifies the column name of the resulting data frame's cells.
Summary
In conclusion, the melt
function in pandas is a useful tool to transform or reshape wide data frames to tall data frames and vice versa. It is used to transform, reshape, or pivot data frame, to make the data suitable for further processing, analyzing, or visualizing. The melt
function is easy to use and highly flexible, enabling you to specify the columns that should remain unchanged, those that should be "melted" down, and the resulting data frame's resulting columns name along with cell values name.