0
0
Pandasdata~15 mins

melt() for unpivoting in Pandas - Mini Project: Build & Apply

Choose your learning style9 modes available
Using melt() for unpivoting data in pandas
📖 Scenario: You work in a small bakery that tracks daily sales of different types of bread. The sales data is recorded in a table where each column is a bread type and each row is a day. You want to reshape this data to a long format to analyze sales more easily.
🎯 Goal: Learn how to use the pandas melt() function to unpivot a wide table into a long table with one column for bread type and one for sales.
📋 What You'll Learn
Create a pandas DataFrame with daily sales data for three bread types.
Define the columns to keep fixed during unpivoting.
Use melt() to transform the DataFrame from wide to long format.
Print the final melted DataFrame.
💡 Why This Matters
🌍 Real World
Unpivoting data is common when you want to convert wide tables into long tables for easier analysis and visualization.
💼 Career
Data analysts and scientists often reshape data using melt() to prepare it for charts, reports, or machine learning.
Progress0 / 4 steps
1
Create the sales DataFrame
Create a pandas DataFrame called sales_data with these exact columns and values:
'Day': ['Monday', 'Tuesday', 'Wednesday']
'Sourdough': [10, 12, 9]
'Baguette': [5, 7, 6]
'Rye': [3, 4, 2]
Pandas
Need a hint?

Use pd.DataFrame() with a dictionary where keys are column names and values are lists of data.

2
Define the id_vars for melting
Create a list called id_vars containing the column 'Day' to keep fixed during melting.
Pandas
Need a hint?

The id_vars list tells melt() which columns to keep as they are.

3
Use melt() to unpivot the DataFrame
Use pd.melt() on sales_data with id_vars=id_vars, var_name='Bread', and value_name='Sales'. Save the result in a variable called melted_data.
Pandas
Need a hint?

The melt() function turns columns into rows. Use var_name for the new column name of the old columns, and value_name for the values.

4
Print the melted DataFrame
Print the variable melted_data to see the unpivoted sales data.
Pandas
Need a hint?

Use print(melted_data) to display the final table.