Instagram
youtube
Facebook
Twitter

Apply a Function to Each Column in a DataFrame

Apply a Function to Each Column in a DataFrame
Code Explanation:
Function Application: apply() with axis=0 applies the function to each column.
Lambda Function: Calculates the sum of values in each column.
Store Result: The result is stored in the variable col_sum.
Output Display: The column-wise sum is printed using print().

 

Program:

import pandas as pd

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

col_sum = df.apply(lambda col: col.sum(), axis=0)
print(col_sum)