Get Sum in Python – List, pandas DataFrame Column & Row (4 Examples)

In this article you’ll learn how to compute the sum of a list or a pandas DataFrame column in Python.

Example 1: Calculating the Sum of a List Object

my_lt = [10, 6, 2, 2, 15, 20, 3, 7, 4]      # Constructing a list in Python
print(my_lt)
# [10, 6, 2, 2, 15, 20, 3, 7, 4]
import numpy as np                          # Import NumPy library in Python
print(np.sum(my_lt))                        # Computing the sum of a list
# 69

Example 2: Calculating the Sum of the Columns in a pandas DataFrame

import pandas as pd                         # Import pandas
my_df = pd.DataFrame({'A':range(10, 17),    # Constructing a pandas DataFrame
                      'B':[6, 1, 8, 5, 3, 8, 9],
                      'C':range(2, 9),
                      'GRP':['gr1', 'gr2', 'gr1', 'gr3', 'gr1', 'gr2', 'gr3']})
print(my_df)
#     A  B  C  GRP
# 0  10  6  2  gr1
# 1  11  1  3  gr2
# 2  12  8  4  gr1
# 3  13  5  5  gr3
# 4  14  3  6  gr1
# 5  15  8  7  gr2
# 6  16  9  8  gr3
print(my_df.sum())                          # Computing the sum of all columns
# A                         91
# B                         40
# C                         35
# GRP    gr1gr2gr1gr3gr1gr2gr3
# dtype: object

Example 3: Calculating the Sum of the Columns in a pandas DataFrame by Group

print(my_df.groupby('GRP').sum())           # Computing the column sums by group
#       A   B   C
# GRP            
# gr1  36  17  12
# gr2  26   9  10
# gr3  29  14  13

Example 4: Calculating the Sum of the Rows in a pandas DataFrame

print(my_df.sum(axis = 1))                  # Computing the sum of all rows
# 0    18
# 1    15
# 2    24
# 3    23
# 4    23
# 5    30
# 6    33
# dtype: int64

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top