w3resource

Compute sum of all elements in 1D array using np.add.reduce

NumPy: Universal Functions Exercise-9 with Solution

ufunc Reduce Method:

Write a NumPy program that uses the np.add.reduce ufunc to compute the sum of all elements in a 1D array.

Sample Solution:

Python Code:

import numpy as np

# Create a 1D NumPy array of integers
array_1d = np.array([1, 2, 3, 4, 5])

# Use the np.add.reduce ufunc to compute the sum of all elements in the array
sum_of_elements = np.add.reduce(array_1d)

# Print the original array and the sum of its elements
print('Original 1D array:', array_1d)
print('Sum of all elements using np.add.reduce:', sum_of_elements)

Output:

Original 1D array: [1 2 3 4 5]
Sum of all elements using np.add.reduce: 15

Explanation:

  • Import Libraries:
    • Imported numpy as "np" for array creation and manipulation.
  • Create 1D NumPy Array:
    • Create a 1D NumPy array named ‘array_1d’ with integers [1, 2, 3, 4, 5].
  • Use np.add.reduce ufunc:
    • Used the np.add.reduce ufunc to compute the sum of all elements in 'array_1d'. The reduce method applies the np.add ufunc cumulatively to the elements of the array, resulting in the sum.
  • Print Results:
    • Print the original array and the sum of its elements computed using 'np.add.reduce'.

Python-Numpy Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Apply np.exp, np.log, and np.sqrt ufuncs to transform a NumPy array.
Next: Compute cumulative product of elements using np.multiply.accumulate.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/python-exercises/numpy/compute-sum-of-all-elements-in-1d-array-using-np-dot-add-dot-reduce.php