[ Web Proxy ]
URL:
Viewing: https://www.pythontutorial.net/python-numpy/numpy-sum/ [Back]  [Original]

NumPy sum(): Calculate the Sum of Elements in an Array
Skip to content

NumPy sum()

Summary: in this tutorial, you’ll learn how to use the numpy sum() function to return the sum of all elements in an array.

Introduction to the numpy sum() function #

The numpy sum() function is an aggregate function that takes an array and returns the sum of all elements.

The following example uses the sum() function to calculate the sum of all elements of a 1-D array:

import numpy as np

a = np.array([1, 2, 3])
total = np.sum(a)
print(total)Code language: Python (python)

Output:

6Code language: Python (python)

How it works.

First, create a new numpy array that has three numbers 1, 2, and 3:

a = np.array([1, 2, 3])Code language: Python (python)

Second, calculate the sum of all elements in array a by using the sum() function:

total = np.sum(a)Code language: Python (python)

Third, display the result:

print(total)Code language: Python (python)

The following example uses the sum() function to calculate the sum of all elements of a 2-D array:

import numpy as np

a = np.array([
    [1, 2, 3],
    [4, 5, 6]
])

total = np.sum(a)
print(total)Code language: Python (python)

Output:

21Code language: Python (python)

In this example, the sum() adds up all the numbers of the array a.

The sum() function also accepts the axis argument that allows you to return the sum of elements of an axis. For example:

import numpy as np

a = np.array([
    [1, 2, 3],
    [4, 5, 6]
])

total = np.sum(a, axis=0)
print(total)Code language: Python (python)
[]

Output:

[5 7 9]Code language: Python (python)

In this example, the sum() function returns a new array where each element is the sum of elements of the array a on axis-0.

Similarly, you can sum elements on axis-1 like this:

import numpy as np

a = np.array([
    [1, 2, 3],
    [4, 5, 6]
])

total = np.sum(a, axis=1)
print(total)Code language: Python (python)

Output:

[]
[ 6 15]Code language: Python (python)

Summary #

Was this tutorial helpful ?
Yes No
Search …:

Getting Started

Creating Arrays

Array Indexing & Slicing

Aggregate Functions

Array Operations

Arithmetic Operations

Joining & Splitting Arrays

Copyright © 2021 - Present, By Python Tutorial. All Rights Reserved.


Web Proxy Viewer  |  New URL  |  Original Page