Hint: Apply lambda to each value and calculate carefully [OK]
Common Mistakes:
Using normal division instead of floor division
Misreading floor division results
Confusing output format with DataFrame instead of Series
4. What is wrong with this code snippet?
df['new_col'] = df['value'].apply(x: x + 5)
How can it be fixed?
medium
A. Missing lambda keyword; fix: df['value'].apply(lambda x: x + 5)
B. apply() cannot add numbers; use map() instead
C. Should use square brackets around x; fix: apply([x]: x + 5)
D. Function must be defined outside apply; fix: def f(x): return x+5
Solution
Step 1: Identify syntax error in lambda function
The code uses x: x + 5 without the lambda keyword, which is required to define an anonymous function.
Step 2: Correct the syntax
Add lambda before the function: df['value'].apply(lambda x: x + 5).
Final Answer:
Missing lambda keyword; fix: df['value'].apply(lambda x: x + 5) -> Option A
Quick Check:
Lambda keyword needed for inline functions [OK]
Hint: Always use 'lambda' before inline functions in apply() [OK]
Common Mistakes:
Omitting the lambda keyword
Using incorrect brackets or syntax for lambda
Thinking apply() can't use inline functions
5. You have a DataFrame df with a column 'temperature' in Celsius. You want to create a new column 'temp_f' with Fahrenheit values using apply(). Which code correctly does this?
hard
A. df['temp_f'] = df.apply(lambda c: (c * 9/5) + 32)
B. df['temp_f'] = df['temperature'].apply(lambda c: (c * 9/5) + 32)
C. df['temp_f'] = df['temperature'].apply(lambda c: c + 32 * 9/5)
D. df['temp_f'] = df['temperature'].apply(lambda c: c * (9/5 + 32))
Solution
Step 1: Recall the formula for Celsius to Fahrenheit
The correct formula is Fahrenheit = (Celsius * 9/5) + 32.
Step 2: Check each option's lambda function
df['temp_f'] = df['temperature'].apply(lambda c: (c * 9/5) + 32) correctly applies the formula to each value in 'temperature'. df['temp_f'] = df.apply(lambda c: (c * 9/5) + 32) applies to whole DataFrame, C and D have incorrect formulas.