2

I'm learning numpy package, and I've found this code example:

import numpy as np
a = np.array([[1,2,3], [4,5,6]])
np.add.reduce(a)

The thing I'm unable to understand is the dot notation:

np.add.reduce(a)

in contrast with, for example

np.add(a,5)

I understand what add and reduce do, but what is add? What is reduce?

BDL
  • 21,052
  • 22
  • 49
  • 55
31173
  • 21
  • 3
  • https://stackoverflow.com/questions/16420097/what-is-the-difference-between-np-sum-and-np-add-reduce – Inder Aug 26 '18 at 10:08
  • 1
    @Inder Thank you, I actually learned that something new when *answering* a question! "add.reduce is about twice faster" (than sum) – nyanpasu64 Aug 26 '18 at 10:15
  • `np.add` is a `ufunc`. `reduce` is a method of that function. – hpaulj Aug 26 '18 at 15:01

1 Answers1

1

"Reduce" is a general concept, and I found a decent definition at https://docs.python.org/3/library/functools.html#functools.reduce

Apply function of two arguments cumulatively to the items of sequence, from left to right, so as to reduce the sequence to a single value.

Numpy's ufunc reduce is documented at https://docs.scipy.org/doc/numpy/reference/generated/numpy.ufunc.reduce.html

Reduces a’s dimension by one, by applying ufunc along one axis.

So np.add.reduce(a) (also known as np.add.reduce(a, axis=0)) will call np.add on a[0] and a[1], then add the result to a[2], etc. until it incorporates all len(a) elements.

Result: array([5, 7, 9])


np.add(x, y) is basically x + y. np.add.reduce(a, axis=0) is basically np.sum(a, axis=0).


np.add.reduce(a, axis=1) adds a[:, 0] to a[:, 1], then adds result to a[:, 2], and so on.`

Result: array([ 6, 15])

nyanpasu64
  • 2,805
  • 2
  • 23
  • 31