0
0
Pandasdata~30 mins

Why MultiIndex enables hierarchical data in Pandas - See It in Action

Choose your learning style9 modes available
Why MultiIndex enables hierarchical data
📖 Scenario: Imagine you work in a store that sells different types of fruits in different cities. You want to organize the sales data so you can easily see sales by city and fruit type.
🎯 Goal: You will create a pandas DataFrame with sales data using a MultiIndex. This will help you understand how MultiIndex allows hierarchical data organization.
📋 What You'll Learn
Create a pandas DataFrame with a MultiIndex from tuples of city and fruit
Add sales data as a column in the DataFrame
Access data using the MultiIndex
Print the final DataFrame to see the hierarchical structure
💡 Why This Matters
🌍 Real World
Stores and businesses often have data that naturally groups by categories like location and product type. MultiIndex helps organize and analyze such data easily.
💼 Career
Data analysts and scientists use MultiIndex in pandas to handle complex datasets with multiple grouping levels, making data exploration and reporting more efficient.
Progress0 / 4 steps
1
Create sales data with city and fruit tuples
Create a list called index_tuples with these exact tuples: ('New York', 'Apple'), ('New York', 'Banana'), ('Los Angeles', 'Apple'), ('Los Angeles', 'Banana').
Pandas
Need a hint?

Use a list of tuples where each tuple has a city and a fruit name.

2
Create a MultiIndex from the tuples
Import pandas as pd and create a MultiIndex called multi_index from the list index_tuples using pd.MultiIndex.from_tuples() with names ['City', 'Fruit'].
Pandas
Need a hint?

Use pd.MultiIndex.from_tuples() and set the names parameter.

3
Create a DataFrame with sales data using the MultiIndex
Create a pandas DataFrame called sales_df with a column 'Sales' containing the values [100, 150, 200, 250] and use multi_index as the index.
Pandas
Need a hint?

Use pd.DataFrame() with a dictionary for the column and set the index parameter.

4
Print the DataFrame to see the hierarchical index
Write a print statement to display the DataFrame sales_df.
Pandas
Need a hint?

Use print(sales_df) to show the DataFrame.