When to use apply vs vectorized operations in Pandas - Performance Comparison
We want to understand how the time to run pandas code changes when using apply versus vectorized operations.
Which method grows faster as data size increases?
Analyze the time complexity of these two approaches.
import pandas as pd
n = 10 # Define n before using it
df = pd.DataFrame({'A': range(n)})
# Using apply
result_apply = df['A'].apply(lambda x: x * 2)
# Using vectorized operation
result_vec = df['A'] * 2
This code multiplies each value in column 'A' by 2 using two methods: apply with a lambda, and a vectorized operation.
Look at what repeats as the data grows.
- Primary operation: For
apply, the lambda function runs once per row. - How many times: Exactly
ntimes, wherenis the number of rows. - Vectorized operation: Uses optimized internal code that processes all rows together.
- How many times: Effectively once, working on the whole column at once.
As the number of rows grows, the time for apply grows linearly because it runs the function on each row.
Vectorized operations grow much slower because they use fast, low-level code that handles many rows at once.
| Input Size (n) | Approx. Operations for apply | Approx. Operations for vectorized |
|---|---|---|
| 10 | 10 function calls | 1 fast operation |
| 100 | 100 function calls | 1 fast operation |
| 1000 | 1000 function calls | 1 fast operation |
Pattern observation: apply time grows directly with data size; vectorized stays mostly constant and is much faster.
Time Complexity: O(n) for apply, O(1) for vectorized operations
This means apply takes longer as data grows, while vectorized operations handle large data efficiently.
[X] Wrong: "Using apply is just as fast as vectorized operations because both process all rows."
[OK] Correct: apply runs Python code for each row, which is slower, while vectorized operations use optimized compiled code that works on all data at once.
Knowing when to use vectorized operations versus apply shows you understand efficient data handling, a key skill in data science work.
What if the function inside apply was a built-in NumPy function instead of a lambda? How would that affect the time complexity?
Practice
apply in pandas?Solution
Step 1: Understand the purpose of
applyapplyis used to apply custom or complex functions to rows or columns in a DataFrame.Step 2: Compare with vectorized operations
Vectorized operations are for simple, fast math on entire columns, not custom row-wise functions.Final Answer:
When you need to run a custom function on each row or column. -> Option DQuick Check:
Custom function use = apply = A [OK]
- Confusing apply with vectorized operations for simple math
- Using apply for sorting or merging
- Thinking apply is always faster
apply on a DataFrame column df['col'] with a function func?Solution
Step 1: Recall the method call syntax
In pandas,applyis a method called on a Series or DataFrame with the function as argument.Step 2: Check each option
df['col'].apply(func) uses correct syntax:df['col'].apply(func). Others have syntax errors or wrong usage.Final Answer:
df['col'].apply(func) -> Option BQuick Check:
Method call with function argument = C [OK]
- Using square brackets instead of parentheses for apply
- Trying to assign function to apply attribute
- Calling apply as a standalone function
import pandas as pd
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})
What is the output of:df['C'] = df['A'] + df['B'] df['D'] = df['A'].apply(lambda x: x * 2) df[['C', 'D']]
Solution
Step 1: Calculate column C using vectorized addition
Column C = A + B = [1+4, 2+5, 3+6] = [5, 7, 9]Step 2: Calculate column D using apply with lambda
Column D = A * 2 = [1*2, 2*2, 3*2] = [2, 4, 6]Final Answer:
C D 0 5 2 1 7 4 2 9 6 -> Option AQuick Check:
Vectorized + apply results = B [OK]
- Mixing up which columns are added
- Forgetting to multiply by 2 in apply
- Confusing apply output with original values
'A' of DataFrame df. Which code has an error?Solution
Step 1: Analyze df['A'] = df.apply(lambda x: x['A'] * 2)'s use of apply
Usingdf.applywithout specifying axis defaults to axis=0 (columns), sox['A']fails because x is a column name string, not a row.Step 2: Compare with other options
Options B, C, and D correctly double values using apply on Series, vectorized, or map on Series.Final Answer:
df['A'] = df.apply(lambda x: x['A'] * 2) -> Option CQuick Check:
apply on DataFrame needs axis=1 for row-wise, else error = A [OK]
- Forgetting axis=1 in DataFrame apply
- Confusing apply on DataFrame vs Series
- Using map on DataFrame instead of Series
df with columns 'X' and 'Y'. You want to create a new column 'Z' that is 'X' squared if 'Y' is even, else 'X' cubed. Which is the best approach?Solution
Step 1: Understand the condition and operations
We wantZ = X^2ifYis even, elseZ = X^3.Step 2: Choose efficient method
Usingnp.wherewith vectorized power operations is fast and clear.applyworks but is slower. For loops are slow and verbose.maponXalone can't checkY.Final Answer:
Use vectorized operations with np.where and powers. -> Option AQuick Check:
Conditional vectorized ops > apply or loops = D [OK]
- Using apply when vectorized is faster
- Using loops instead of vectorized code
- Trying to map without condition on another column
Ready to prove it?
Pass the test and this pattern moves unknown
