Pandas - Applying a Custom Function to Rows using apply()
Pandas: Custom Function Exercise-2 with Solution
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.
Python-Pandas Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Pandas - Applying a Custom Function Element-wise with applymap().
Next: Pandas - Applying a Custom Function to Columns using apply().
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics