Challenge - 5 Problems
Index Sorting Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ query_result
intermediate2:00remaining
What is the output of sorting a DataFrame by index with ascending=False?
Given the DataFrame
df with index [3, 1, 2] and values ["a", "b", "c"], what is the result of df.sort_index(ascending=False)?Pandas
import pandas as pd df = pd.DataFrame({'value': ['a', 'b', 'c']}, index=[3, 1, 2]) result = df.sort_index(ascending=False)
Attempts:
2 left
💡 Hint
Remember that ascending=False sorts from highest index to lowest.
✗ Incorrect
The sort_index method sorts the DataFrame by its index. With ascending=False, the order is from the largest index to the smallest, so indices 3, 2, then 1.
📝 Syntax
intermediate2:00remaining
Which option correctly sorts a DataFrame by its index in place?
You want to sort the DataFrame
df by its index and modify it directly without creating a new object. Which code does this correctly?Pandas
import pandas as pd df = pd.DataFrame({'val': [10, 20, 30]}, index=[2, 0, 1])
Attempts:
2 left
💡 Hint
Check the exact parameter name and its boolean value.
✗ Incorrect
The parameter to sort_index that modifies the DataFrame in place is 'inplace=True'. Other options either use wrong parameter names or values.
❓ optimization
advanced2:30remaining
How to efficiently sort a MultiIndex DataFrame by the second level index?
Given a DataFrame
df with a MultiIndex of two levels, which code sorts the DataFrame by the second level of the index only?Pandas
import pandas as pd index = pd.MultiIndex.from_tuples([(1, 'b'), (2, 'a'), (1, 'a')], names=['num', 'char']) df = pd.DataFrame({'val': [10, 20, 30]}, index=index)
Attempts:
2 left
💡 Hint
The 'level' parameter specifies which index level to sort by.
✗ Incorrect
Using level=1 sorts by the second level of the MultiIndex. Option A sorts by the first level. Option A uses a non-existent parameter 'by'. Option A sorts columns, not index.
🔧 Debug
advanced2:00remaining
Why does this sort_index call raise an error?
Consider the code:
df.sort_index(axis=2). Why does this raise an error?Pandas
import pandas as pd df = pd.DataFrame({'a': [1, 2], 'b': [3, 4]}) df.sort_index(axis=2)
Attempts:
2 left
💡 Hint
Check the valid axis values for DataFrame methods.
✗ Incorrect
DataFrames have only two axes: 0 for rows (index) and 1 for columns. Axis=2 is invalid and causes an error.
🧠 Conceptual
expert3:00remaining
What happens when you sort a DataFrame with a non-unique index using sort_index()?
If a DataFrame has duplicate index values, what is the behavior of
df.sort_index()?Attempts:
2 left
💡 Hint
Think about whether sorting requires unique index values.
✗ Incorrect
sort_index sorts rows by their index values regardless of duplicates. It does not raise errors or remove duplicates.