Instagram
youtube
Facebook
Twitter

Apply Function Column-wise and Add Total Row in Pandas

Apply Function Column-wise and Add Total Row in Pandas.

Code Explanation:
Column-wise Application: The apply() function calculates the sum of each column.
New Row: The result is stored in a new row labeled 'Total' using df.loc['Total'].
Output Display: The DataFrame is printed, now including the new 'Total' row at the bottom.

 

Program:

import pandas as pd

df = pd.DataFrame({
    'Math': [85, 90, 95],
    'Science': [80, 85, 88],
    'English': [78, 82, 85]
})

df.loc['Total'] = df.apply(lambda col: col.sum())
print(df)