0
0
Pandasdata~20 mins

apply() with lambda functions in Pandas - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Apply Lambda Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of apply() with lambda on DataFrame column
What is the output of the following code snippet?
Pandas
import pandas as pd

df = pd.DataFrame({'A': [1, 2, 3, 4]})
result = df['A'].apply(lambda x: x**2 if x % 2 == 0 else x)
print(result.tolist())
A[1, 2, 3, 4]
B[2, 4, 6, 8]
C[1, 4, 9, 16]
D[1, 4, 3, 16]
Attempts:
2 left
💡 Hint
Remember the lambda squares only even numbers.
data_output
intermediate
2:00remaining
Resulting DataFrame after apply() with lambda on multiple columns
Given the DataFrame and the apply() operation below, what is the resulting DataFrame?
Pandas
import pandas as pd

df = pd.DataFrame({'X': [1, 2], 'Y': [3, 4]})
result = df.apply(lambda row: row['X'] + row['Y'], axis=1)
print(result)
A
X    4
Y    6
dtype: int64
B
0    4
1    6
dtype: int64
C
0    3
1    4
dtype: int64
D
0    1
1    2
dtype: int64
Attempts:
2 left
💡 Hint
axis=1 means apply function to each row.
🔧 Debug
advanced
2:00remaining
Identify the error in apply() with lambda on DataFrame
What error does the following code raise?
Pandas
import pandas as pd

df = pd.DataFrame({'A': [1, 2, 3]})
result = df.apply(lambda x: x + 1)
print(result)
ANo error, output is DataFrame with each element incremented by 1
BValueError: The truth value of a Series is ambiguous
CTypeError: unsupported operand type(s) for +: 'str' and 'int'
DAttributeError: 'int' object has no attribute 'apply'
Attempts:
2 left
💡 Hint
Check what apply does by default on DataFrame without axis specified.
🚀 Application
advanced
2:00remaining
Using apply() with lambda to categorize data
You have a DataFrame with a column 'score'. You want to create a new column 'grade' where scores >= 90 get 'A', scores >= 80 get 'B', else 'C'. Which code correctly does this?
Pandas
import pandas as pd

df = pd.DataFrame({'score': [95, 82, 74, 88]})
Adf['grade'] = df['score'].apply(lambda x: 'A' if x >= 90 else ('B' if x >= 80 else 'C'))
Bdf['grade'] = df['score'].apply(lambda x: 'A' if x > 90 else 'B' if x > 80 else 'C')
Cdf['grade'] = df['score'].map(lambda x: 'A' if x >= 90 else 'B' if x >= 80 else 'C')
Ddf['grade'] = df.apply(lambda x: 'A' if x['score'] >= 90 else 'B' if x['score'] >= 80 else 'C')
Attempts:
2 left
💡 Hint
Check the comparison operators and method used.
🧠 Conceptual
expert
2:00remaining
Understanding apply() behavior with lambda on DataFrame axis
Consider a DataFrame df with shape (3, 2). What is the shape of the output when running df.apply(lambda x: x.sum(), axis=1)?
A(3, 2)
B(2,)
C(3,)
D(1,)
Attempts:
2 left
💡 Hint
axis=1 applies function to each row, returning one value per row.