Bird
Raised Fist0
Pandasdata~20 mins

Sorting MultiIndex in Pandas - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
MultiIndex Sorting Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of sorting a MultiIndex DataFrame by level
What is the output of the following code snippet?
Pandas
import pandas as pd

index = pd.MultiIndex.from_tuples([('b', 2), ('a', 1), ('b', 1), ('a', 2)])
df = pd.DataFrame({'value': [4, 3, 2, 1]}, index=index)
sorted_df = df.sort_index(level=0)
print(sorted_df)
A
       value
(b, 1)      2
(b, 2)      4
(a, 1)      3
(a, 2)      1
B
       value
(a, 1)      3
(a, 2)      1
(b, 1)      2
(b, 2)      4
C
       value
(a, 2)      1
(a, 1)      3
(b, 2)      4
(b, 1)      2
D
       value
(b, 2)      4
(b, 1)      2
(a, 2)      1
(a, 1)      3
Attempts:
2 left
💡 Hint
Sorting by level=0 sorts by the first index level alphabetically.
❓ data_output
intermediate
1:30remaining
Number of rows after sorting MultiIndex with ascending=False
Given the following DataFrame, how many rows does the sorted DataFrame have after sorting by both levels descending?
Pandas
import pandas as pd

index = pd.MultiIndex.from_tuples([('x', 3), ('y', 1), ('x', 1), ('y', 2)])
df = pd.DataFrame({'score': [10, 20, 30, 40]}, index=index)
sorted_df = df.sort_index(level=[0,1], ascending=False)
print(len(sorted_df))
A1
B2
C3
D4
Attempts:
2 left
💡 Hint
Sorting does not remove rows, it only reorders them.
🔧 Debug
advanced
1:30remaining
Identify the error in sorting MultiIndex with invalid level
What error does the following code raise?
Pandas
import pandas as pd

index = pd.MultiIndex.from_tuples([('a', 1), ('b', 2)])
df = pd.DataFrame({'val': [5, 6]}, index=index)
sorted_df = df.sort_index(level=2)
print(sorted_df)
AIndexError: Too many levels: Index has only 2 levels, not 3
BNo error, prints sorted DataFrame
CTypeError: level must be int or str
DKeyError: 2
Attempts:
2 left
💡 Hint
Check the number of levels in the MultiIndex before sorting by level.
🚀 Application
advanced
2:00remaining
Sorting MultiIndex DataFrame by multiple levels with mixed ascending order
You have a MultiIndex DataFrame with two levels: 'city' and 'year'. You want to sort it so that cities are in ascending order but years are in descending order. Which code snippet achieves this?
Pandas
import pandas as pd

index = pd.MultiIndex.from_tuples([('NY', 2020), ('LA', 2019), ('NY', 2019), ('LA', 2020)])
df = pd.DataFrame({'population': [8, 4, 7, 5]}, index=index)
Adf.sort_index(level=['city', 'year'], ascending=[True, False])
Bdf.sort_index(level=['city', 'year'], ascending=[False, True])
Cdf.sort_index(level=[0, 1], ascending=[False, False])
Ddf.sort_index(level=[1, 0], ascending=[True, False])
Attempts:
2 left
💡 Hint
The ascending parameter accepts a list matching the levels order.
🧠 Conceptual
expert
1:30remaining
Effect of sort_index on MultiIndex with duplicates
Consider a MultiIndex DataFrame with duplicate index entries. What is the effect of calling sort_index() on this DataFrame?
AIt raises an error because duplicates are not allowed in MultiIndex.
BIt removes duplicate index entries and sorts the DataFrame.
CIt sorts the DataFrame by the MultiIndex levels but keeps duplicate index entries intact.
DIt sorts the DataFrame and resets the index to default integers.
Attempts:
2 left
💡 Hint
Think about whether sorting changes data or just order.

Practice

(1/5)
1. What does sorting a MultiIndex in pandas do?
easy
A. It removes duplicate rows from the DataFrame.
B. It merges multiple DataFrames into one.
C. It changes the data types of the index levels.
D. It arranges the data based on one or more index levels in order.

Solution

  1. Step 1: Understand MultiIndex structure

    A MultiIndex has multiple levels that can be sorted independently or together.
  2. Step 2: Define sorting effect

    Sorting organizes rows by the values in these index levels, making data easier to analyze.
  3. Final Answer:

    It arranges the data based on one or more index levels in order. -> Option D
  4. Quick Check:

    Sorting MultiIndex = Arrange by index levels [OK]
Hint: Sorting MultiIndex orders data by index levels [OK]
Common Mistakes:
  • Confusing sorting with removing duplicates
  • Thinking sorting changes data types
  • Mixing sorting with merging DataFrames
2. Which of the following is the correct syntax to sort a pandas DataFrame df by its MultiIndex?
easy
A. df.sort(level=[0,1], ascending=[True, False])
B. df.sort_values(by=['level_0', 'level_1'])
C. df.sort_index(level=[0,1], ascending=[True, False])
D. df.sort_index(by=['level_0', 'level_1'])

Solution

  1. Step 1: Recall sorting MultiIndex method

    Use sort_index() to sort by index levels, specifying levels and order.
  2. Step 2: Check syntax correctness

    df.sort_index(level=[0,1], ascending=[True, False]) correctly uses sort_index(level=[0,1], ascending=[True, False]). Others use wrong methods or parameters.
  3. Final Answer:

    df.sort_index(level=[0,1], ascending=[True, False]) -> Option C
  4. Quick Check:

    sort_index with level and ascending = correct syntax [OK]
Hint: Use sort_index(level=..., ascending=...) for MultiIndex [OK]
Common Mistakes:
  • Using sort_values instead of sort_index for MultiIndex
  • Passing 'by' parameter to sort_index
  • Using deprecated sort() method
3. Given the following code, what will be the order of the MultiIndex after sorting?
import pandas as pd
index = pd.MultiIndex.from_tuples([('b', 2), ('a', 3), ('b', 1), ('a', 2)])
df = pd.DataFrame({'value': [10, 20, 30, 40]}, index=index)
sorted_df = df.sort_index(level=[0,1], ascending=[True, False])
print(sorted_df.index.tolist())
medium
A. [('a', 3), ('a', 2), ('b', 2), ('b', 1)]
B. [('a', 2), ('a', 3), ('b', 1), ('b', 2)]
C. [('b', 1), ('b', 2), ('a', 2), ('a', 3)]
D. [('b', 2), ('b', 1), ('a', 3), ('a', 2)]

Solution

  1. Step 1: Understand sorting parameters

    Level 0 sorted ascending (a before b), level 1 descending (higher number first).
  2. Step 2: Apply sorting to tuples

    For 'a': (3,2) sorted descending gives (3), then (2). For 'b': (2,1) sorted descending gives (2), then (1).
  3. Final Answer:

    [('a', 3), ('a', 2), ('b', 2), ('b', 1)] -> Option A
  4. Quick Check:

    Level 0 asc, Level 1 desc = [('a',3),('a',2),('b',2),('b',1)] [OK]
Hint: Sort level 0 ascending, level 1 descending to get correct order [OK]
Common Mistakes:
  • Sorting both levels ascending by default
  • Confusing ascending order for level 1
  • Not matching index tuples correctly
4. You run this code but get an error:
df.sort_index(level=[0,1], ascending=True, inplace=True)

What is the likely cause?
medium
A. The 'ascending' parameter must be a list when sorting multiple levels.
B. The 'inplace' parameter is not supported in sort_index.
C. The 'level' parameter cannot accept a list.
D. The DataFrame does not have a MultiIndex.

Solution

  1. Step 1: Check parameter types for multiple levels

    When sorting multiple levels, 'ascending' must be a list matching levels count.
  2. Step 2: Identify error cause

    Passing a single boolean True instead of a list causes a ValueError.
  3. Final Answer:

    The 'ascending' parameter must be a list when sorting multiple levels. -> Option A
  4. Quick Check:

    ascending list needed for multiple levels [OK]
Hint: Use list for ascending when sorting multiple levels [OK]
Common Mistakes:
  • Passing single bool to ascending with multiple levels
  • Assuming inplace is unsupported
  • Misunderstanding level parameter type
5. You have a MultiIndex DataFrame with levels 'Country' and 'Year'. You want to sort it so that 'Country' is ascending but 'Year' is descending, and then reset the index to get a flat DataFrame sorted accordingly. Which code snippet achieves this?
hard
A. df.sort_values(by=['Country', 'Year'], ascending=[True, False]).reset_index(drop=True)
B. df.sort_index(level=['Country', 'Year'], ascending=[True, False]).reset_index()
C. df.sort_index(level=['Country', 'Year'], ascending=[False, True]).reset_index()
D. df.sort_values(by=['Year', 'Country'], ascending=[False, True]).reset_index()

Solution

  1. Step 1: Choose correct sorting method for MultiIndex

    Use sort_index() with levels and ascending list to sort MultiIndex properly.
  2. Step 2: Reset index to flatten DataFrame

    Calling reset_index() converts MultiIndex to columns, preserving sorted order.
  3. Final Answer:

    df.sort_index(level=['Country', 'Year'], ascending=[True, False]).reset_index() -> Option B
  4. Quick Check:

    sort_index with levels + reset_index = correct approach [OK]
Hint: Use sort_index with ascending list, then reset_index [OK]
Common Mistakes:
  • Using sort_values instead of sort_index for MultiIndex
  • Wrong ascending order for levels
  • Forgetting to reset index after sorting
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard