method
ufunc.reduce(a, axis=0, dtype=None, out=None, keepdims=False, initial=<no value>, where=True) Reduces a’s dimension by one, by applying ufunc along one axis.
Let . Then
= the result of iterating
j over , cumulatively applying ufunc to each
. For a one-dimensional array, reduce produces results equivalent to:
r = op.identity # op = ufunc for i in range(len(A)): r = op(r, A[i]) return r
For example, add.reduce() is equivalent to sum().
| Parameters: |
|
|---|---|
| Returns: |
|
>>> np.multiply.reduce([2,3,5]) 30
A multi-dimensional array example:
>>> X = np.arange(8).reshape((2,2,2))
>>> X
array([[[0, 1],
[2, 3]],
[[4, 5],
[6, 7]]])
>>> np.add.reduce(X, 0)
array([[ 4, 6],
[ 8, 10]])
>>> np.add.reduce(X) # confirm: default axis value is 0
array([[ 4, 6],
[ 8, 10]])
>>> np.add.reduce(X, 1)
array([[ 2, 4],
[10, 12]])
>>> np.add.reduce(X, 2)
array([[ 1, 5],
[ 9, 13]])
You can use the initial keyword argument to initialize the reduction with a different value, and where to select specific elements to include:
>>> np.add.reduce([10], initial=5) 15 >>> np.add.reduce(np.ones((2, 2, 2)), axis=(0, 2), initial=10) array([14., 14.]) >>> a = np.array([10., np.nan, 10]) >>> np.add.reduce(a, where=~np.isnan(a)) 20.0
Allows reductions of empty arrays where they would normally fail, i.e. for ufuncs without an identity.
>>> np.minimum.reduce([], initial=np.inf)
inf
>>> np.minimum.reduce([[1., 2.], [3., 4.]], initial=10., where=[True, False])
array([ 1., 10.])
>>> np.minimum.reduce([])
Traceback (most recent call last):
...
ValueError: zero-size array to reduction operation minimum which has no identity
© 2005–2019 NumPy Developers
Licensed under the 3-clause BSD License.
https://docs.scipy.org/doc/numpy-1.17.0/reference/generated/numpy.ufunc.reduce.html