Bird
Raised Fist0
Pandasdata~20 mins

Sorting by values in Pandas - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Sorting Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Sorting a DataFrame by a single column
What is the output of this code snippet that sorts a DataFrame by column 'B' in ascending order?
Pandas
import pandas as pd

df = pd.DataFrame({'A': [3, 1, 2], 'B': [9, 5, 7]})
sorted_df = df.sort_values(by='B')
print(sorted_df)
A
   A  B
2  2  7
1  1  5
0  3  9
B
   A  B
0  3  9
2  2  7
1  1  5
C
   A  B
1  1  5
0  3  9
2  2  7
D
   A  B
1  1  5
2  2  7
0  3  9
Attempts:
2 left
💡 Hint
Remember that sort_values(by='B') sorts the DataFrame by column 'B' in ascending order by default.
❓ data_output
intermediate
2:00remaining
Sorting by multiple columns with different orders
Given the DataFrame below, what is the output after sorting by column 'A' ascending and then by column 'B' descending?
Pandas
import pandas as pd

df = pd.DataFrame({'A': [1, 2, 1, 2], 'B': [3, 4, 2, 1]})
sorted_df = df.sort_values(by=['A', 'B'], ascending=[True, False])
print(sorted_df)
A
   A  B
2  1  2
0  1  3
3  2  1
1  2  4
B
   A  B
0  1  3
2  1  2
1  2  4
3  2  1
C
   A  B
0  1  3
2  1  2
3  2  1
1  2  4
D
   A  B
2  1  2
0  1  3
1  2  4
3  2  1
Attempts:
2 left
💡 Hint
Sorting by 'A' ascending means rows with A=1 come before A=2. For ties in 'A', sort 'B' descending.
🔧 Debug
advanced
2:00remaining
Identify the error in sorting by values
What error does this code raise when trying to sort a DataFrame by a non-existent column 'C'?
Pandas
import pandas as pd

df = pd.DataFrame({'A': [1, 2], 'B': [3, 4]})
sorted_df = df.sort_values(by='C')
AKeyError: 'C'
BValueError: Cannot sort by non-existent column
CTypeError: 'C' is not a valid column
DAttributeError: 'DataFrame' object has no attribute 'C'
Attempts:
2 left
💡 Hint
Check what happens when you try to access a column that does not exist in a DataFrame.
🚀 Application
advanced
2:00remaining
Sorting a DataFrame with missing values
You have this DataFrame with missing values in column 'B'. What is the output after sorting by 'B' with na_position='first'?
Pandas
import pandas as pd
import numpy as np

df = pd.DataFrame({'A': [1, 2, 3], 'B': [np.nan, 2, 1]})
sorted_df = df.sort_values(by='B', na_position='first')
print(sorted_df)
A
     A    B
1  2  2.0
2  3  1.0
0  1  NaN
B
     A    B
2  3  1.0
1  2  2.0
0  1  NaN
C
     A    B
0  1  NaN
2  3  1.0
1  2  2.0
D
     A    B
0  1  NaN
1  2  2.0
2  3  1.0
Attempts:
2 left
💡 Hint
na_position='first' places missing values at the top when sorting ascending.
🧠 Conceptual
expert
2:00remaining
Effect of inplace parameter in sort_values
What is the effect of setting inplace=True in the sort_values method on a DataFrame?
AThe DataFrame is sorted in place and the method returns None.
BThe DataFrame is sorted and a new sorted DataFrame is returned, original unchanged.
CThe DataFrame is sorted in place and the method returns the sorted DataFrame.
DThe DataFrame is not sorted but a sorted copy is returned.
Attempts:
2 left
💡 Hint
Check the pandas documentation for the behavior of inplace=True in sort_values.

Practice

(1/5)
1. What does the sort_values() function do in pandas?
easy
A. It filters rows based on a condition.
B. It groups data by a column.
C. It sorts the DataFrame by one or more columns.
D. It merges two DataFrames.

Solution

  1. Step 1: Understand the function purpose

    The sort_values() function is designed to reorder rows in a DataFrame based on the values in one or more columns.
  2. Step 2: Compare with other functions

    Filtering, grouping, and merging are done by different pandas functions like filter(), groupby(), and merge().
  3. Final Answer:

    It sorts the DataFrame by one or more columns. -> Option C
  4. Quick Check:

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

Solution

  1. Step 1: Identify correct parameter names

    The correct parameter to specify the column is by='age', and to sort descending, use ascending=False.
  2. Step 2: Check syntax correctness

    df.sort_values(by='age', ascending=False) uses the correct function name sort_values and correct parameters. df.sort_values('age', ascending=True) sorts ascending, C uses a wrong function sort, and B uses a wrong parameter descending=True.
  3. Final Answer:

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

    sort_values(by=col, ascending=False) = descending sort [OK]
Hint: Use ascending=False for descending order in sort_values [OK]
Common Mistakes:
  • Using ascending=True for descending sort
  • Using wrong parameter names like descending=True
  • Using non-existent sort() method
3. Given the DataFrame:
import pandas as pd
df = pd.DataFrame({'name': ['Anna', 'Bob', 'Cara'], 'score': [88, 92, 85]})
print(df.sort_values('score'))

What will be the output?
medium
A. Original DataFrame without sorting
B. Rows sorted by 'score' descending: Bob, Anna, Cara
C. Error because 'score' is not a column
D. Rows sorted by 'score' ascending: Cara, Anna, Bob

Solution

  1. Step 1: Understand the DataFrame content

    The DataFrame has names and scores: Anna(88), Bob(92), Cara(85).
  2. Step 2: Apply sort_values on 'score'

    Sorting by 'score' ascending orders rows as Cara(85), Anna(88), Bob(92).
  3. Final Answer:

    Rows sorted by 'score' ascending: Cara, Anna, Bob -> Option D
  4. Quick Check:

    sort_values('score') sorts ascending by default [OK]
Hint: Default sort_values sorts ascending unless told otherwise [OK]
Common Mistakes:
  • Assuming descending order by default
  • Thinking original order is preserved
  • Believing 'score' column does not exist
4. What is wrong with this code snippet?
df.sort_values('age', ascending='False')
medium
A. The column name 'age' must 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 function should be sort_by_values, not sort_values.

Solution

  1. Step 1: Check parameter types

    The ascending parameter expects a boolean value True or False, not a string.
  2. Step 2: Validate other parts

    The column name can be a string or list, sort_values is the correct function, and it accepts ascending.
  3. Final Answer:

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

    ascending must be True/False boolean, not 'False' string [OK]
Hint: Use True/False without quotes for ascending parameter [OK]
Common Mistakes:
  • Passing 'False' as a string instead of boolean
  • Thinking column name must be a list
  • Using wrong function name
5. You have a DataFrame df with columns 'city' and 'temperature'. You want to sort it first by 'city' alphabetically ascending, then by 'temperature' descending within each city. Which code correctly does this?
hard
A. df.sort_values(by=['city', 'temperature'], ascending=[True, False])
B. df.sort_values(by=['temperature', 'city'], ascending=[False, True])
C. df.sort_values(by=['city', 'temperature'], ascending=False)
D. df.sort_values(['city', 'temperature'], ascending=[False, True])

Solution

  1. Step 1: Understand multi-column sorting

    To sort by multiple columns, pass a list to by and a list of booleans to ascending matching each column.
  2. Step 2: Match sorting order requirements

    We want 'city' ascending (True) and 'temperature' descending (False), so ascending=[True, False].
  3. Step 3: Check options

    df.sort_values(by=['city', 'temperature'], ascending=[True, False]) matches the correct order and ascending list. df.sort_values(by=['temperature', 'city'], ascending=[False, True]) reverses columns. df.sort_values(by=['city', 'temperature'], ascending=False) uses a single boolean for two columns. df.sort_values(['city', 'temperature'], ascending=[False, True]) has wrong ascending order.
  4. Final Answer:

    df.sort_values(by=['city', 'temperature'], ascending=[True, False]) -> Option A
  5. Quick Check:

    Multi-column sort uses lists for by and ascending [OK]
Hint: Use lists for by and ascending to sort multiple columns [OK]
Common Mistakes:
  • Using single boolean for multiple columns
  • Mixing column order in by list
  • Wrong ascending order list
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