Challenge - 5 Problems
Index Sorting Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ query_result
intermediate2:00remaining
Sorting a DataFrame by index ascending
Given the DataFrame below, what is the output after sorting by index in ascending order?
import pandas as pd
df = pd.DataFrame({
'A': [3, 1, 2],
'B': [9, 8, 7]
}, index=['c', 'a', 'b'])
sorted_df = df.sort_index()Pandas
import pandas as pd df = pd.DataFrame({ 'A': [3, 1, 2], 'B': [9, 8, 7] }, index=['c', 'a', 'b']) sorted_df = df.sort_index() print(sorted_df)
Attempts:
2 left
💡 Hint
Sorting by index with default parameters sorts in ascending order alphabetically.
✗ Incorrect
The DataFrame is sorted by its index labels alphabetically: 'a', 'b', then 'c'.
❓ query_result
intermediate2:00remaining
Sorting a DataFrame by index descending
What is the output of sorting the following DataFrame by index in descending order?
import pandas as pd
df = pd.DataFrame({
'X': [10, 20, 30],
'Y': [100, 200, 300]
}, index=[2, 1, 3])
sorted_df = df.sort_index(ascending=False)
print(sorted_df)Pandas
import pandas as pd df = pd.DataFrame({ 'X': [10, 20, 30], 'Y': [100, 200, 300] }, index=[2, 1, 3]) sorted_df = df.sort_index(ascending=False) print(sorted_df)
Attempts:
2 left
💡 Hint
Descending order means largest index first.
✗ Incorrect
Sorting by index descending orders rows by index 3, 2, then 1.
📝 Syntax
advanced2:00remaining
Identify the syntax error in sorting by index
Which option contains a syntax error when trying to sort a DataFrame by index?
Pandas
import pandas as pd df = pd.DataFrame({'A':[1,2]}, index=[1,0])
Attempts:
2 left
💡 Hint
Check the use of assignment vs comparison operators in function arguments.
✗ Incorrect
Using 'ascending==False' is a comparison expression, not a keyword argument assignment, causing a syntax error.
❓ query_result
advanced2:30remaining
Sorting a MultiIndex DataFrame by level
Given the MultiIndex DataFrame below, what is the output after sorting by the second level of the index?
import pandas as pd
index = pd.MultiIndex.from_tuples([('a', 2), ('a', 1), ('b', 1), ('b', 2)])
df = pd.DataFrame({'val': [10, 20, 30, 40]}, index=index)
sorted_df = df.sort_index(level=1)
print(sorted_df)Pandas
import pandas as pd index = pd.MultiIndex.from_tuples([('a', 2), ('a', 1), ('b', 1), ('b', 2)]) df = pd.DataFrame({'val': [10, 20, 30, 40]}, index=index) sorted_df = df.sort_index(level=1) print(sorted_df)
Attempts:
2 left
💡 Hint
Sorting by level=1 sorts by the second index value across all first-level groups.
✗ Incorrect
Rows are ordered by the second index level: 1, 1, 2, 2, preserving first level order within ties.
🧠 Conceptual
expert2:30remaining
Effect of inplace parameter in sort_index
What is the effect of using
inplace=True when calling df.sort_index() on a DataFrame?Attempts:
2 left
💡 Hint
Consider what inplace means in pandas methods.
✗ Incorrect
Using inplace=True modifies the original DataFrame directly and returns None.