A MultiIndex is a way to have multiple levels of indexing on rows or columns in a pandas DataFrame or Series. It helps organize data with hierarchical labels.
Click to reveal answer
beginner
How do you select data from a MultiIndex DataFrame using .loc?
You use .loc with tuples to specify values at each level of the MultiIndex. For example, df.loc[(level1_value, level2_value)] selects rows matching those index levels.
Click to reveal answer
intermediate
What does df.xs() do in pandas with MultiIndex?
The xs() method extracts a cross-section from a MultiIndex DataFrame. You can select data at a particular level of the index easily without specifying all levels.
Click to reveal answer
intermediate
How can you select all data for a specific value in one level of a MultiIndex?
You can use df.loc with pd.IndexSlice or df.xs specifying the level name or number to select all rows matching that value in that level.
Click to reveal answer
beginner
What is the benefit of using MultiIndex for data selection?
MultiIndex allows you to organize complex data hierarchically and select subsets easily by specifying index levels, making data analysis clearer and more efficient.
Click to reveal answer
Which method allows selecting data at a specific level in a MultiIndex DataFrame?
Apivot()
Bgroupby()
Cmerge()
Dxs()
✗ Incorrect
The xs() method extracts a cross-section at a specific level in a MultiIndex DataFrame.
How do you select a row with MultiIndex levels 'A' and 1 using .loc?
Adf.loc['A', 1]
Bdf.loc[('A', 1)]
Cdf.loc['A'][1]
Ddf.loc[1, 'A']
✗ Incorrect
You must pass a tuple with the index values to .loc for MultiIndex selection: df.loc[('A', 1)].
What does df.loc[pd.IndexSlice[:, 'x']] select in a MultiIndex DataFrame?
AAll rows where second level index is 'x'
BAll rows where first level index is 'x'
CAll rows where any level is 'x'
DNo rows
✗ Incorrect
pd.IndexSlice[:, 'x'] selects all rows with any first level and second level equal to 'x'.
Which of these is NOT a way to select data in a MultiIndex DataFrame?
AUsing .groupby() to filter
BUsing .xs() method
CUsing .append() method
DUsing .loc with tuples
✗ Incorrect
.append() is used to add rows, not to select data.
If you want to select all rows with first level index 'B', which is the simplest method?
AAll of the above
Bdf.xs('B')
Cdf.loc[('B',)]
Ddf.loc['B']
✗ Incorrect
All these methods select rows where the first level index is 'B'.
Explain how to select data from a pandas DataFrame with a MultiIndex using .loc and xs().
Think about how you specify index values for multiple levels.
You got /3 concepts.
Describe a real-life example where MultiIndex selection would help organize and analyze data.
Imagine a store tracking sales by city and month.
You got /3 concepts.
Practice
(1/5)
1. What does df.loc[('A', 1)] do when df has a MultiIndex with two levels?
easy
A. Selects the row where the first level is 'A' and the second level is 1.
B. Selects all rows where the first level is 'A' regardless of the second level.
C. Selects all rows where the second level is 1 regardless of the first level.
D. Raises an error because tuples cannot be used with MultiIndex.
Solution
Step 1: Understand MultiIndex selection with tuples
Using df.loc with a tuple selects rows matching each level in the MultiIndex exactly.
Step 2: Apply tuple to select specific row
The tuple ('A', 1) matches the first level 'A' and second level 1, selecting that exact row.
Final Answer:
Selects the row where the first level is 'A' and the second level is 1. -> Option A
Quick Check:
Tuple in loc = exact MultiIndex row [OK]
Hint: Use full tuple in loc to select exact MultiIndex row [OK]
Common Mistakes:
Thinking partial tuple selects exact row
Confusing level order in tuple
Believing tuple usage causes error
2. Which of the following is the correct tuple syntax to select all rows where the first level of a MultiIndex is 'B' using df.loc?
easy
A. df.loc[('B')]
B. df.loc[('B',)]
C. df.loc['B']
D. df.loc[['B']]
Solution
Step 1: Understand tuple syntax for single element
To specify a single-element tuple in Python, a comma is needed: ('B',).
Step 2: Use tuple in df.loc to select first level
Using df.loc[('B',)] selects all rows where the first level is 'B'.
Final Answer:
df.loc[('B',)] -> Option B
Quick Check:
Single-element tuple needs comma [OK]
Hint: Use comma for single-element tuple in loc [OK]
Common Mistakes:
Using parentheses without comma for tuple
Using list instead of tuple
Omitting tuple and causing key error
3. Given the DataFrame df with MultiIndex levels 'Letter' and 'Number':
import pandas as pd
index = pd.MultiIndex.from_tuples([('A', 1), ('A', 2), ('B', 1), ('B', 2)], names=['Letter', 'Number'])
data = [10, 20, 30, 40]
df = pd.DataFrame(data, index=index, columns=['Value'])
print(df.loc['A'])
What is the output?
medium
A. Value\nLetter Number\nA 1 10\n 2 20
B. Value\nLetter Number\nB 1 30\n 2 40
C. KeyError because 'A' is not a valid index
D. Value\nNumber\n1 10\n2 20
Solution
Step 1: Understand partial selection with single label
Using df.loc['A'] selects all rows where the first level is 'A'. The result is a DataFrame indexed by the second level only.
Step 2: Check output structure
The output shows 'Value' column with index 'Number' 1 and 2, values 10 and 20 respectively.
Final Answer:
Value
Number
1 10
2 20 -> Option D
Quick Check:
Partial index selection drops first level [OK]
Hint: Partial loc drops selected level from index [OK]
Common Mistakes:
Expecting full MultiIndex in output
Confusing which levels remain after selection
Thinking KeyError occurs for valid label
4. Consider this code snippet:
import pandas as pd
index = pd.MultiIndex.from_tuples([('X', 1), ('X', 2), ('Y', 1)])
data = [100, 200, 300]
df = pd.DataFrame(data, index=index, columns=['Score'])
# Attempt to select all rows where first level is 'X'
result = df.loc[('X')]
print(result)
What is the issue and how to fix it?
medium
A. SyntaxError; fix by removing parentheses: df.loc['X'].
B. Raises KeyError; fix by using df.loc[('X',)] to specify single-element tuple.
C. No issue; code runs correctly and prints rows with first level 'X'.
D. Raises TypeError; fix by converting 'X' to list: df.loc[['X']].
Solution
Step 1: Analyze the tuple usage in df.loc
Here, df.loc[('X')] is equivalent to df.loc['X'] because parentheses around a string do not create a tuple.
Step 2: Confirm code behavior
This selects all rows where the first level is 'X' correctly, so no error occurs.
Final Answer:
No issue; code runs correctly and prints rows with first level 'X'. -> Option C
5. You have a MultiIndex DataFrame df with levels 'City', 'Year', and 'Month'. How do you select all data for 'New York' in 2023 regardless of month using a tuple that specifies all three levels?
hard
A. df.loc[('New York', 2023, slice(None))]
B. df.loc[('New York', 2023)]
C. df.loc[('New York', 2023,)]
D. df.loc['New York', 2023]
Solution
Step 1: Understand MultiIndex with 3 levels
The MultiIndex has three levels: 'City', 'Year', and 'Month'. To select all months for 'New York' and 2023, we must specify all three levels.
Step 2: Use slice(None) to select all in third level
Using slice(None) in the third position selects all months. So df.loc[('New York', 2023, slice(None))] selects all rows matching city and year, any month.
Final Answer:
df.loc[('New York', 2023, slice(None))] -> Option A
Quick Check:
Use slice(None) for full level selection [OK]
Hint: Use slice(None) for full selection in MultiIndex level [OK]
Common Mistakes:
Omitting third level causing KeyError
Using incomplete tuple without slice
Using comma-separated loc without tuple
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.