What is the best way to sum all values in a pandas dataframe?

Given a pandas dataframe, we have to find the sum all values in a pandas dataframe. By Pranit Sharma Last updated : October 01, 2023

Pandas is a special tool that allows us to perform complex manipulations of data effectively and efficiently. Inside pandas, we mostly deal with a dataset in the form of DataFrame. DataFrames are 2-dimensional data structures in pandas. DataFrames consist of rows, columns, and data.

The sum here represents the addition of all the values of the DataFrame. This operation can be computed in two ways.

  1. By using the sum() method twice
  2. By using the DataFrame.values.sum() method

Both of the methods have their pros and cons, method 2 is fast and satisfying but it returns a float value in the case of a nan value.

Let us understand both methods with the help of an example,

Find the sum all values in a pandas dataframe using sum() method twice

# Importing pandas package
import pandas as pd

# Importing numpy package
import numpy as np

# Creating a dictionary
d = {
    'A':[1,4,3,7,3],
    'B':[6,3,8,5,3],
    'C':[78,4,2,74,3]
}

# Creating a DataFrame
df = pd.DataFrame(d)

# Display Original DataFrames
print("Created DataFrame:\n",df,"\n")

# Using sum method twice
res = df.sum().sum()

# Display result
print("Sum:\n",res)

Output

The output of the above program is:

Example 1: Sum all values in a pandas dataframe

Find the sum all values in a pandas dataframe DataFrame.values.sum() method

# Importing pandas package
import pandas as pd

# Importing numpy package
import numpy as np

# Creating a dictionary
d = {
    'A':[1,4,3,7,3],
    'B':[6,3,8,5,3],
    'C':[78,4,2,74,3]
}

# Creating a DataFrame
df = pd.DataFrame(d)

# Display Original DataFrames
print("Created DataFrame:\n",df,"\n")

# Using df.values.sum twice
res = df.values.sum()

# Display result
print("Sum:\n",res)

Output

The output of the above program is:

Example 2: Sum all values in a pandas dataframe

Python Pandas Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.