Pandas.melt() Method

Pandas.melt() function converts a wide-form DataFrame into a long-form DataFrame by “melting” or “unpivoting” the data. It transforms a DataFrame with multiple columns into a DataFrame with fewer columns, where one or more columns are identifier variables, and the rest are merged into a single variable and value columns.

Syntax

pandas.melt(frame, id_vars=None, value_vars=None, var_name=None, 
            value_name='value', col_level=None, ignore_index=True)

Parameters

frame: The input DataFrame to melt.

id_vars: Columns to use as identifier variables. These columns will remain unchanged in the resulting DataFrame.

value_vars: Columns to melt into the variable and value columns. By default, all columns not set as identifier variables are melted.

var_name: The name to use for the variable column. The default value is None, which infers the name from the input DataFrame.

value_name: The name to use for the value column. The default value is ‘value‘.

col_level: For DataFrames with multi-level columns, specify which level to melt. The default value is None, which melts all levels.

ignore_index: If True, the resulting DataFrame’s index is reset. The default value is True.

Example

import pandas as pd

data = {
  'Name': ['Krunal', 'Ankit', 'Rushabh', 'Dhaval', 'Hemang'],
  'Age': [25, 30, 22, 28, 35],
  'Score': [90, 85, 92, 88, 78]
}
df = pd.DataFrame(data)
print("Original DataFrame:")
print(df)

melted_df = pd.melt(df, id_vars=['Name'], value_vars=[
            'Age', 'Score'], var_name='Attribute', value_name='Value')
print("\nMelted DataFrame:")
print(melted_df)

Output

Original DataFrame:
   Name    Age   Score
0  Krunal  25     90
1  Ankit   30     85
2  Rushabh 22     92
3  Dhaval  28     88
4  Hemang  35     78

Melted DataFrame:
   Name    Attribute  Value
0  Krunal    Age       25
1  Ankit     Age       30
2  Rushabh   Age       22
3  Dhaval    Age       28
4  Hemang    Age       35
5  Krunal   Score      90
6  Ankit    Score      85
7  Rushabh  Score      92
8  Dhaval   Score      88
9  Hemang   Score      78

In this code, we created a sample DataFrame with ‘Name’, ‘Age’, and ‘Score’ columns.

In the next step, we melted the DataFrame using the ‘Name’ column as the identifier variable and ‘Age’ and ‘Score’ as the value variables.

The final DataFrame has a ‘Name’ column, an ‘Attribute’ column (variable column), and a ‘Value’ column.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.