Bird
Raised Fist0
Pandasdata~10 mins

sort_values() by multiple columns in Pandas - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - sort_values() by multiple columns
Start with DataFrame
↓
Choose columns to sort by
↓
Specify ascending or descending for each
↓
Call sort_values() with columns and order
↓
DataFrame sorted by first column
↓
Within ties, sorted by second column
↓
Return sorted DataFrame
We start with a DataFrame, pick columns to sort by, specify order for each, then call sort_values(). The DataFrame is sorted first by the first column, then by the second within ties.
Execution Sample
Pandas
import pandas as pd

df = pd.DataFrame({
  'A': [2, 1, 2, 1],
  'B': [1, 2, 2, 1]
})

sorted_df = df.sort_values(by=['A', 'B'], ascending=[True, False])
Sort the DataFrame first by column 'A' ascending, then by column 'B' descending within ties.
Execution Table
StepDataFrame StateActionResult
1[{'A':2,'B':1},{'A':1,'B':2},{'A':2,'B':2},{'A':1,'B':1}]Start with original DataFrameDataFrame with 4 rows as given
2Same as step 1Choose columns to sort by: ['A', 'B']Ready to sort by 'A' then 'B'
3Same as step 1Specify ascending=[True, False]Sort 'A' ascending, 'B' descending
4Same as step 1Call df.sort_values(by=['A','B'], ascending=[True,False])Sort rows by 'A' ascending and 'B' descending within ties
5[{'A':1,'B':2},{'A':1,'B':1},{'A':2,'B':2},{'A':2,'B':1}]Within ties of 'A', sort by 'B' descendingRows with A=1 sorted by B descending: 2 then 1 Rows with A=2 sorted by B descending: 2 then 1
6[{'A':1,'B':2},{'A':1,'B':1},{'A':2,'B':2},{'A':2,'B':1}]Return sorted DataFrameFinal sorted DataFrame
💡 Sorting complete: DataFrame sorted by 'A' ascending and 'B' descending within ties
Variable Tracker
VariableStartAfter Step 4After Step 5Final
df[{'A':2,'B':1},{'A':1,'B':2},{'A':2,'B':2},{'A':1,'B':1}][{'A':2,'B':1},{'A':1,'B':2},{'A':2,'B':2},{'A':1,'B':1}][{'A':2,'B':1},{'A':1,'B':2},{'A':2,'B':2},{'A':1,'B':1}][{'A':2,'B':1},{'A':1,'B':2},{'A':2,'B':2},{'A':1,'B':1}]
sorted_dfNone[{'A':1,'B':2},{'A':1,'B':1},{'A':2,'B':2},{'A':2,'B':1}][{'A':1,'B':2},{'A':1,'B':1},{'A':2,'B':2},{'A':2,'B':1}][{'A':1,'B':2},{'A':1,'B':1},{'A':2,'B':2},{'A':2,'B':1}]
Key Moments - 3 Insights
Why does the sorting first order by column 'A' before column 'B'?
Because in the execution_table step 4, sort_values() uses the 'by' list order. It sorts first by 'A', then breaks ties by sorting 'B' as shown in step 5.
How does specifying ascending=[True, False] affect the sorting?
As seen in step 3 and 5, 'A' is sorted ascending (small to large), while 'B' is sorted descending (large to small) within groups of equal 'A'.
Does the original DataFrame 'df' change after sorting?
No, as shown in variable_tracker, 'df' remains unchanged. The sorted DataFrame is returned as 'sorted_df'.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table step 5, what is the order of rows with 'A' equal to 2?
A[{'A':2,'B':2}, {'A':2,'B':1}]
B[{'A':2,'B':1}, {'A':2,'B':1}]
C[{'A':2,'B':1}, {'A':2,'B':2}]
D[{'A':2,'B':2}, {'A':2,'B':2}]
💡 Hint
Check the 'Within ties' sorting in step 5 of execution_table where 'B' is descending for 'A' = 2
At which step does the DataFrame get sorted by the first column 'A'?
AStep 2
BStep 4
CStep 5
DStep 6
💡 Hint
Look at execution_table step 4 where sort_values() is called and sorting by 'A' happens
If ascending=[False, True] was used instead, how would the order of rows with 'A' = 1 change?
ARows with 'A' = 1 would not change order
BRows with 'A' = 1 would be sorted by 'B' descending (2 then 1)
CRows with 'A' = 1 would be sorted by 'B' ascending (1 then 2)
DRows with 'A' = 1 would be sorted by 'A' descending
💡 Hint
Refer to how ascending list controls order per column in execution_table steps 3 and 5
Concept Snapshot
sort_values(by=[col1, col2], ascending=[bool1, bool2])
- Sorts DataFrame by multiple columns in order
- First sorts by col1, then col2 within ties
- ascending list controls order per column
- Returns new sorted DataFrame, original unchanged
Full Transcript
This visual execution shows how pandas sort_values() works when sorting by multiple columns. We start with a DataFrame with columns 'A' and 'B'. We choose to sort by 'A' first, then 'B'. We specify ascending order for 'A' as True and for 'B' as False. The sorting happens in steps: first by 'A' ascending, then within equal 'A' values by 'B' descending. The original DataFrame remains unchanged, and a new sorted DataFrame is returned. Key moments include understanding the order of sorting columns, how ascending list affects each column, and that the original data is not modified. The quizzes test understanding of sorting order and effects of changing ascending flags.

Practice

(1/5)
1.

What does the sort_values() function do when used on a pandas DataFrame?

easy
A. It sorts the DataFrame rows based on the values in one or more columns.
B. It filters rows that match a condition.
C. It changes the data types of columns.
D. It adds new columns to the DataFrame.

Solution

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

    This function organizes the rows of a DataFrame by sorting them according to the values in specified columns.
  2. Step 2: Compare with other DataFrame operations

    Filtering selects rows, changing data types modifies columns, and adding columns is unrelated to sorting.
  3. Final Answer:

    It sorts the DataFrame rows based on the values in one or more columns. -> Option A
  4. Quick Check:

    Sorting = Organizing rows by column values [OK]
Hint: Remember: sort_values() arranges rows by column values [OK]
Common Mistakes:
  • Confusing sorting with filtering rows
  • Thinking it changes data types
  • Assuming it adds or removes columns
2.

Which of the following is the correct syntax to sort a DataFrame df by columns 'A' ascending and 'B' descending?

df.sort_values(??? )
easy
A. columns=['A', 'B'], ascending=[False, True]
B. by=['A', 'B'], ascending=[True, False]
C. by=['A', 'B'], ascending=True
D. sort=['A', 'B'], order=[True, False]

Solution

  1. Step 1: Identify correct parameter names

    The method uses by to specify columns and ascending to specify order per column.
  2. Step 2: Match order for each column

    To sort 'A' ascending and 'B' descending, use ascending=[True, False].
  3. Final Answer:

    by=['A', 'B'], ascending=[True, False] -> Option B
  4. Quick Check:

    Correct parameters = by=['A', 'B'], ascending=[True, False] [OK]
Hint: Use by=columns and ascending=list of booleans [OK]
Common Mistakes:
  • Using wrong parameter names like columns or sort
  • Passing a single boolean for multiple columns
  • Mixing ascending order values
3.

Given the DataFrame:

import pandas as pd
df = pd.DataFrame({
  'Name': ['Anna', 'Bob', 'Anna', 'Bob'],
  'Score': [90, 92, 85, 80]
})

What is the result of df.sort_values(by=['Name', 'Score'], ascending=[True, False])?
medium
A. Rows sorted by Name ascending, then Score descending: Anna(90), Anna(85), Bob(92), Bob(80)
B. Rows sorted by Name descending, then Score ascending: Bob(80), Bob(92), Anna(85), Anna(90)
C. Rows sorted by Score ascending only: Bob(80), Anna(85), Anna(90), Bob(92)
D. Rows sorted by Score descending only: Bob(92), Anna(90), Anna(85), Bob(80)

Solution

  1. Step 1: Sort by 'Name' ascending

    Names order: Anna, Anna, Bob, Bob.
  2. Step 2: Within each Name, sort 'Score' descending

    For Anna: 90 then 85; for Bob: 92 then 80.
  3. Final Answer:

    Rows sorted by Name ascending, then Score descending: Anna(90), Anna(85), Bob(92), Bob(80) -> Option A
  4. Quick Check:

    Sort by Name ↑, Score ↓ = Rows sorted by Name ascending, then Score descending: Anna(90), Anna(85), Bob(92), Bob(80) [OK]
Hint: Sort first column ascending, second descending as list [OK]
Common Mistakes:
  • Mixing ascending and descending order
  • Sorting only by one column
  • Confusing order of sorting columns
4.

What is wrong with this code snippet?

df.sort_values(by=['A', 'B'], ascending=True)

Assuming df has columns 'A' and 'B'.

medium
A. The method sort_values does not accept the ascending parameter.
B. The by parameter should be a string, not a list.
C. The ascending parameter should be a list when sorting by multiple columns.
D. The code is correct and will run without errors.

Solution

  1. Step 1: Recall sort_values() parameters

    by accepts list of columns, ascending accepts bool (applies to all) or list of bools.
  2. Step 2: Validate the code

    The code uses ascending=True, which correctly sorts both columns ascending. No errors.
  3. Final Answer:

    The code is correct and will run without errors. -> Option D
  4. Quick Check:

    ascending=True valid for multi-column sort [OK]
Hint: ascending=True sorts all columns ascending; use list for mixed orders [OK]
Common Mistakes:
  • Believing ascending must be a list for multiple columns
  • Using string instead of list for 'by' parameter
  • Assuming sort_values lacks ascending parameter
5.

You have a DataFrame df with columns 'City', 'Temperature', and 'Humidity'. You want to sort the data so that cities are in alphabetical order, but within each city, rows with higher temperature come first, and if temperatures are equal, rows with lower humidity come first.

Which sort_values() call achieves this?

hard
A. df.sort_values(by=['City', 'Temperature', 'Humidity'], ascending=[False, True, False])
B. df.sort_values(by=['City', 'Humidity', 'Temperature'], ascending=[True, True, False])
C. df.sort_values(by=['City', 'Temperature', 'Humidity'], ascending=[True, False, True])
D. df.sort_values(by=['Temperature', 'City', 'Humidity'], ascending=[False, True, True])

Solution

  1. Step 1: Sort 'City' alphabetically ascending

    Set ascending=True for 'City' to get alphabetical order.
  2. Step 2: Sort 'Temperature' descending within each city

    Use ascending=False for 'Temperature' to have higher temperatures first.
  3. Step 3: Sort 'Humidity' ascending when temperatures tie

    Use ascending=True for 'Humidity' to get lower humidity first.
  4. Final Answer:

    df.sort_values(by=['City', 'Temperature', 'Humidity'], ascending=[True, False, True]) -> Option C
  5. Quick Check:

    City ↑, Temp ↓, Humidity ↑ = df.sort_values(by=['City', 'Temperature', 'Humidity'], ascending=[True, False, True]) [OK]
Hint: Match ascending list to desired order per column [OK]
Common Mistakes:
  • Mixing order of columns in 'by' list
  • Using wrong ascending booleans
  • Sorting humidity before temperature
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