w3resource

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


9. Ufunc: Sum Reduction with 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'.

For more Practice: Solve these Related Problems:

  • Write a Numpy program to compute the sum of a 1D array using np.add.reduce and then compare it with np.sum for consistency.
  • Write a Numpy program to use np.add.reduce to sum elements conditionally based on a mask array.
  • Write a Numpy program to apply np.add.reduce on segmented parts of a 1D array and then combine the results.
  • Write a Numpy program to implement np.add.reduce on a large array and analyze its performance versus a standard summation loop.

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.



Follow us on Facebook and Twitter for latest update.