python - Appending column totals to a Pandas DataFrame - Stack Overflow

PHOTO EMBED

Wed Jul 27 2022 02:36:43 GMT+0000 (Coordinated Universal Time)

Saved by [deleted user] #python

import numpy as np
import pandas as pd


df = pd.DataFrame({'a': [10,20],'b':[100,200],'c': ['a','b']})

df.loc['Column_Total']= df.sum(numeric_only=True, axis=0)
df.loc[:,'Row_Total'] = df.sum(numeric_only=True, axis=1)

print(df)

                 a      b    c  Row_Total
0             10.0  100.0    a      110.0
1             20.0  200.0    b      220.0
Column_Total  30.0  300.0  NaN      330.0
content_copyCOPY

https://stackoverflow.com/questions/20804673/appending-column-totals-to-a-pandas-dataframe