Challenge - 5 Problems
Sort Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of sorting DataFrame by one column ascending
What is the output of this code snippet that sorts the DataFrame by column 'Age' in ascending order?
Pandas
import pandas as pd df = pd.DataFrame({ 'Name': ['Alice', 'Bob', 'Charlie'], 'Age': [25, 30, 20] }) sorted_df = df.sort_values(by='Age') print(sorted_df)
Attempts:
2 left
💡 Hint
Remember that sort_values(by='Age') sorts the rows by the 'Age' column in ascending order by default.
✗ Incorrect
The DataFrame is sorted by the 'Age' column from smallest to largest. Charlie (20) comes first, then Alice (25), then Bob (30). The original index is preserved.
❓ data_output
intermediate1:30remaining
Number of rows after sorting by a single column
After sorting this DataFrame by the 'Score' column, how many rows does the resulting DataFrame have?
Pandas
import pandas as pd df = pd.DataFrame({ 'Student': ['Ann', 'Ben', 'Cara', 'Dan'], 'Score': [88, 92, 85, 90] }) sorted_df = df.sort_values(by='Score') print(len(sorted_df))
Attempts:
2 left
💡 Hint
Sorting does not remove or add rows; it only changes their order.
✗ Incorrect
Sorting a DataFrame by a column does not change the number of rows. The original 4 rows remain.
🔧 Debug
advanced2:00remaining
Identify the error in sorting by a single column
What error does this code produce when trying to sort the DataFrame by column 'Height'?
Pandas
import pandas as pd df = pd.DataFrame({ 'Name': ['Eva', 'Frank'], 'Weight': [55, 70] }) sorted_df = df.sort_values(by='Height')
Attempts:
2 left
💡 Hint
Check if the column name exists in the DataFrame before sorting.
✗ Incorrect
The DataFrame does not have a 'Height' column, so pandas raises a KeyError when trying to sort by it.
🧠 Conceptual
advanced1:30remaining
Effect of inplace=True in sort_values()
What is the effect of using inplace=True in the sort_values() method on a DataFrame?
Attempts:
2 left
💡 Hint
inplace=True means the operation modifies the original object directly.
✗ Incorrect
Using inplace=True sorts the original DataFrame in place and returns None, so no new DataFrame is created.
🚀 Application
expert2:30remaining
Sorting and resetting index in a DataFrame
Given this DataFrame, which option correctly sorts by 'Salary' descending and resets the index to start from 0?
Pandas
import pandas as pd df = pd.DataFrame({ 'Employee': ['John', 'Jane', 'Doe'], 'Salary': [50000, 60000, 55000] })
Attempts:
2 left
💡 Hint
Remember to sort descending and reset index without keeping old index as a column.
✗ Incorrect
Option A sorts by Salary descending and resets the index dropping the old one, producing a clean DataFrame with index 0,1,2.