A. Using axis=0 applies function column-wise, causing a KeyError.
B. Lambda function syntax is incorrect.
C. DataFrame is missing required columns.
D. No error; code runs correctly.
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 A
Quick Check:
axis=0 = columns, lambda expects rows [OK]
Hint: Use axis=1 for row-wise logic to avoid key errors [OK]
Common Mistakes:
Confusing axis=0 and axis=1
Expecting row keys when applying column-wise
Ignoring error messages about missing keys
5. You have a DataFrame 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?
hard
A. 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)
B. df['grade'] = df.apply(lambda r: 'A' if r['score'] >= 90 else 'B' if r['score'] >= 75 else 'F', axis=0)
C. df['grade'] = df.apply(lambda r: 'A' if r['passed'] or r['score'] >= 90 else 'F', axis=1)
D. df['grade'] = df.apply(lambda r: 'A' if r['passed'] and r['score'] > 90 else 'B', axis=1)
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 A
Quick Check:
Correct logic and axis=1 for row-wise apply [OK]
Hint: Use axis=1 and nested if-else for multi-condition grading [OK]
Common Mistakes:
Using axis=0 instead of axis=1
Using 'or' instead of 'and' in conditions
Missing else condition for failing grade
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.