sum columns pandas code example

Example 1: pandas ttable with sum totals

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

Example 2: sum columns r

colSums (x, na.rm = FALSE, dims = 1)
rowSums (x, na.rm = FALSE, dims = 1)
colMeans(x, na.rm = FALSE, dims = 1)
rowMeans(x, na.rm = FALSE, dims = 1)

Example 3: python column = sum of list of columns

list_of_my_columns = ['Col A', 'Col E', 'Col Z']
df['Sum'] = df[list_of_my_columns].sum(axis=1)

Example 4: pandas sum missing values

dfObj.isnull().sum()

Tags:

R Example