Selecting rows by condition in Pandas - Time & Space Complexity
We want to know how the time to select rows by a condition changes as the data grows.
How does the work increase when the table gets bigger?
Analyze the time complexity of the following code snippet.
import pandas as pd
df = pd.DataFrame({'age': [23, 45, 12, 36, 27] * 200})
selected = df[df['age'] > 30]
This code creates a table with ages and selects rows where age is greater than 30.
- Primary operation: Checking each row's 'age' value against 30.
- How many times: Once for every row in the table.
As the number of rows grows, the time to check each row grows at the same rate.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 checks |
| 100 | 100 checks |
| 1000 | 1000 checks |
Pattern observation: The work grows directly with the number of rows.
Time Complexity: O(n)
This means the time to select rows grows in a straight line as the table gets bigger.
[X] Wrong: "Selecting rows by condition is instant no matter the size."
[OK] Correct: The code must check each row to see if it meets the condition, so more rows mean more work.
Understanding how filtering data scales helps you write efficient code and explain your choices clearly.
"What if we select rows using multiple conditions combined with AND? How would the time complexity change?"
Practice
df[df['age'] > 30] do in pandas?Solution
Step 1: Understand the condition inside the brackets
The conditiondf['age'] > 30creates a True/False mask for each row based on the 'age' value.Step 2: Apply the condition to select rows
Usingdf[condition]returns only rows where the condition is True, i.e., 'age' > 30.Final Answer:
Selects rows where the 'age' column is greater than 30 -> Option CQuick Check:
Condition filters rows [OK]
- Thinking it selects columns instead of rows
- Confusing filtering with sorting
- Using parentheses incorrectly around conditions
Solution
Step 1: Identify correct equality operator in pandas
In pandas, to compare values, use double equals==, not single=or triple===.Step 2: Check correct column access syntax
Usingdf['score']is correct and safe for all column names.Final Answer:
df[df['score'] == 100] -> Option DQuick Check:
Use == for comparison and brackets for column [OK]
- Using single = instead of == for comparison
- Using triple === which is invalid in Python
- Accessing columns without quotes when name has special chars
import pandas as pd
data = {'name': ['Ann', 'Bob', 'Cara', 'Dan'], 'age': [25, 35, 30, 40]}
df = pd.DataFrame(data)
What is the output of df[df['age'] >= 30]?Solution
Step 1: Evaluate the condition df['age'] >= 30
This condition is True for ages 35 (Bob), 30 (Cara), and 40 (Dan).Step 2: Select rows where condition is True
Rows with names Bob, Cara, and Dan are returned.Final Answer:
Rows with names Bob, Cara, and Dan -> Option AQuick Check:
age >= 30 selects Bob, Cara, Dan [OK]
- Including Ann who is 25 (less than 30)
- Confusing >= with >
- Misreading the DataFrame data
df[df['score'] > 50 && df['age'] < 30]
Solution
Step 1: Check operator for combining conditions in pandas
In pandas, use single ampersand&for 'and', not double ampersand&&.Step 2: Confirm correct syntax
Correct syntax isdf[(df['score'] > 50) & (df['age'] < 30)]with parentheses and single &.Final Answer:
Using && instead of & for combining conditions -> Option AQuick Check:
Use & not && for and in pandas [OK]
- Using && which causes syntax error
- Not adding parentheses around each condition
- Using | instead of & for and
df with columns 'city', 'temperature', and 'humidity'. How do you select rows where the city is 'Paris' and temperature is above 20 or humidity is below 30?Solution
Step 1: Understand operator precedence and grouping
Logical AND (&) has higher precedence than OR (|), so parentheses are needed to group OR conditions correctly.Step 2: Write correct condition with parentheses
We want city == 'Paris' AND (temperature > 20 OR humidity < 30), so use:df[(df['city'] == 'Paris') & ((df['temperature'] > 20) | (df['humidity'] < 30))]Final Answer:
df[(df['city'] == 'Paris') & ((df['temperature'] > 20) | (df['humidity'] < 30))] -> Option BQuick Check:
Group OR inside AND with parentheses [OK]
- Missing parentheses causing wrong logic
- Using Python 'and'/'or' instead of & and |
- Not using parentheses around each condition
Ready to prove it?
Pass the test and this pattern moves unknown
