Bird
Raised Fist0
Data Analysis Pythondata~20 mins

apply() function for custom logic in Data Analysis Python - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Apply Function Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of apply() with a custom function on DataFrame column
What is the output of the following code snippet?
Data Analysis Python
import pandas as pd

df = pd.DataFrame({'score': [45, 82, 77, 90, 56]})

def grade(x):
    if x >= 80:
        return 'A'
    elif x >= 60:
        return 'B'
    else:
        return 'C'

df['grade'] = df['score'].apply(grade)
print(df['grade'].tolist())
A['B', 'A', 'B', 'A', 'C']
B['C', 'A', 'B', 'A', 'C']
C['C', 'A', 'A', 'A', 'C']
D['C', 'B', 'B', 'A', 'C']
Attempts:
2 left
💡 Hint
Check the conditions in the grade function carefully for each score.
❓ data_output
intermediate
2:00remaining
Resulting DataFrame after apply() with lambda function
What is the resulting DataFrame after applying the lambda function below?
Data Analysis Python
import pandas as pd

df = pd.DataFrame({'value': [10, 15, 20, 25]})
df['double'] = df['value'].apply(lambda x: x * 2)
print(df)
A
   value  double
0     10     100
1     15     225
2     20     400
3     25     625
B
   value  double
0     10      10
1     15      15
2     20      20
3     25      25
C
   value  double
0     10      20
1     15      30
2     20      40
3     25      50
D
   value  double
0     10      5
1     15      7
2     20     10
3     25     12
Attempts:
2 left
💡 Hint
The lambda function multiplies each value by 2.
🔧 Debug
advanced
2:00remaining
Identify the error in apply() usage with a custom function
What error does the following code raise?
Data Analysis Python
import pandas as pd

df = pd.DataFrame({'temp': [30, 22, 25]})

def convert(x):
    return x * 9/5 + 32

df['temp_f'] = df.apply(convert)
print(df)
ATypeError: unsupported operand type(s) for *: 'DataFrame' and 'float'
BValueError: The truth value of a DataFrame is ambiguous
CKeyError: 'temp_f'
DNo error, prints DataFrame with 'temp_f' column
Attempts:
2 left
💡 Hint
Check how apply() is used on the DataFrame without specifying axis.
🚀 Application
advanced
2:00remaining
Using apply() to create a new column based on multiple columns
Given the DataFrame below, which option correctly creates a new column 'status' that is 'Pass' if score >= 50 and attendance >= 75, else 'Fail'?
Data Analysis Python
import pandas as pd

df = pd.DataFrame({'score': [55, 48, 70, 40], 'attendance': [80, 70, 90, 85]})
Adf['status'] = df.apply(lambda row: 'Pass' if row.score >= 50 or row.attendance >= 75 else 'Fail', axis=0)
Bdf['status'] = df.apply(lambda x: 'Pass' if x['score'] >= 50 and x['attendance'] >= 75 else 'Fail')
Cdf['status'] = df['score'].apply(lambda x: 'Pass' if x >= 50 else 'Fail')
Ddf['status'] = df.apply(lambda row: 'Pass' if row['score'] >= 50 and row['attendance'] >= 75 else 'Fail', axis=1)
Attempts:
2 left
💡 Hint
Remember to use axis=1 to apply function row-wise.
🧠 Conceptual
expert
2:00remaining
Understanding apply() behavior with axis parameter
Which statement best describes the behavior of the apply() function when used on a DataFrame with axis=0 and axis=1?
Aaxis=0 applies the function to each column (Series), axis=1 applies the function to each row (Series)
Baxis=0 applies the function to each row (Series), axis=1 applies the function to each column (Series)
Caxis=0 applies the function element-wise, axis=1 applies the function to the entire DataFrame
Daxis=0 and axis=1 both apply the function to the entire DataFrame but in different orders
Attempts:
2 left
💡 Hint
Think about rows and columns as Series objects.

Practice

(1/5)
1. What does the apply() function do in a pandas DataFrame?
easy
A. It merges two DataFrames together.
B. It sorts the DataFrame by a column.
C. It filters rows based on a condition.
D. It applies a custom function to each row or column.

Solution

  1. Step 1: Understand the purpose of apply()

    The apply() function is used to run a custom function on each row or column of a DataFrame.
  2. Step 2: Compare with other DataFrame methods

    Sorting, filtering, and merging are different operations and not done by apply().
  3. Final Answer:

    It applies a custom function to each row or column. -> Option D
  4. Quick Check:

    apply() = custom function application [OK]
Hint: Remember: apply() runs your function on rows or columns [OK]
Common Mistakes:
  • Confusing apply() with sort or filter methods
  • Thinking apply() merges DataFrames
  • Assuming apply() only works on columns
2. Which of the following is the correct syntax to apply a function f row-wise on a DataFrame df?
easy
A. df.apply(f, axis=0)
B. df.apply(f)
C. df.apply(f, axis=1)
D. df.apply(f, axis=2)

Solution

  1. Step 1: Recall axis parameter meaning

    In pandas, axis=1 means apply function row-wise, while axis=0 means column-wise.
  2. Step 2: Identify correct axis for row-wise

    Since the question asks for row-wise application, axis=1 is correct.
  3. Final Answer:

    df.apply(f, axis=1) -> Option C
  4. Quick Check:

    Row-wise apply = axis=1 [OK]
Hint: Use axis=1 for rows, axis=0 for columns [OK]
Common Mistakes:
  • Using axis=0 for row-wise apply
  • Omitting axis parameter and expecting row-wise
  • Using invalid axis values like 2
3. Given the DataFrame:
import pandas as pd
df = pd.DataFrame({'A': [1, 2], 'B': [3, 4]})
What is the output of:
df['Sum'] = df.apply(lambda row: row['A'] + row['B'], axis=1)
print(df)
medium
A. A B Sum 0 1 3 3 1 2 4 4
B. A B Sum 0 1 3 4 1 2 4 6
C. A B Sum 0 1 3 1 1 2 4 2
D. Error: axis parameter missing

Solution

  1. Step 1: Understand the lambda function

    The lambda adds values from columns 'A' and 'B' for each row.
  2. Step 2: Apply row-wise addition

    Row 0: 1 + 3 = 4; Row 1: 2 + 4 = 6.
  3. Final Answer:

    A B Sum 0 1 3 4 1 2 4 6 -> Option B
  4. Quick Check:

    Sum column = A + B per row [OK]
Hint: Sum columns row-wise with apply and axis=1 [OK]
Common Mistakes:
  • Forgetting axis=1 causes wrong operation
  • Adding columns incorrectly (e.g., column-wise)
  • Expecting apply to work without lambda
4. What is wrong with this code snippet?
df = pd.DataFrame({'X': [10, 20], 'Y': [30, 40]})
df['Result'] = df.apply(lambda x: x['X'] * 2 if x['Y'] > 35 else x['X'], axis=0)
medium
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

  1. Step 1: Check axis parameter usage

    axis=0 applies function to each column (Series), not rows.
  2. Step 2: Understand lambda function context

    Lambda expects row with keys 'X' and 'Y', but column Series only has index labels, causing KeyError.
  3. Final Answer:

    Using axis=0 applies function column-wise, causing a KeyError. -> Option A
  4. 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)

Solution

  1. Step 1: Check axis parameter for row-wise logic

    axis=1 is needed to apply function on each row.
  2. Step 2: Verify conditional logic matches requirements

    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'.
  3. 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.
  4. 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
  5. 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 unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard