0
0
Pandasdata~30 mins

Creating MultiIndex DataFrames in Pandas - Try It Yourself

Choose your learning style9 modes available
Creating MultiIndex DataFrames
📖 Scenario: You work in a company that tracks sales data across different regions and product categories. You want to organize this data in a clear way so you can analyze sales by region and category easily.
🎯 Goal: Build a pandas DataFrame with a MultiIndex using region and category as the two levels of the index.
📋 What You'll Learn
Create a pandas DataFrame with sales data for different regions and categories
Use a MultiIndex with two levels: 'Region' and 'Category'
Display the final DataFrame with the MultiIndex
💡 Why This Matters
🌍 Real World
MultiIndex DataFrames help organize complex data with multiple categories, like sales by region and product type, making analysis easier.
💼 Career
Data scientists and analysts often use MultiIndex DataFrames to handle hierarchical data and perform detailed group analysis.
Progress0 / 4 steps
1
Create the sales data dictionary
Create a dictionary called sales_data with these exact keys and values: 'Region' with the list ['North', 'North', 'South', 'South'], 'Category' with the list ['Electronics', 'Furniture', 'Electronics', 'Furniture'], and 'Sales' with the list [2500, 1500, 2000, 1200].
Pandas
Need a hint?

Use a dictionary with keys 'Region', 'Category', and 'Sales'. Each key should have a list of values.

2
Create the DataFrame from the dictionary
Create a pandas DataFrame called df from the sales_data dictionary.
Pandas
Need a hint?

Use pd.DataFrame() with sales_data as the argument.

3
Set MultiIndex using Region and Category
Use df.set_index() with the list ['Region', 'Category'] and inplace=True to set a MultiIndex on df.
Pandas
Need a hint?

Use df.set_index(['Region', 'Category'], inplace=True) to create the MultiIndex.

4
Display the MultiIndex DataFrame
Write a print() statement to display the DataFrame df with the MultiIndex.
Pandas
Need a hint?

Use print(df) to show the DataFrame with the MultiIndex.