0
0
Pandasdata~30 mins

Long to wide format conversion in Pandas - Mini Project: Build & Apply

Choose your learning style9 modes available
Long to Wide Format Conversion with pandas
📖 Scenario: You work in a sales team that tracks monthly sales data for different products. The data is currently in a long format, where each row shows the sales of one product in one month. You want to convert this data into a wide format, where each product has one row and each month is a separate column showing the sales.
🎯 Goal: Convert a sales dataset from long format to wide format using pandas. You will create the initial data, set a configuration variable for the pivot, apply the pivot operation, and then display the final wide format table.
📋 What You'll Learn
Create a pandas DataFrame with sales data in long format
Create a variable to specify the column to pivot on
Use pandas pivot method to convert the data from long to wide format
Print the resulting wide format DataFrame
💡 Why This Matters
🌍 Real World
Sales teams and analysts often receive data in long format but need to see it in wide format for easier comparison and reporting.
💼 Career
Data scientists and analysts use data reshaping techniques like pivoting to prepare data for visualization, reporting, and further analysis.
Progress0 / 4 steps
1
Create the sales data in long format
Create a pandas DataFrame called sales_long with these exact columns and rows:
Product, Month, and Sales.
Include these rows exactly:
'A', 'Jan', 100, 'A', 'Feb', 120, 'B', 'Jan', 90, 'B', 'Feb', 110.
Pandas
Need a hint?

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

2
Set the pivot column variable
Create a variable called pivot_column and set it to the string 'Month'. This will be used to pivot the data by month.
Pandas
Need a hint?

Just assign the string 'Month' to the variable pivot_column.

3
Pivot the data from long to wide format
Use the pandas pivot method on sales_long to create a new DataFrame called sales_wide. Use 'Product' as the index, pivot_column as the columns, and 'Sales' as the values.
Pandas
Need a hint?

Use sales_long.pivot(index='Product', columns=pivot_column, values='Sales') to reshape the data.

4
Print the wide format DataFrame
Print the sales_wide DataFrame to display the sales data in wide format.
Pandas
Need a hint?

Use print(sales_wide) to show the wide format table.