pandas sum rows code example

Example 1: pandas sum rows

# Basic syntax:
df.sum(axis=1)

# Create new column consisting of row sums across specific columns:
df['sums'] = df.iloc[:, 6:23].sum(axis=1)

# Where:
#	- iloc allows you to specify the rows and columns with slicing. Here
#		I select all rows and sum over columns 6-22
#	- df['sums'] is how you assign a new column named 'sums' to the df

# Example usage:
import pandas as pd
import numpy as np

# Create dataframe:
df = pd.DataFrame(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]), 
                  columns=['a', 'b', 'c'])

print(df)
   a  b  c
0  1  2  3
1  4  5  6
2  7  8  9

# Sum columns 1-2:
df['sums'] = df.iloc[:, 1:3].sum(axis=1)

print(df)
   a  b  c  sums
0  1  2  3     5
1  4  5  6    11
2  7  8  9    17

Example 2: 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 3: pandas groupby sum

df.groupby(['Fruit','Name'])['Number'].sum()

Example 4: pandas row sum

df.sum(axis=1)

Example 5: pandas sum missing values

dfObj.isnull().sum()

Example 6: pandas sum

# select numeric columns and calculate the sums
sums = df.select_dtypes(pd.np.number).sum().rename('total')

# append sums to the data frame
df.append(sums)
#         X  MyColumn      Y      Z
#0        A      84.0   13.0   69.0
#1        B      76.0   77.0  127.0
#2        C      28.0   69.0   16.0
#3        D      28.0   28.0   31.0
#4        E      19.0   20.0   85.0
#5        F      84.0  193.0   70.0
#total  NaN     319.0  400.0  398.0

Tags:

Misc Example