1# Basic syntax:
2df.sum(axis=1)
3
4# Create new column consisting of row sums across specific columns:
5df['sums'] = df.iloc[:, 6:23].sum(axis=1)
6
7# Where:
8# - iloc allows you to specify the rows and columns with slicing. Here
9# I select all rows and sum over columns 6-22
10# - df['sums'] is how you assign a new column named 'sums' to the df
11
12# Example usage:
13import pandas as pd
14import numpy as np
15
16# Create dataframe:
17df = pd.DataFrame(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]),
18 columns=['a', 'b', 'c'])
19
20print(df)
21 a b c
220 1 2 3
231 4 5 6
242 7 8 9
25
26# Sum columns 1-2:
27df['sums'] = df.iloc[:, 1:3].sum(axis=1)
28
29print(df)
30 a b c sums
310 1 2 3 5
321 4 5 6 11
332 7 8 9 17
1import numpy as np
2import pandas as pd
3
4
5df = pd.DataFrame({'a': [10,20],'b':[100,200],'c': ['a','b']})
6
7df.loc['Column_Total']= df.sum(numeric_only=True, axis=0)
8df.loc[:,'Row_Total'] = df.sum(numeric_only=True, axis=1)
9
10print(df)
11
12 a b c Row_Total
130 10.0 100.0 a 110.0
141 20.0 200.0 b 220.0
15Column_Total 30.0 300.0 NaN 330.0
1# select numeric columns and calculate the sums
2sums = df.select_dtypes(pd.np.number).sum().rename('total')
3
4# append sums to the data frame
5df.append(sums)
6# X MyColumn Y Z
7#0 A 84.0 13.0 69.0
8#1 B 76.0 77.0 127.0
9#2 C 28.0 69.0 16.0
10#3 D 28.0 28.0 31.0
11#4 E 19.0 20.0 85.0
12#5 F 84.0 193.0 70.0
13#total NaN 319.0 400.0 398.0
14