Challenge - 5 Problems
Custom Functions Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of applying a custom function with pandas apply
What is the output of the following code that uses a custom function with pandas apply on a DataFrame column?
Pandas
import pandas as pd def add_five(x): return x + 5 df = pd.DataFrame({'A': [1, 2, 3]}) df['B'] = df['A'].apply(add_five) print(df)
Attempts:
2 left
💡 Hint
Remember that apply passes each element of the column to the function.
✗ Incorrect
The custom function add_five adds 5 to each element in column 'A'. Applying it creates column 'B' with values 6, 7, 8.
❓ data_output
intermediate2:00remaining
Result of using a lambda function with apply on a DataFrame
What is the resulting DataFrame after applying this lambda function to column 'score'?
Pandas
import pandas as pd df = pd.DataFrame({'score': [50, 80, 90]}) df['grade'] = df['score'].apply(lambda x: 'Pass' if x >= 60 else 'Fail') print(df)
Attempts:
2 left
💡 Hint
Check the condition inside the lambda function carefully.
✗ Incorrect
The lambda function assigns 'Pass' if score is 60 or more, otherwise 'Fail'. So 50 is 'Fail', 80 and 90 are 'Pass'.
🔧 Debug
advanced2:00remaining
Identify the error in this custom function used with apply
What error will this code raise when applying the custom function to the DataFrame column?
Pandas
import pandas as pd def divide_by_zero(x): return x / 0 df = pd.DataFrame({'num': [1, 2, 3]}) df['result'] = df['num'].apply(divide_by_zero)
Attempts:
2 left
💡 Hint
Think about what happens when dividing by zero in Python.
✗ Incorrect
Dividing any number by zero raises a ZeroDivisionError in Python, so the apply call will fail with this error.
🚀 Application
advanced2:30remaining
Using a custom function to categorize data in pandas
You want to categorize ages into 'Child', 'Adult', and 'Senior' using a custom function with apply. Which code correctly creates a new column 'category' with these labels?
Pandas
import pandas as pd df = pd.DataFrame({'age': [5, 25, 70]})
Attempts:
2 left
💡 Hint
Check the boundary conditions carefully for age groups.
✗ Incorrect
Option D correctly categorizes ages: under 18 is 'Child', 18 to 65 inclusive is 'Adult', above 65 is 'Senior'.
🧠 Conceptual
expert2:00remaining
Why use custom functions with pandas apply instead of vectorized operations?
Which statement best explains why custom functions are important when working with pandas apply?
Attempts:
2 left
💡 Hint
Think about the flexibility custom functions provide.
✗ Incorrect
Custom functions let you apply any logic you want, even if pandas does not have a built-in vectorized method for it.