w3resource

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


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: