apply() function for custom logic in Data Analysis Python - Time & Space Complexity
We want to understand how the time it takes to run the apply() function changes as the data grows.
Specifically, how does applying a custom function to each row or column affect the total work done?
Analyze the time complexity of the following code snippet.
import pandas as pd
def custom_logic(row):
return row['A'] * 2 + row['B']
# Create a DataFrame with columns A and B
# Apply custom_logic to each row
result = df.apply(custom_logic, axis=1)
This code applies a custom function to each row of a DataFrame to create a new series.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The
apply()function runs the custom function once for each row. - How many times: It runs exactly as many times as there are rows in the DataFrame.
As the number of rows grows, the total work grows in the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 function calls |
| 100 | 100 function calls |
| 1000 | 1000 function calls |
Pattern observation: Doubling the rows doubles the number of function calls.
Time Complexity: O(n)
This means the time grows linearly with the number of rows in the DataFrame.
[X] Wrong: "The apply() function runs faster than looping manually because it's built-in."
[OK] Correct: apply() still calls the function once per row, so it does similar work as a manual loop. It's not magically faster in terms of time complexity.
Understanding how apply() scales helps you explain your data processing choices clearly and shows you know what happens behind the scenes.
"What if we changed the custom function to use vectorized operations instead of apply()? How would the time complexity change?"
Practice
apply() function do in a pandas DataFrame?Solution
Step 1: Understand the purpose of
Theapply()apply()function is used to run a custom function on each row or column of a DataFrame.Step 2: Compare with other DataFrame methods
Sorting, filtering, and merging are different operations and not done byapply().Final Answer:
It applies a custom function to each row or column. -> Option DQuick Check:
apply()= custom function application [OK]
- Confusing apply() with sort or filter methods
- Thinking apply() merges DataFrames
- Assuming apply() only works on columns
f row-wise on a DataFrame df?Solution
Step 1: Recall axis parameter meaning
In pandas,axis=1means apply function row-wise, whileaxis=0means column-wise.Step 2: Identify correct axis for row-wise
Since the question asks for row-wise application,axis=1is correct.Final Answer:
df.apply(f, axis=1) -> Option CQuick Check:
Row-wise apply = axis=1 [OK]
- Using axis=0 for row-wise apply
- Omitting axis parameter and expecting row-wise
- Using invalid axis values like 2
import pandas as pd
df = pd.DataFrame({'A': [1, 2], 'B': [3, 4]})
What is the output of:df['Sum'] = df.apply(lambda row: row['A'] + row['B'], axis=1) print(df)
Solution
Step 1: Understand the lambda function
The lambda adds values from columns 'A' and 'B' for each row.Step 2: Apply row-wise addition
Row 0: 1 + 3 = 4; Row 1: 2 + 4 = 6.Final Answer:
A B Sum 0 1 3 4 1 2 4 6 -> Option BQuick Check:
Sum column = A + B per row [OK]
- Forgetting axis=1 causes wrong operation
- Adding columns incorrectly (e.g., column-wise)
- Expecting apply to work without lambda
df = pd.DataFrame({'X': [10, 20], 'Y': [30, 40]})
df['Result'] = df.apply(lambda x: x['X'] * 2 if x['Y'] > 35 else x['X'], axis=0)Solution
Step 1: Check axis parameter usage
axis=0 applies function to each column (Series), not rows.Step 2: Understand lambda function context
Lambda expects row with keys 'X' and 'Y', but column Series only has index labels, causing KeyError.Final Answer:
Using axis=0 applies function column-wise, causing a KeyError. -> Option AQuick Check:
axis=0 = columns, lambda expects rows [OK]
- Confusing axis=0 and axis=1
- Expecting row keys when applying column-wise
- Ignoring error messages about missing keys
df with columns "score" and "passed" (boolean). You want to create a new column "grade" where:- If
passed is True and score >= 90, grade is 'A'- If
passed is True and score >= 75 but < 90, grade is 'B'- Otherwise, grade is 'F'
Which
apply() function correctly implements this logic?Solution
Step 1: Check axis parameter for row-wise logic
axis=1 is needed to apply function on each row.Step 2: Verify conditional logic matches requirements
df['grade'] = df.apply(lambda r: 'A' if r['passed'] and r['score'] >= 90 else ('B' if r['passed'] and r['score'] >= 75 else 'F'), axis=1) correctly checks if passed is True and score thresholds for 'A' and 'B', else 'F'.Step 3: Identify errors in other options
df['grade'] = df.apply(lambda r: 'A' if r['score'] >= 90 else 'B' if r['score'] >= 75 else 'F', axis=0) uses axis=0 (wrong axis). df['grade'] = df.apply(lambda r: 'A' if r['passed'] or r['score'] >= 90 else 'F', axis=1) uses 'or' instead of 'and'. df['grade'] = df.apply(lambda r: 'A' if r['passed'] and r['score'] > 90 else 'B', axis=1) misses 'F' grade and uses wrong comparison for 90.Final Answer:
df['grade'] = df.apply(lambda r: 'A' if r['passed'] and r['score'] >= 90 else ('B' if r['passed'] and r['score'] >= 75 else 'F'), axis=1) -> Option AQuick Check:
Correct logic and axis=1 for row-wise apply [OK]
- Using axis=0 instead of axis=1
- Using 'or' instead of 'and' in conditions
- Missing else condition for failing grade
Ready to prove it?
Pass the test and this pattern moves unknown
