sort_values() by multiple columns in Pandas - Time & Space Complexity
We want to understand how the time needed to sort data changes as the data grows.
Specifically, how sorting by multiple columns affects the work done.
Analyze the time complexity of the following code snippet.
import pandas as pd
df = pd.DataFrame({
'A': [3, 1, 2, 1],
'B': [4, 3, 2, 1],
'C': [10, 20, 30, 40]
})
sorted_df = df.sort_values(by=['A', 'B'])
This code sorts the DataFrame first by column 'A', then by column 'B' to break ties.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Comparing and rearranging rows based on column values.
- How many times: The sorting algorithm compares elements multiple times, roughly proportional to the number of rows times the logarithm of the number of rows.
As the number of rows grows, the sorting work grows faster than just the number of rows.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 30 to 40 comparisons |
| 100 | About 600 to 700 comparisons |
| 1000 | About 10,000 to 12,000 comparisons |
Pattern observation: The number of operations grows a bit faster than the number of rows, roughly like n times log n.
Time Complexity: O(n log n)
This means sorting takes more time as data grows, but not as fast as checking every pair; it grows in a balanced way.
[X] Wrong: "Sorting by multiple columns multiplies the time by the number of columns."
[OK] Correct: Sorting still mainly depends on the number of rows; adding columns to sort by only changes how comparisons are done, not the overall growth rate.
Understanding how sorting scales helps you explain data processing steps clearly and shows you know how data size affects performance.
"What if we sorted by only one column instead of multiple? How would the time complexity change?"
Practice
What does the sort_values() function do when used on a pandas DataFrame?
Solution
Step 1: Understand the purpose of
This function organizes the rows of a DataFrame by sorting them according to the values in specified columns.sort_values()Step 2: Compare with other DataFrame operations
Filtering selects rows, changing data types modifies columns, and adding columns is unrelated to sorting.Final Answer:
It sorts the DataFrame rows based on the values in one or more columns. -> Option AQuick Check:
Sorting = Organizing rows by column values [OK]
- Confusing sorting with filtering rows
- Thinking it changes data types
- Assuming it adds or removes columns
Which of the following is the correct syntax to sort a DataFrame df by columns 'A' ascending and 'B' descending?
df.sort_values(??? )
Solution
Step 1: Identify correct parameter names
The method usesbyto specify columns andascendingto specify order per column.Step 2: Match order for each column
To sort 'A' ascending and 'B' descending, useascending=[True, False].Final Answer:
by=['A', 'B'], ascending=[True, False] -> Option BQuick Check:
Correct parameters = by=['A', 'B'], ascending=[True, False] [OK]
- Using wrong parameter names like columns or sort
- Passing a single boolean for multiple columns
- Mixing ascending order values
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])?Solution
Step 1: Sort by 'Name' ascending
Names order: Anna, Anna, Bob, Bob.Step 2: Within each Name, sort 'Score' descending
For Anna: 90 then 85; for Bob: 92 then 80.Final Answer:
Rows sorted by Name ascending, then Score descending: Anna(90), Anna(85), Bob(92), Bob(80) -> Option AQuick Check:
Sort by Name ↑, Score ↓ = Rows sorted by Name ascending, then Score descending: Anna(90), Anna(85), Bob(92), Bob(80) [OK]
- Mixing ascending and descending order
- Sorting only by one column
- Confusing order of sorting columns
What is wrong with this code snippet?
df.sort_values(by=['A', 'B'], ascending=True)
Assuming df has columns 'A' and 'B'.
Solution
Step 1: Recall
sort_values()parametersbyaccepts list of columns,ascendingaccepts bool (applies to all) or list of bools.Step 2: Validate the code
The code usesascending=True, which correctly sorts both columns ascending. No errors.Final Answer:
The code is correct and will run without errors. -> Option DQuick Check:
ascending=True valid for multi-column sort [OK]
- Believing ascending must be a list for multiple columns
- Using string instead of list for 'by' parameter
- Assuming sort_values lacks ascending parameter
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?
Solution
Step 1: Sort 'City' alphabetically ascending
Set ascending=True for 'City' to get alphabetical order.Step 2: Sort 'Temperature' descending within each city
Use ascending=False for 'Temperature' to have higher temperatures first.Step 3: Sort 'Humidity' ascending when temperatures tie
Use ascending=True for 'Humidity' to get lower humidity first.Final Answer:
df.sort_values(by=['City', 'Temperature', 'Humidity'], ascending=[True, False, True]) -> Option CQuick Check:
City ↑, Temp ↓, Humidity ↑ = df.sort_values(by=['City', 'Temperature', 'Humidity'], ascending=[True, False, True]) [OK]
- Mixing order of columns in 'by' list
- Using wrong ascending booleans
- Sorting humidity before temperature
Ready to prove it?
Pass the test and this pattern moves unknown
