0
0
NumPydata~5 mins

Understanding ufunc methods (reduce, accumulate) in NumPy

Choose your learning style9 modes available
Introduction

Ufunc methods like reduce and accumulate help you quickly combine or process array elements step-by-step. They make calculations easier and faster.

When you want to add or multiply all numbers in a list quickly.
When you want to see the running total or product of numbers in a list.
When you need to combine data step-by-step to understand how values build up.
When you want to perform fast calculations on large arrays without writing loops.
Syntax
NumPy
numpy.ufunc.reduce(array, axis=None, dtype=None, out=None, keepdims=False)
numpy.ufunc.accumulate(array, axis=None, dtype=None, out=None)

reduce combines all elements into one value using the ufunc (like sum or multiply).

accumulate shows the intermediate results after applying the ufunc step-by-step.

Examples
This adds all numbers: 1 + 2 + 3 + 4 = 10.
NumPy
import numpy as np
arr = np.array([1, 2, 3, 4])
sum_result = np.add.reduce(arr)
print(sum_result)
This shows running sums: [1, 3, 6, 10].
NumPy
import numpy as np
arr = np.array([1, 2, 3, 4])
accum_result = np.add.accumulate(arr)
print(accum_result)
This multiplies all numbers: 1 * 2 * 3 * 4 = 24.
NumPy
import numpy as np
arr = np.array([1, 2, 3, 4])
prod_result = np.multiply.reduce(arr)
print(prod_result)
This shows running products: [1, 2, 6, 24].
NumPy
import numpy as np
arr = np.array([1, 2, 3, 4])
accum_prod = np.multiply.accumulate(arr)
print(accum_prod)
Sample Program

This program shows how to use reduce and accumulate with addition and multiplication on a simple array.

NumPy
import numpy as np

# Create an array
arr = np.array([2, 3, 5, 7])

# Use reduce to sum all elements
sum_all = np.add.reduce(arr)

# Use accumulate to get running sums
running_sum = np.add.accumulate(arr)

# Use reduce to multiply all elements
product_all = np.multiply.reduce(arr)

# Use accumulate to get running products
running_product = np.multiply.accumulate(arr)

print(f"Sum of all elements: {sum_all}")
print(f"Running sums: {running_sum}")
print(f"Product of all elements: {product_all}")
print(f"Running products: {running_product}")
OutputSuccess
Important Notes

Reduce returns a single combined value.

Accumulate returns an array of intermediate results.

These methods work with many ufuncs like add, multiply, minimum, maximum.

Summary

Use reduce to combine all array elements into one result.

Use accumulate to see step-by-step results of combining elements.

They help do fast calculations without writing loops.