0
0
Pandasdata~30 mins

Sorting MultiIndex in Pandas - Mini Project: Build & Apply

Choose your learning style9 modes available
Sorting MultiIndex
📖 Scenario: You work in a company that tracks sales data by region and product category. The data is stored in a table with two levels of row labels: the region and the product category. You want to organize this data so it is easier to analyze by sorting the rows based on these labels.
🎯 Goal: Create a pandas DataFrame with a MultiIndex for regions and product categories, then sort the DataFrame by the MultiIndex to organize the data.
📋 What You'll Learn
Create a pandas DataFrame with a MultiIndex using the exact regions and product categories given.
Add a configuration variable to specify sorting order.
Sort the DataFrame by the MultiIndex using the specified order.
Print the sorted DataFrame to show the result.
💡 Why This Matters
🌍 Real World
Companies often store data with multiple levels of categories, like region and product type. Sorting this data helps in clear reporting and analysis.
💼 Career
Data analysts and scientists frequently work with MultiIndex data in pandas to organize and analyze complex datasets efficiently.
Progress0 / 4 steps
1
Create a MultiIndex DataFrame
Create a pandas DataFrame called sales with a MultiIndex from the tuples [('East', 'Furniture'), ('East', 'Technology'), ('West', 'Furniture'), ('West', 'Technology')]. Use the sales values [1000, 1500, 1200, 1300] for a column named 'Sales'.
Pandas
Need a hint?

Use pd.MultiIndex.from_tuples to create the MultiIndex and then create the DataFrame with the Sales column.

2
Set sorting order configuration
Create a variable called sort_ascending and set it to True to specify that sorting should be in ascending order.
Pandas
Need a hint?

Just create a variable named sort_ascending and assign it the value True.

3
Sort the MultiIndex DataFrame
Sort the DataFrame sales by its MultiIndex using the variable sort_ascending to control ascending order. Assign the sorted DataFrame back to sales.
Pandas
Need a hint?

Use sales.sort_index(ascending=sort_ascending) and assign it back to sales.

4
Display the sorted DataFrame
Print the sorted DataFrame sales to display the organized sales data.
Pandas
Need a hint?

Use print(sales) to show the sorted DataFrame.