We use apply and vectorized operations to change or analyze data in tables. Vectorized operations are faster and simpler, but apply is useful when we need custom or complex changes.
When to use apply vs vectorized operations in Pandas
df['new_column'] = df['existing_column'].apply(function) df['new_column'] = df['existing_column'] + 10 # vectorized example
apply runs a function on each element or row/column.
Vectorized operations use built-in fast math on whole columns at once.
df['double'] = df['value'] * 2
df['double'] = df['value'].apply(lambda x: x * 2)
df['category'] = df.apply(lambda row: 'high' if row['value'] > 10 else 'low', axis=1)
This code shows adding 10 to each number using vectorized operation, which is fast and simple.
Then it uses apply with a function to label values as 'high' or 'low'.
import pandas as pd data = {'value': [5, 15, 8, 20]} df = pd.DataFrame(data) # Vectorized operation: add 10 to each value added = df['value'] + 10 print('Vectorized result:') print(added) # Apply with a custom function: label high or low labels = df['value'].apply(lambda x: 'high' if x > 10 else 'low') print('\nApply result:') print(labels)
Vectorized operations are usually faster and preferred for simple math or built-in functions.
Use apply when you need custom logic that vectorized operations cannot do.
apply with axis=1 works row-wise, axis=0 works column-wise.
Use vectorized operations for simple, fast math on columns.
Use apply for custom or complex functions on rows or columns.
apply is slower but more flexible than vectorized operations.
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
