Sorting by values in Pandas - Time & Space Complexity
When we sort data in pandas, we want to know how the time it takes changes as the data grows.
We ask: How does sorting time increase when we have more rows?
Analyze the time complexity of the following code snippet.
import pandas as pd
df = pd.DataFrame({
'A': [5, 2, 9, 1, 7],
'B': [3, 8, 4, 6, 0]
})
sorted_df = df.sort_values(by='A')
This code creates a small table and sorts it by the values in column 'A'.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Comparing and rearranging rows based on column 'A' 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 a bit 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 work grows faster than just the number of rows, but not as fast as the square of rows.
Time Complexity: O(n log n)
This means sorting takes more time as data grows, but it grows in a balanced way, not too slow or too fast.
[X] Wrong: "Sorting time grows exactly like the number of rows (linear)."
[OK] Correct: Sorting needs to compare many pairs, so it grows a bit faster than just the number of rows.
Understanding sorting time helps you explain how data operations scale, a useful skill when working with real datasets.
"What if we sorted by multiple columns instead of one? How would the time complexity change?"
Practice
sort_values() function do in pandas?Solution
Step 1: Understand the function purpose
Thesort_values()function is designed to reorder rows in a DataFrame based on the values in one or more columns.Step 2: Compare with other functions
Filtering, grouping, and merging are done by different pandas functions likefilter(),groupby(), andmerge().Final Answer:
It sorts the DataFrame by one or more columns. -> Option CQuick Check:
sort_values() = reorder rows by column values [OK]
- Confusing sorting with filtering
- Thinking it groups data
- Mixing it up with merging DataFrames
df by the column 'age' in descending order?Solution
Step 1: Identify correct parameter names
The correct parameter to specify the column isby='age', and to sort descending, useascending=False.Step 2: Check syntax correctness
df.sort_values(by='age', ascending=False) uses the correct function namesort_valuesand correct parameters. df.sort_values('age', ascending=True) sorts ascending, C uses a wrong functionsort, and B uses a wrong parameterdescending=True.Final Answer:
df.sort_values(by='age', ascending=False) -> Option AQuick Check:
sort_values(by=col, ascending=False) = descending sort [OK]
- Using ascending=True for descending sort
- Using wrong parameter names like descending=True
- Using non-existent sort() method
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?
Solution
Step 1: Understand the DataFrame content
The DataFrame has names and scores: Anna(88), Bob(92), Cara(85).Step 2: Apply sort_values on 'score'
Sorting by 'score' ascending orders rows as Cara(85), Anna(88), Bob(92).Final Answer:
Rows sorted by 'score' ascending: Cara, Anna, Bob -> Option DQuick Check:
sort_values('score') sorts ascending by default [OK]
- Assuming descending order by default
- Thinking original order is preserved
- Believing 'score' column does not exist
df.sort_values('age', ascending='False')Solution
Step 1: Check parameter types
Theascendingparameter expects a boolean valueTrueorFalse, not a string.Step 2: Validate other parts
The column name can be a string or list,sort_valuesis the correct function, and it acceptsascending.Final Answer:
The ascending parameter should be a boolean, not a string. -> Option BQuick Check:
ascending must be True/False boolean, not 'False' string [OK]
- Passing 'False' as a string instead of boolean
- Thinking column name must be a list
- Using wrong function name
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?Solution
Step 1: Understand multi-column sorting
To sort by multiple columns, pass a list tobyand a list of booleans toascendingmatching each column.Step 2: Match sorting order requirements
We want'city'ascending (True) and'temperature'descending (False), soascending=[True, False].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.Final Answer:
df.sort_values(by=['city', 'temperature'], ascending=[True, False]) -> Option AQuick Check:
Multi-column sort uses lists for by and ascending [OK]
- Using single boolean for multiple columns
- Mixing column order in by list
- Wrong ascending order list
Ready to prove it?
Pass the test and this pattern moves unknown
