Challenge - 5 Problems
Sorting Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Sorting a DataFrame by one column ascending
What is the output of this code snippet sorting the DataFrame by column 'A' in ascending order?
Pandas
import pandas as pd df = pd.DataFrame({'A': [3, 1, 2], 'B': [9, 8, 7]}) sorted_df = df.sort_values(by='A', ascending=True) print(sorted_df)
Attempts:
2 left
💡 Hint
Remember ascending=True means smallest to largest values.
✗ Incorrect
The DataFrame is sorted by column 'A' from smallest to largest. The index order changes accordingly.
❓ Predict Output
intermediate2:00remaining
Sorting a DataFrame by multiple columns with mixed order
What is the output of this code sorting by column 'A' ascending and 'B' descending?
Pandas
import pandas as pd df = pd.DataFrame({'A': [1, 1, 2, 2], 'B': [3, 4, 1, 2]}) sorted_df = df.sort_values(by=['A', 'B'], ascending=[True, False]) print(sorted_df)
Attempts:
2 left
💡 Hint
First sort by 'A' ascending, then by 'B' descending within each 'A' group.
✗ Incorrect
Rows with 'A' = 1 come first, sorted by 'B' descending (4 then 3). Then rows with 'A' = 2 sorted by 'B' descending (2 then 1).
❓ data_output
advanced1:30remaining
Number of rows after sorting by descending order
After sorting this DataFrame by column 'score' descending, how many rows remain in the result?
Pandas
import pandas as pd df = pd.DataFrame({'name': ['Ann', 'Bob', 'Cara'], 'score': [88, 92, 85]}) sorted_df = df.sort_values(by='score', ascending=False) print(len(sorted_df))
Attempts:
2 left
💡 Hint
Sorting does not remove rows, it only changes order.
✗ Incorrect
Sorting keeps all rows, so the length remains the same as original DataFrame.
🔧 Debug
advanced1:30remaining
Identify the error in sorting code
What error does this code raise when trying to sort a DataFrame?
Pandas
import pandas as pd df = pd.DataFrame({'X': [1, 2], 'Y': [3, 4]}) sorted_df = df.sort_values(by='Z')
Attempts:
2 left
💡 Hint
Check if the column name exists in the DataFrame.
✗ Incorrect
The column 'Z' does not exist in the DataFrame, so pandas raises a KeyError.
🚀 Application
expert2:30remaining
Sorting and resetting index in a DataFrame
After sorting the DataFrame by column 'age' descending, which option correctly resets the index to default integers?
Pandas
import pandas as pd df = pd.DataFrame({'name': ['Tom', 'Jerry', 'Spike'], 'age': [5, 3, 7]}) sorted_df = df.sort_values(by='age', ascending=False)
Attempts:
2 left
💡 Hint
To remove old index and update in place, use drop=True and inplace=True.
✗ Incorrect
Option C resets the index in place and drops the old index, so the DataFrame has a clean integer index.