Instagram
youtube
Facebook
Twitter

Apply a Function to Each Row in a DataFrame

Apply a Function to Each Row in a DataFrame
Code Explanation:
Function Application: apply() method with axis=1 is used to apply a function across each row.
Lambda Function: A lambda function is passed to compute the sum of values in each row.
Store Result: The result is stored in the variable row_sum.
Output Display: The total (row-wise sum) for each row is printed.

 

Program:

import pandas as pd

df = pd.DataFrame({
    'Math': [80, 90, 85],
    'Science': [75, 88, 92],
    'English': [78, 83, 89]
})

row_sum = df.apply(lambda row: row.sum(), axis=1)
print(row_sum)