Instagram
youtube
Facebook
Twitter

Unpivot a Pandas DataFrame using Melt

 

A Unpivot a Pandas DataFrame using Melt?
Code Explanation:
Unpivoting: The pd.melt() function is used to convert a wide-form DataFrame (columns as variables) into a long-form     format (rows as observations).
Reset Index: Before melting, .reset_index() is used so that 'Date' becomes a column again (required for id_vars).
Store Result: The result of melting is stored in the variable melted_df.
Output Display: The reshaped long-form DataFrame is printed with columns: Date, Product, and Sales.

 

Program:

import pandas as pd

data = pd.DataFrame({
    'Date': ['Jan', 'Jan', 'Feb'],
    'Product': ['A', 'B', 'A'],
    'Sales': [100, 150, 200]
})

pivot_df = data.pivot(index='Date', columns='Product', values='Sales')

melted_df = pd.melt(pivot_df.reset_index(), id_vars='Date', var_name='Product', value_name='Sales')

print(melted_df)