0
0
Pandasdata~30 mins

Wide to long format conversion in Pandas - Mini Project: Build & Apply

Choose your learning style9 modes available
Wide to Long Format Conversion
📖 Scenario: You work in a small company that tracks monthly sales data for different products. The sales data is currently stored in a wide format, where each month is a separate column. Your manager wants the data in a long format to analyze trends easily.
🎯 Goal: Convert the sales data from wide format to long format using pandas. You will create a DataFrame, set up the necessary configuration, apply the conversion, and display the final long format data.
📋 What You'll Learn
Create a pandas DataFrame with given sales data in wide format
Create a list of month columns to convert
Use pandas melt function to convert wide format to long format
Print the resulting long format DataFrame
💡 Why This Matters
🌍 Real World
Data often comes in wide format from reports or spreadsheets. Converting it to long format helps in easier analysis and visualization.
💼 Career
Data scientists and analysts frequently reshape data to prepare it for analysis, reporting, and visualization tasks.
Progress0 / 4 steps
1
Create the sales data DataFrame
Create a pandas DataFrame called sales_data with these exact values: columns 'Product', 'Jan', 'Feb', 'Mar' and rows: 'A', 100, 150, 200, 'B', 80, 120, 160, 'C', 90, 110, 130.
Pandas
Need a hint?

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

2
Create a list of month columns
Create a list called months containing the strings 'Jan', 'Feb', and 'Mar' to represent the month columns.
Pandas
Need a hint?

Simply assign the list of month names to the variable months.

3
Convert wide format to long format
Use the pandas melt function on sales_data to convert it to long format. Store the result in a variable called long_format. Use id_vars='Product', value_vars=months, var_name='Month', and value_name='Sales' as parameters.
Pandas
Need a hint?

Use pd.melt with the correct parameters to reshape the DataFrame.

4
Display the long format DataFrame
Print the long_format DataFrame to display the converted data.
Pandas
Need a hint?

Use print(long_format) to show the DataFrame.