Bird
Raised Fist0
Pandasdata~10 mins

apply() on rows (axis=1) in Pandas - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - apply() on rows (axis=1)
Start with DataFrame
↓
Define function to apply
↓
Call apply() with axis=1
↓
Function runs on each row
↓
Collect results into Series or DataFrame
↓
Use or assign results
This flow shows how apply() runs a function on each row of a DataFrame when axis=1 is set.
Execution Sample
Pandas
import pandas as pd

df = pd.DataFrame({
    'A': [1, 2, 3],
    'B': [4, 5, 6]
})

result = df.apply(lambda row: row['A'] + row['B'], axis=1)
This code adds values in columns A and B for each row using apply() with axis=1.
Execution Table
StepRow IndexRow DataFunction AppliedResult
10{'A': 1, 'B': 4}1 + 45
21{'A': 2, 'B': 5}2 + 57
32{'A': 3, 'B': 6}3 + 69
4--All rows processedSeries([5, 7, 9])
💡 All rows processed, apply() returns a Series with results.
Variable Tracker
VariableStartAfter 1After 2After 3Final
rowNoneA 1 B 4 Name: 0, dtype: int64A 2 B 5 Name: 1, dtype: int64A 3 B 6 Name: 2, dtype: int64None
resultEmpty579Series([5, 7, 9])
Key Moments - 3 Insights
Why do we use axis=1 in apply()?
axis=1 tells apply() to run the function on each row, not on each column. See execution_table steps 1-3 where each row is processed.
What type of object is passed to the function inside apply()?
Each row is passed as a Series object representing that row's data, as shown in execution_table column 'Row Data'.
What does apply() return when used with axis=1?
It returns a Series with the function results for each row, as shown in execution_table step 4.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the result of the function applied on row index 1?
A5
B9
C7
D6
💡 Hint
Check the 'Result' column for row index 1 in execution_table step 2.
At which step does apply() finish processing all rows?
AStep 3
BStep 4
CStep 2
DStep 1
💡 Hint
Look at the exit_note and the last row in execution_table.
If axis=0 was used instead of axis=1, how would the function be applied?
AOn each column
BOn the entire DataFrame at once
COn each row
DIt would cause an error
💡 Hint
axis=0 means apply function on columns, not rows.
Concept Snapshot
apply() with axis=1 runs a function on each row of a DataFrame.
The function receives a row as a Series.
Results are collected into a Series or DataFrame.
Use axis=1 to operate row-wise, axis=0 for column-wise.
Common for row-based calculations or transformations.
Full Transcript
We start with a DataFrame containing columns A and B. We define a function that adds the values in columns A and B for each row. Using apply() with axis=1, the function runs on each row one by one. For row 0, values 1 and 4 are added to get 5. For row 1, 2 and 5 sum to 7. For row 2, 3 and 6 sum to 9. The results are collected into a Series with values 5, 7, and 9. The key is axis=1 tells apply() to work row-wise. Each row is passed as a Series to the function. The final output is a Series with the function results for each row.

Practice

(1/5)
1.

What does apply() with axis=1 do in a pandas DataFrame?

easy
A. It applies a function to each column of the DataFrame.
B. It applies a function to each row of the DataFrame.
C. It applies a function to the entire DataFrame at once.
D. It applies a function only to the first row.

Solution

  1. Step 1: Understand the axis parameter

    In pandas, axis=1 means the function is applied across columns for each row.
  2. Step 2: Apply function on rows

    Using apply() with axis=1 runs the function on each row individually.
  3. Final Answer:

    It applies a function to each row of the DataFrame. -> Option B
  4. Quick Check:

    apply(axis=1) = row-wise function [OK]
Hint: Remember axis=1 means row-wise operation [OK]
Common Mistakes:
  • Confusing axis=1 with column-wise operation
  • Thinking apply(axis=1) applies to the whole DataFrame at once
  • Assuming it only applies to the first row
2.

Which of the following is the correct syntax to apply a function f to each row of a DataFrame df?

def f(row):
    return row['A'] + row['B']
easy
A. df.apply(f, axis=1)
B. df.apply(f, axis=0)
C. df.apply(f)
D. df.apply(f, axis='rows')

Solution

  1. Step 1: Identify axis for row-wise apply

    Row-wise apply requires axis=1.
  2. Step 2: Check syntax correctness

    df.apply(f, axis=1) uses axis=1, which is correct. The other options use incorrect axis parameters.
  3. Final Answer:

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

    Use axis=1 for rows [OK]
Hint: Use axis=1 to apply function row-wise [OK]
Common Mistakes:
  • Using axis=0 applies function column-wise
  • Omitting axis defaults to axis=0
  • Using incorrect axis string values
3.

What is the output of the following code?

import pandas as pd
df = pd.DataFrame({'A': [1, 2], 'B': [3, 4]})
def sum_row(row):
    return row['A'] + row['B']
df['Sum'] = df.apply(sum_row, axis=1)
print(df)
medium
A. Error: KeyError
B. A B Sum 0 1 3 3 1 2 4 4
C. A B Sum 0 1 3 1 1 2 4 2
D. A B Sum 0 1 3 4 1 2 4 6

Solution

  1. Step 1: Understand the function sum_row

    The function adds values from columns 'A' and 'B' for each row.
  2. Step 2: Apply function row-wise and add new column

    Applying with axis=1 sums each row's 'A' and 'B'. For 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 D
  4. Quick Check:

    Row sums = 4, 6 [OK]
Hint: Sum columns per row with apply(axis=1) [OK]
Common Mistakes:
  • Using axis=0 sums columns, not rows
  • Forgetting to assign result back to DataFrame
  • Mixing up row and column indices
4.

Identify the error in the following code snippet:

import pandas as pd
df = pd.DataFrame({'X': [10, 20], 'Y': [30, 40]})
def multiply(row):
    return row['x'] * row['Y']
df['Product'] = df.apply(multiply, axis=1)
print(df)
medium
A. KeyError because 'x' column does not exist (case sensitive).
B. TypeError due to wrong axis parameter.
C. No error, output is correct.
D. SyntaxError in function definition.

Solution

  1. Step 1: Check column names in DataFrame

    Columns are 'X' and 'Y' with uppercase letters.
  2. Step 2: Check function usage of column names

    Function uses 'x' (lowercase), which does not match 'X' (uppercase), causing KeyError.
  3. Final Answer:

    KeyError because 'x' column does not exist (case sensitive). -> Option A
  4. Quick Check:

    Column names are case sensitive [OK]
Hint: Check exact column names and case sensitivity [OK]
Common Mistakes:
  • Ignoring case sensitivity in column names
  • Using wrong axis parameter
  • Assuming no error without testing
5.

You have a DataFrame df with columns 'Name', 'Math', and 'English'. You want to create a new column 'Result' that shows 'Pass' if the average of 'Math' and 'English' is 50 or more, otherwise 'Fail'. Which code correctly uses apply() with axis=1 to do this?

hard
A. df['Result'] = df.apply(lambda row: 'Pass' if row['Math'] + row['English'] >= 50 else 'Fail', axis=1)
B. df['Result'] = df.apply(lambda col: 'Pass' if (col['Math'] + col['English']) / 2 >= 50 else 'Fail', axis=0)
C. df['Result'] = df.apply(lambda row: 'Pass' if (row['Math'] + row['English']) / 2 >= 50 else 'Fail', axis=1)
D. df['Result'] = df.apply(lambda row: 'Pass' if row['Math'] >= 50 and row['English'] >= 50 else 'Fail')

Solution

  1. Step 1: Understand the condition for passing

    Pass if average of 'Math' and 'English' >= 50, else Fail.
  2. Step 2: Check each option's logic and axis

    df['Result'] = df.apply(lambda row: 'Pass' if (row['Math'] + row['English']) / 2 >= 50 else 'Fail', axis=1) correctly uses axis=1 for row-wise apply and calculates average properly. df['Result'] = df.apply(lambda col: 'Pass' if (col['Math'] + col['English']) / 2 >= 50 else 'Fail', axis=0) uses axis=0 (column-wise), which is wrong. df['Result'] = df.apply(lambda row: 'Pass' if row['Math'] >= 50 and row['English'] >= 50 else 'Fail') misses axis=1 and uses wrong condition. df['Result'] = df.apply(lambda row: 'Pass' if row['Math'] + row['English'] >= 50 else 'Fail', axis=1) checks sum >= 50, which is incorrect for average >= 50.
  3. Final Answer:

    df['Result'] = df.apply(lambda row: 'Pass' if (row['Math'] + row['English']) / 2 >= 50 else 'Fail', axis=1) -> Option C
  4. Quick Check:

    Use axis=1 and correct average condition [OK]
Hint: Use axis=1 and check average inside lambda [OK]
Common Mistakes:
  • Using axis=0 applies function column-wise
  • Forgetting to divide sum by 2 for average
  • Using wrong logical conditions
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