Bird
Raised Fist0
Pandasdata~20 mins

sort_values() by single column in Pandas - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Sort Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2: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)
A
     Name  Age
2  Charlie   20
0    Alice   25
1      Bob   30
B
     Name  Age
0    Alice   25
1      Bob   30
2  Charlie   20
C
     Name  Age
1      Bob   30
0    Alice   25
2  Charlie   20
D
     Name  Age
2  Charlie   20
1      Bob   30
0    Alice   25
Attempts:
2 left
💡 Hint
Remember that sort_values(by='Age') sorts the rows by the 'Age' column in ascending order by default.
❓ data_output
intermediate
1: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))
A0
B3
C4
D1
Attempts:
2 left
💡 Hint
Sorting does not remove or add rows; it only changes their order.
🔧 Debug
advanced
2: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')
AValueError: Cannot sort by multiple columns
BNo error, returns sorted DataFrame
CTypeError: unsupported operand type(s) for <
DKeyError: 'Height'
Attempts:
2 left
💡 Hint
Check if the column name exists in the DataFrame before sorting.
🧠 Conceptual
advanced
1:30remaining
Effect of inplace=True in sort_values()
What is the effect of using inplace=True in the sort_values() method on a DataFrame?
AThe method raises an error because inplace is not a valid argument.
BThe original DataFrame is sorted and updated without creating a new DataFrame.
CThe DataFrame is sorted but the changes are lost after the method call.
DA new sorted DataFrame is returned, and the original remains unchanged.
Attempts:
2 left
💡 Hint
inplace=True means the operation modifies the original object directly.
🚀 Application
expert
2: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]
})
Adf.sort_values(by='Salary', ascending=False).reset_index(drop=True)
Bdf.sort_values(by='Salary', ascending=True).reset_index()
Cdf.reset_index().sort_values(by='Salary', ascending=False)
Ddf.sort_values('Salary', ascending=False, inplace=True).reset_index(drop=True)
Attempts:
2 left
💡 Hint
Remember to sort descending and reset index without keeping old index as a column.

Practice

(1/5)
1. What does the sort_values() function do in pandas when used on a DataFrame?
easy
A. It filters rows based on a condition.
B. It changes the data type of a column.
C. It sorts the DataFrame rows based on the values in a specified column.
D. It adds a new column to the DataFrame.

Solution

  1. Step 1: Understand the purpose of sort_values()

    This function is used to reorder rows in a DataFrame based on the values in one or more columns.
  2. Step 2: Compare with other options

    Changing data types, filtering rows, or adding columns are done by different functions, not sort_values().
  3. Final Answer:

    It sorts the DataFrame rows based on the values in a specified column. -> Option C
  4. Quick Check:

    sort_values() = reorder rows by column [OK]
Hint: Remember: sort_values() orders rows by column values [OK]
Common Mistakes:
  • Confusing sorting with filtering
  • Thinking it changes data types
  • Assuming it adds columns
2. Which of the following is the correct syntax to sort a DataFrame df by the column 'age' in ascending order?
easy
A. df.sort_values(by='age', ascending=True)
B. df.sort_values('age', ascending=False)
C. df.sort(by='age', ascending=True)
D. df.sort_values(by='age', ascending='yes')

Solution

  1. Step 1: Check the correct function and parameters

    The function is sort_values() and it requires the parameter by='column_name'. The ascending parameter should be a boolean.
  2. Step 2: Validate each option

    df.sort_values(by='age', ascending=True) uses correct function and parameters. df.sort_values('age', ascending=False) has ascending=False (descending). df.sort(by='age', ascending=True) uses wrong function sort(). df.sort_values(by='age', ascending='yes') uses a string instead of boolean for ascending.
  3. Final Answer:

    df.sort_values(by='age', ascending=True) -> Option A
  4. Quick Check:

    Correct syntax = df.sort_values(by='age', ascending=True) [OK]
Hint: Use by='column' and ascending=True/False in sort_values() [OK]
Common Mistakes:
  • Using sort() instead of sort_values()
  • Passing ascending as string instead of boolean
  • Omitting 'by' keyword
3. Given the DataFrame:
import pandas as pd
df = pd.DataFrame({'name': ['Anna', 'Bob', 'Cara'], 'score': [88, 92, 85]})
sorted_df = df.sort_values(by='score')

What is the order of names in sorted_df?
medium
A. ['Cara', 'Anna', 'Bob']
B. ['Bob', 'Anna', 'Cara']
C. ['Anna', 'Bob', 'Cara']
D. ['Cara', 'Bob', 'Anna']

Solution

  1. Step 1: Understand sorting by 'score'

    The scores are 88 (Anna), 92 (Bob), and 85 (Cara). Sorting ascending means smallest to largest.
  2. Step 2: Order names by ascending scores

    Sorted scores: 85 (Cara), 88 (Anna), 92 (Bob). So names order is ['Cara', 'Anna', 'Bob'].
  3. Final Answer:

    ['Cara', 'Anna', 'Bob'] -> Option A
  4. Quick Check:

    Ascending sort by score = ['Cara', 'Anna', 'Bob'] [OK]
Hint: Sort ascending means smallest value first [OK]
Common Mistakes:
  • Assuming descending order by default
  • Mixing up names and scores
  • Not using 'by' parameter
4. What is wrong with this code snippet?
df = pd.DataFrame({'A': [3, 1, 2]})
df.sort_values('A', ascending='False')
medium
A. The column name should be passed as a list.
B. The ascending parameter should be a boolean, not a string.
C. sort_values() does not accept the ascending parameter.
D. The DataFrame must be sorted inplace.

Solution

  1. Step 1: Check the ascending parameter type

    The ascending parameter expects a boolean (True or False), but here it is passed as a string 'False'.
  2. Step 2: Validate other options

    Passing column name as string is allowed. sort_values() accepts ascending. Sorting inplace is optional.
  3. Final Answer:

    The ascending parameter should be a boolean, not a string. -> Option B
  4. Quick Check:

    ascending must be True/False boolean [OK]
Hint: Use True/False, not 'True'/'False' for ascending [OK]
Common Mistakes:
  • Passing ascending as string
  • Thinking column name must be list
  • Forcing inplace sorting unnecessarily
5. You have a DataFrame df with columns 'product' and 'price'. You want to sort the products by price descending but keep the original DataFrame unchanged. Which code achieves this?
hard
A. df.sort_values(by='price', ascending=False, inplace=True)
B. df.sort_values('price', inplace=False)
C. df.sort_values(by='price', ascending=True)
D. sorted_df = df.sort_values(by='price', ascending=False)

Solution

  1. Step 1: Understand sorting without changing original

    To keep original DataFrame unchanged, do not use inplace=True. Instead, assign the sorted result to a new variable.
  2. Step 2: Check options for descending order

    sorted_df = df.sort_values(by='price', ascending=False) sorts by 'price' descending and assigns to sorted_df. df.sort_values(by='price', ascending=False, inplace=True) changes original due to inplace=True. df.sort_values(by='price', ascending=True) sorts ascending, not descending. df.sort_values('price', inplace=False) sorts ascending by default and does not assign result.
  3. Final Answer:

    sorted_df = df.sort_values(by='price', ascending=False) -> Option D
  4. Quick Check:

    Assign sorted result without inplace for original unchanged [OK]
Hint: Assign sorted DataFrame to new variable, avoid inplace=True [OK]
Common Mistakes:
  • Using inplace=True and losing original order
  • Sorting ascending instead of descending
  • Not assigning sorted DataFrame to a variable
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