0
0
Data Analysis Pythondata~30 mins

Melt for wide-to-long reshaping in Data Analysis Python - Mini Project: Build & Apply

Choose your learning style9 modes available
Melt for wide-to-long reshaping
📖 Scenario: You work in a small company that tracks monthly sales for different products. The sales data is stored in a table where each product has its own column for each month. This format is hard to analyze because the months are spread across columns.To make the data easier to analyze, you want to reshape it from wide format (many columns for months) to long format (one column for month and one for sales).
🎯 Goal: Learn how to use the pandas.melt() function to reshape a wide table into a long table. You will start with a dictionary of sales data, convert it to a DataFrame, then reshape it so each row shows a product, month, and sales value.
📋 What You'll Learn
Create a pandas DataFrame from a dictionary with product sales for three months
Define the columns to keep fixed during reshaping
Use pandas melt to reshape the DataFrame from wide to long format
Print the reshaped DataFrame
💡 Why This Matters
🌍 Real World
Data scientists often receive data in wide format, which is hard to analyze. Reshaping data to long format helps in plotting, grouping, and applying statistical methods.
💼 Career
Knowing how to reshape data with pandas melt is a key skill for data cleaning and preparation, essential for roles like data analyst, data scientist, and business intelligence specialist.
Progress0 / 4 steps
1
Create the sales data dictionary and DataFrame
Create a dictionary called sales_data with these exact entries: 'Product': ['A', 'B', 'C'], 'Jan': [100, 150, 200], 'Feb': [110, 160, 210], 'Mar': [120, 170, 220]. Then create a pandas DataFrame called df from sales_data.
Data Analysis Python
Hint

Use pd.DataFrame() to convert the dictionary to a DataFrame.

2
Define the id_vars for melting
Create a list called id_vars containing the column 'Product'. This tells pandas which column to keep fixed when reshaping.
Data Analysis Python
Hint

The id_vars list should include columns you want to keep as is.

3
Use pandas melt to reshape the DataFrame
Create a new DataFrame called df_long by using pd.melt() on df, with id_vars=id_vars, var_name='Month', and value_name='Sales'.
Data Analysis Python
Hint

Use pd.melt() with id_vars, var_name, and value_name parameters.

4
Print the reshaped DataFrame
Print the DataFrame df_long to see the data in long format.
Data Analysis Python
Hint

Use print(df_long) to display the reshaped DataFrame.