Find the sum and product of a NumPy array elements


A Python package called NumPy is employed in scientific computing and to handle large-scale numerical data. It provides support for multi-dimensional arrays and matrices, as well as a large library of mathematical functions to manipulate them. In this tutorial, we will focus on two of the most commonly used NumPy functions: sum() and prod(). These functions are used to calculate the sum and product of all the elements in a NumPy array, respectively.

Installation

Get the numpy package installed using pip inside your terminal

pip install numpy

Import it as highlighted after successful installation −

import numpy as np

Syntax

NumPy provides two useful functions for calculating the sum and product of arrays −

  • np.sum() - np.sum(array, axis=None, dtype=None, out=None, keepdims=<no value>)

  • np.prod() - np.prod(array, axis=None, dtype=None, out=None, keepdims=<no value>)

The NumPy array you want to use for the operation is the first argument you give to both functions. The function will calculate the array's sum or product if the optional parameter axis is not specified. The axis along which the calculation will be performed can be specified with the help of the axis parameter. The data type of the returned value can be specified using the optional parameter dtype. The function will place the output in the specified array if the optional parameter out is specified. Finally, you can decide whether or not to keep the dimensions of the output array the same as those of the input array using the optional parameter keepdims.

Algorithm

  • Import the NumPy library.

  • Create a NumPy array.

  • Use the sum() or prod() function to calculate the sum or product of the elements in the array.

Example

import numpy as np

# Example 1: Calculate the sum of all the elements in a 1D array
a = np.array([1, 2, 3, 4, 5])
total_sum = np.sum(a)
print(total_sum) # Output: 15

# Example 2: Calculate the product of all the elements in a 1D array
b = np.array([2, 3, 4, 5])
total_prod = np.prod(b)
print(total_prod) # Output: 120

# Example 3: Calculate the sum of all the elements in a 2D array along the columns
c = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
col_sum = np.sum(c, axis=0)
print(col_sum) # Output: [12 15 18]

Output

15
120
[12 15 18]

Example

How to use the sum() and prod() functions in NumPy to calculate the sum and product of all the elements in a 2D array.

import numpy as np

# Create a 2D NumPy array
a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

# Add together all the array's components to get the total.
total_sum = np.sum(a)
print(total_sum) # Output: 45

# compute the array's total elements' product.
total_prod = np.prod(a)
print(total_prod) # Output: 362880

# Calculate the sum of all the elements in the array using a for loop
sum = 0
for i in range(len(a)):
   sum += a[i]
print(sum) # Output: 45

Output

45
362880
[12 15 18]

To cycle through the array's elements and add each one to the variable total, use a for loop or a for expression inside a list comprehension. The total of all the items in the array is displayed after iterating over all of the elements.

Broadcasting

Moreover, broadcasting, a potent technique that enables NumPy to operate on arrays of various forms, is supported by NumPy arrays. In order for the smaller array and the bigger array to have similar forms, they are broadcast over one another. Here is an illustration of how to compute the sum and product of a NumPy array using broadcasting −

Example

import numpy as np

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

# Calculate the sum of the two arrays
total_sum = a + b
print(total_sum) # Output: [5 7 9]

# Calculate the product of the two arrays
total_prod = a * b
print(total_prod) # Output: [ 4 10 18]

Output

[5 7 9]
[ 4 10 18]

In this example, we are performing arithmetic operations between two arrays of different shapes. However, the broadcasting feature automatically broadcasts the smaller array across the larger array so that the shapes are compatible for the operation.

Applications

The ability to calculate the sum and product of NumPy arrays is useful in many scientific and engineering applications. Some examples of applications include −

  • Calculating the total revenue from sales data stored in a NumPy array

  • Computing the average temperature of a city over a period of time using temperature data stored in a NumPy array

  • Finding the maximum and minimum values of a set of data stored in a NumPy array

  • Calculating the dot product between two vectors stored as NumPy arrays

Conclusion

In this post, we learnt how to use the sum() and prod() methods to compute the sum and product of NumPy array components as well as how to use broadcasting to carry out arithmetic operations on arrays with various forms. The scientific and technical community chose NumPy because it can do effective array calculations.

Updated on: 21-Aug-2023

195 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements