w3resource

Pandas - Applying a Custom Function to Rows using apply()


2. Apply Custom Function to Each Row Using apply()

Write a Pandas program that apply a custom function to each row using apply() function.

In this exercise, we have applied a custom function that calculates the sum of each row in a DataFrame using apply() function.

Sample Solution:

Code :

import pandas as pd

# Create a sample DataFrame
df = pd.DataFrame({
    'A': [1, 2, 3],
    'B': [4, 5, 6],
    'C': [7, 8, 9]
})

# Define a custom function to calculate the sum of a row
def row_sum(row):
    return row.sum()

# Apply the custom function row-wise
df['Row_Sum'] = df.apply(row_sum, axis=1)

# Output the result
print(df)

Output:

   A  B  C  Row_Sum
0  1  4  7       12
1  2  5  8       15
2  3  6  9       18                                     

Explanation:

  • Created a DataFrame with columns 'A', 'B', 'C'.
  • Defined a function row_sum() to calculate the sum of a row.
  • Applied row_sum() row-wise using apply() with axis=1.
  • Added the row sums as a new column to the DataFrame.

For more Practice: Solve these Related Problems:

  • Write a Pandas program to calculate the sum of each row using a custom function applied with apply(axis=1).
  • Write a Pandas program to create a new column that concatenates values from multiple columns by applying a custom function to each row.
  • Write a Pandas program to apply a custom function row-wise that returns the maximum value among selected columns.
  • Write a Pandas program to compute a new metric for each row by applying a custom function using apply(axis=1) with conditional logic.

Go to:


Previous: Apply Custom Function to Multiple Columns Using apply().
Next: Apply Custom Function to Each Column Using apply().

Python-Pandas Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.