Pandas Sum DataFrame Columns With Examples

To sum pandas DataFrame columns (given selected multiple columns) using either sum(), iloc[], eval() and loc[] functions. Among these pandas DataFrame.sum() function returns the sum of the values for the requested axis, In order to calculate the sum of columns use axis=1. In this article, I will explain how to sum pandas DataFrame rows for given columns with examples.

# Below are quick example
# Using DataFrame.sum() to Sum of each row
df2 = df.sum(axis=1)

# Sum the rows of DataFrame
df['Sum'] = df.sum(axis=1)

# Just a few columns to sum
df['Sum'] = df['mathantics'] + df['science'] + df['english']

# Remove english column
col_list= list(df)

# sum specific columns
col_list= list(df)
df['Sum'] = df[col_list].sum(axis=1)

# Select 1 to 3 columns to sum

# Select 1 and 2 columns to sum Using DataFrame.iloc[]

# Using DataFrame.iloc[] to select 2 and 3 columns to sum

# Sum columns Fee and Discount for row from r2 to r3
df['Sum'] = df.loc['r2':'r4',['mathantics','science']].sum(axis = 1)

# Using DataFrame.eval() function to sum of rows
df2 = df.eval('Sum = mathantics + english')

# Using DataFrame.loc[] and eval function to sum specific rows
df2 = df.loc['r2':'r4'].eval('Sum = mathantics + science')

Now, let’s create a DataFrame with a few rows and columns, execute these examples and validate results. Our DataFrame contains column names studentname, mathantics, science and english.

import pandas as pd
studentdetails = {
"mathantics" :[80,90,85,70,95],
"science" :[85,95,80,90,75],
"english" :[90,85,80,70,95]
df = pd.DataFrame(studentdetails ,index=index_labels)

Yields below output.

studentname  mathantics  science  english
r1 Ram 80 85 90
r2 Sam 90 95 85
r3 Scott 85 80 80
r4 Ann 70 90 70
r5 John 95 75 95



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store