Instagram
youtube
Facebook
Twitter

Apply Function Row-wise and Create New Column in Pandas

Apply Function Row-wise and Create New Column in Pandas

Code Explanation:
Row-wise Application: apply() with axis=1 is used to apply the function to each row.
Lambda Function: Calculates the sum of values from columns 'A' and 'B'.
New Column: The result of each row's sum is stored in a new column 'Sum'.
Output Display: The updated DataFrame is printed, now including the 'Sum' column.

 

Program:

import pandas as pd

df = pd.DataFrame({
    'A': [10, 20, 30],
    'B': [1, 2, 3]
})

df['Sum'] = df.apply(lambda row: row['A'] + row['B'], axis=1)
print(df)