1"""Module containing non-deprecated functions borrowed from Numeric.
2
3"""
4import functools
5import types
6import warnings
7
8import numpy as np
9from .._utils import set_module
10from . import multiarray as mu
11from . import overrides
12from . import umath as um
13from . import numerictypes as nt
14from .multiarray import asarray, array, asanyarray, concatenate
15from ._multiarray_umath import _array_converter
16from . import _methods
17
18_dt_ = nt.sctype2char
19
20# functions that are methods
21__all__ = [
22 'all', 'amax', 'amin', 'any', 'argmax',
23 'argmin', 'argpartition', 'argsort', 'around', 'choose', 'clip',
24 'compress', 'cumprod', 'cumsum', 'cumulative_prod', 'cumulative_sum',
25 'diagonal', 'mean', 'max', 'min', 'matrix_transpose',
26 'ndim', 'nonzero', 'partition', 'prod', 'ptp', 'put',
27 'ravel', 'repeat', 'reshape', 'resize', 'round',
28 'searchsorted', 'shape', 'size', 'sort', 'squeeze',
29 'std', 'sum', 'swapaxes', 'take', 'trace', 'transpose', 'var',
30]
31
32_gentype = types.GeneratorType
33# save away Python sum
34_sum_ = sum
35
36array_function_dispatch = functools.partial(
37 overrides.array_function_dispatch, module='numpy')
38
39
40# functions that are now methods
41def _wrapit(obj, method, *args, **kwds):
42 conv = _array_converter(obj)
43 # As this already tried the method, subok is maybe quite reasonable here
44 # but this follows what was done before. TODO: revisit this.
45 arr, = conv.as_arrays(subok=False)
46 result = getattr(arr, method)(*args, **kwds)
47
48 return conv.wrap(result, to_scalar=False)
49
50
51def _wrapfunc(obj, method, *args, **kwds):
52 bound = getattr(obj, method, None)
53 if bound is None:
54 return _wrapit(obj, method, *args, **kwds)
55
56 try:
57 return bound(*args, **kwds)
58 except TypeError:
59 # A TypeError occurs if the object does have such a method in its
60 # class, but its signature is not identical to that of NumPy's. This
61 # situation has occurred in the case of a downstream library like
62 # 'pandas'.
63 #
64 # Call _wrapit from within the except clause to ensure a potential
65 # exception has a traceback chain.
66 return _wrapit(obj, method, *args, **kwds)
67
68
69def _wrapreduction(obj, ufunc, method, axis, dtype, out, **kwargs):
70 passkwargs = {k: v for k, v in kwargs.items()
71 if v is not np._NoValue}
72
73 if type(obj) is not mu.ndarray:
74 try:
75 reduction = getattr(obj, method)
76 except AttributeError:
77 pass
78 else:
79 # This branch is needed for reductions like any which don't
80 # support a dtype.
81 if dtype is not None:
82 return reduction(axis=axis, dtype=dtype, out=out, **passkwargs)
83 else:
84 return reduction(axis=axis, out=out, **passkwargs)
85
86 return ufunc.reduce(obj, axis, dtype, out, **passkwargs)
87
88
89def _wrapreduction_any_all(obj, ufunc, method, axis, out, **kwargs):
90 # Same as above function, but dtype is always bool (but never passed on)
91 passkwargs = {k: v for k, v in kwargs.items()
92 if v is not np._NoValue}
93
94 if type(obj) is not mu.ndarray:
95 try:
96 reduction = getattr(obj, method)
97 except AttributeError:
98 pass
99 else:
100 return reduction(axis=axis, out=out, **passkwargs)
101
102 return ufunc.reduce(obj, axis, bool, out, **passkwargs)
103
104
105def _take_dispatcher(a, indices, axis=None, out=None, mode=None):
106 return (a, out)
107
108
109@array_function_dispatch(_take_dispatcher)
110def take(a, indices, axis=None, out=None, mode='raise'):
111 """
112 Take elements from an array along an axis.
113
114 When axis is not None, this function does the same thing as "fancy"
115 indexing (indexing arrays using arrays); however, it can be easier to use
116 if you need elements along a given axis. A call such as
117 ``np.take(arr, indices, axis=3)`` is equivalent to
118 ``arr[:,:,:,indices,...]``.
119
120 Explained without fancy indexing, this is equivalent to the following use
121 of `ndindex`, which sets each of ``ii``, ``jj``, and ``kk`` to a tuple of
122 indices::
123
124 Ni, Nk = a.shape[:axis], a.shape[axis+1:]
125 Nj = indices.shape
126 for ii in ndindex(Ni):
127 for jj in ndindex(Nj):
128 for kk in ndindex(Nk):
129 out[ii + jj + kk] = a[ii + (indices[jj],) + kk]
130
131 Parameters
132 ----------
133 a : array_like (Ni..., M, Nk...)
134 The source array.
135 indices : array_like (Nj...)
136 The indices of the values to extract.
137 Also allow scalars for indices.
138 axis : int, optional
139 The axis over which to select values. By default, the flattened
140 input array is used.
141 out : ndarray, optional (Ni..., Nj..., Nk...)
142 If provided, the result will be placed in this array. It should
143 be of the appropriate shape and dtype. Note that `out` is always
144 buffered if `mode='raise'`; use other modes for better performance.
145 mode : {'raise', 'wrap', 'clip'}, optional
146 Specifies how out-of-bounds indices will behave.
147
148 * 'raise' -- raise an error (default)
149 * 'wrap' -- wrap around
150 * 'clip' -- clip to the range
151
152 'clip' mode means that all indices that are too large are replaced
153 by the index that addresses the last element along that axis. Note
154 that this disables indexing with negative numbers.
155
156 Returns
157 -------
158 out : ndarray (Ni..., Nj..., Nk...)
159 The returned array has the same type as `a`.
160
161 See Also
162 --------
163 compress : Take elements using a boolean mask
164 ndarray.take : equivalent method
165 take_along_axis : Take elements by matching the array and the index arrays
166
167 Notes
168 -----
169 By eliminating the inner loop in the description above, and using `s_` to
170 build simple slice objects, `take` can be expressed in terms of applying
171 fancy indexing to each 1-d slice::
172
173 Ni, Nk = a.shape[:axis], a.shape[axis+1:]
174 for ii in ndindex(Ni):
175 for kk in ndindex(Nj):
176 out[ii + s_[...,] + kk] = a[ii + s_[:,] + kk][indices]
177
178 For this reason, it is equivalent to (but faster than) the following use
179 of `apply_along_axis`::
180
181 out = np.apply_along_axis(lambda a_1d: a_1d[indices], axis, a)
182
183 Examples
184 --------
185 >>> import numpy as np
186 >>> a = [4, 3, 5, 7, 6, 8]
187 >>> indices = [0, 1, 4]
188 >>> np.take(a, indices)
189 array([4, 3, 6])
190
191 In this example if `a` is an ndarray, "fancy" indexing can be used.
192
193 >>> a = np.array(a)
194 >>> a[indices]
195 array([4, 3, 6])
196
197 If `indices` is not one dimensional, the output also has these dimensions.
198
199 >>> np.take(a, [[0, 1], [2, 3]])
200 array([[4, 3],
201 [5, 7]])
202 """
203 return _wrapfunc(a, 'take', indices, axis=axis, out=out, mode=mode)
204
205
206def _reshape_dispatcher(a, /, shape=None, order=None, *, newshape=None,
207 copy=None):
208 return (a,)
209
210
211@array_function_dispatch(_reshape_dispatcher)
212def reshape(a, /, shape=None, order='C', *, newshape=None, copy=None):
213 """
214 Gives a new shape to an array without changing its data.
215
216 Parameters
217 ----------
218 a : array_like
219 Array to be reshaped.
220 shape : int or tuple of ints
221 The new shape should be compatible with the original shape. If
222 an integer, then the result will be a 1-D array of that length.
223 One shape dimension can be -1. In this case, the value is
224 inferred from the length of the array and remaining dimensions.
225 order : {'C', 'F', 'A'}, optional
226 Read the elements of ``a`` using this index order, and place the
227 elements into the reshaped array using this index order. 'C'
228 means to read / write the elements using C-like index order,
229 with the last axis index changing fastest, back to the first
230 axis index changing slowest. 'F' means to read / write the
231 elements using Fortran-like index order, with the first index
232 changing fastest, and the last index changing slowest. Note that
233 the 'C' and 'F' options take no account of the memory layout of
234 the underlying array, and only refer to the order of indexing.
235 'A' means to read / write the elements in Fortran-like index
236 order if ``a`` is Fortran *contiguous* in memory, C-like order
237 otherwise.
238 newshape : int or tuple of ints
239 .. deprecated:: 2.1
240 Replaced by ``shape`` argument. Retained for backward
241 compatibility.
242 copy : bool, optional
243 If ``True``, then the array data is copied. If ``None``, a copy will
244 only be made if it's required by ``order``. For ``False`` it raises
245 a ``ValueError`` if a copy cannot be avoided. Default: ``None``.
246
247 Returns
248 -------
249 reshaped_array : ndarray
250 This will be a new view object if possible; otherwise, it will
251 be a copy. Note there is no guarantee of the *memory layout* (C- or
252 Fortran- contiguous) of the returned array.
253
254 See Also
255 --------
256 ndarray.reshape : Equivalent method.
257
258 Notes
259 -----
260 It is not always possible to change the shape of an array without copying
261 the data.
262
263 The ``order`` keyword gives the index ordering both for *fetching*
264 the values from ``a``, and then *placing* the values into the output
265 array. For example, let's say you have an array:
266
267 >>> a = np.arange(6).reshape((3, 2))
268 >>> a
269 array([[0, 1],
270 [2, 3],
271 [4, 5]])
272
273 You can think of reshaping as first raveling the array (using the given
274 index order), then inserting the elements from the raveled array into the
275 new array using the same kind of index ordering as was used for the
276 raveling.
277
278 >>> np.reshape(a, (2, 3)) # C-like index ordering
279 array([[0, 1, 2],
280 [3, 4, 5]])
281 >>> np.reshape(np.ravel(a), (2, 3)) # equivalent to C ravel then C reshape
282 array([[0, 1, 2],
283 [3, 4, 5]])
284 >>> np.reshape(a, (2, 3), order='F') # Fortran-like index ordering
285 array([[0, 4, 3],
286 [2, 1, 5]])
287 >>> np.reshape(np.ravel(a, order='F'), (2, 3), order='F')
288 array([[0, 4, 3],
289 [2, 1, 5]])
290
291 Examples
292 --------
293 >>> import numpy as np
294 >>> a = np.array([[1,2,3], [4,5,6]])
295 >>> np.reshape(a, 6)
296 array([1, 2, 3, 4, 5, 6])
297 >>> np.reshape(a, 6, order='F')
298 array([1, 4, 2, 5, 3, 6])
299
300 >>> np.reshape(a, (3,-1)) # the unspecified value is inferred to be 2
301 array([[1, 2],
302 [3, 4],
303 [5, 6]])
304 """
305 if newshape is None and shape is None:
306 raise TypeError(
307 "reshape() missing 1 required positional argument: 'shape'")
308 if newshape is not None:
309 if shape is not None:
310 raise TypeError(
311 "You cannot specify 'newshape' and 'shape' arguments "
312 "at the same time.")
313 # Deprecated in NumPy 2.1, 2024-04-18
314 warnings.warn(
315 "`newshape` keyword argument is deprecated, "
316 "use `shape=...` or pass shape positionally instead. "
317 "(deprecated in NumPy 2.1)",
318 DeprecationWarning,
319 stacklevel=2,
320 )
321 shape = newshape
322 if copy is not None:
323 return _wrapfunc(a, 'reshape', shape, order=order, copy=copy)
324 return _wrapfunc(a, 'reshape', shape, order=order)
325
326
327def _choose_dispatcher(a, choices, out=None, mode=None):
328 yield a
329 yield from choices
330 yield out
331
332
333@array_function_dispatch(_choose_dispatcher)
334def choose(a, choices, out=None, mode='raise'):
335 """
336 Construct an array from an index array and a list of arrays to choose from.
337
338 First of all, if confused or uncertain, definitely look at the Examples -
339 in its full generality, this function is less simple than it might
340 seem from the following code description::
341
342 np.choose(a,c) == np.array([c[a[I]][I] for I in np.ndindex(a.shape)])
343
344 But this omits some subtleties. Here is a fully general summary:
345
346 Given an "index" array (`a`) of integers and a sequence of ``n`` arrays
347 (`choices`), `a` and each choice array are first broadcast, as necessary,
348 to arrays of a common shape; calling these *Ba* and *Bchoices[i], i =
349 0,...,n-1* we have that, necessarily, ``Ba.shape == Bchoices[i].shape``
350 for each ``i``. Then, a new array with shape ``Ba.shape`` is created as
351 follows:
352
353 * if ``mode='raise'`` (the default), then, first of all, each element of
354 ``a`` (and thus ``Ba``) must be in the range ``[0, n-1]``; now, suppose
355 that ``i`` (in that range) is the value at the ``(j0, j1, ..., jm)``
356 position in ``Ba`` - then the value at the same position in the new array
357 is the value in ``Bchoices[i]`` at that same position;
358
359 * if ``mode='wrap'``, values in `a` (and thus `Ba`) may be any (signed)
360 integer; modular arithmetic is used to map integers outside the range
361 `[0, n-1]` back into that range; and then the new array is constructed
362 as above;
363
364 * if ``mode='clip'``, values in `a` (and thus ``Ba``) may be any (signed)
365 integer; negative integers are mapped to 0; values greater than ``n-1``
366 are mapped to ``n-1``; and then the new array is constructed as above.
367
368 Parameters
369 ----------
370 a : int array
371 This array must contain integers in ``[0, n-1]``, where ``n`` is the
372 number of choices, unless ``mode=wrap`` or ``mode=clip``, in which
373 cases any integers are permissible.
374 choices : sequence of arrays
375 Choice arrays. `a` and all of the choices must be broadcastable to the
376 same shape. If `choices` is itself an array (not recommended), then
377 its outermost dimension (i.e., the one corresponding to
378 ``choices.shape[0]``) is taken as defining the "sequence".
379 out : array, optional
380 If provided, the result will be inserted into this array. It should
381 be of the appropriate shape and dtype. Note that `out` is always
382 buffered if ``mode='raise'``; use other modes for better performance.
383 mode : {'raise' (default), 'wrap', 'clip'}, optional
384 Specifies how indices outside ``[0, n-1]`` will be treated:
385
386 * 'raise' : an exception is raised
387 * 'wrap' : value becomes value mod ``n``
388 * 'clip' : values < 0 are mapped to 0, values > n-1 are mapped to n-1
389
390 Returns
391 -------
392 merged_array : array
393 The merged result.
394
395 Raises
396 ------
397 ValueError: shape mismatch
398 If `a` and each choice array are not all broadcastable to the same
399 shape.
400
401 See Also
402 --------
403 ndarray.choose : equivalent method
404 numpy.take_along_axis : Preferable if `choices` is an array
405
406 Notes
407 -----
408 To reduce the chance of misinterpretation, even though the following
409 "abuse" is nominally supported, `choices` should neither be, nor be
410 thought of as, a single array, i.e., the outermost sequence-like container
411 should be either a list or a tuple.
412
413 Examples
414 --------
415
416 >>> import numpy as np
417 >>> choices = [[0, 1, 2, 3], [10, 11, 12, 13],
418 ... [20, 21, 22, 23], [30, 31, 32, 33]]
419 >>> np.choose([2, 3, 1, 0], choices
420 ... # the first element of the result will be the first element of the
421 ... # third (2+1) "array" in choices, namely, 20; the second element
422 ... # will be the second element of the fourth (3+1) choice array, i.e.,
423 ... # 31, etc.
424 ... )
425 array([20, 31, 12, 3])
426 >>> np.choose([2, 4, 1, 0], choices, mode='clip') # 4 goes to 3 (4-1)
427 array([20, 31, 12, 3])
428 >>> # because there are 4 choice arrays
429 >>> np.choose([2, 4, 1, 0], choices, mode='wrap') # 4 goes to (4 mod 4)
430 array([20, 1, 12, 3])
431 >>> # i.e., 0
432
433 A couple examples illustrating how choose broadcasts:
434
435 >>> a = [[1, 0, 1], [0, 1, 0], [1, 0, 1]]
436 >>> choices = [-10, 10]
437 >>> np.choose(a, choices)
438 array([[ 10, -10, 10],
439 [-10, 10, -10],
440 [ 10, -10, 10]])
441
442 >>> # With thanks to Anne Archibald
443 >>> a = np.array([0, 1]).reshape((2,1,1))
444 >>> c1 = np.array([1, 2, 3]).reshape((1,3,1))
445 >>> c2 = np.array([-1, -2, -3, -4, -5]).reshape((1,1,5))
446 >>> np.choose(a, (c1, c2)) # result is 2x3x5, res[0,:,:]=c1, res[1,:,:]=c2
447 array([[[ 1, 1, 1, 1, 1],
448 [ 2, 2, 2, 2, 2],
449 [ 3, 3, 3, 3, 3]],
450 [[-1, -2, -3, -4, -5],
451 [-1, -2, -3, -4, -5],
452 [-1, -2, -3, -4, -5]]])
453
454 """
455 return _wrapfunc(a, 'choose', choices, out=out, mode=mode)
456
457
458def _repeat_dispatcher(a, repeats, axis=None):
459 return (a,)
460
461
462@array_function_dispatch(_repeat_dispatcher)
463def repeat(a, repeats, axis=None):
464 """
465 Repeat each element of an array after themselves
466
467 Parameters
468 ----------
469 a : array_like
470 Input array.
471 repeats : int or array of ints
472 The number of repetitions for each element. `repeats` is broadcasted
473 to fit the shape of the given axis.
474 axis : int, optional
475 The axis along which to repeat values. By default, use the
476 flattened input array, and return a flat output array.
477
478 Returns
479 -------
480 repeated_array : ndarray
481 Output array which has the same shape as `a`, except along
482 the given axis.
483
484 See Also
485 --------
486 tile : Tile an array.
487 unique : Find the unique elements of an array.
488
489 Examples
490 --------
491 >>> import numpy as np
492 >>> np.repeat(3, 4)
493 array([3, 3, 3, 3])
494 >>> x = np.array([[1,2],[3,4]])
495 >>> np.repeat(x, 2)
496 array([1, 1, 2, 2, 3, 3, 4, 4])
497 >>> np.repeat(x, 3, axis=1)
498 array([[1, 1, 1, 2, 2, 2],
499 [3, 3, 3, 4, 4, 4]])
500 >>> np.repeat(x, [1, 2], axis=0)
501 array([[1, 2],
502 [3, 4],
503 [3, 4]])
504
505 """
506 return _wrapfunc(a, 'repeat', repeats, axis=axis)
507
508
509def _put_dispatcher(a, ind, v, mode=None):
510 return (a, ind, v)
511
512
513@array_function_dispatch(_put_dispatcher)
514def put(a, ind, v, mode='raise'):
515 """
516 Replaces specified elements of an array with given values.
517
518 The indexing works on the flattened target array. `put` is roughly
519 equivalent to:
520
521 ::
522
523 a.flat[ind] = v
524
525 Parameters
526 ----------
527 a : ndarray
528 Target array.
529 ind : array_like
530 Target indices, interpreted as integers.
531 v : array_like
532 Values to place in `a` at target indices. If `v` is shorter than
533 `ind` it will be repeated as necessary.
534 mode : {'raise', 'wrap', 'clip'}, optional
535 Specifies how out-of-bounds indices will behave.
536
537 * 'raise' -- raise an error (default)
538 * 'wrap' -- wrap around
539 * 'clip' -- clip to the range
540
541 'clip' mode means that all indices that are too large are replaced
542 by the index that addresses the last element along that axis. Note
543 that this disables indexing with negative numbers. In 'raise' mode,
544 if an exception occurs the target array may still be modified.
545
546 See Also
547 --------
548 putmask, place
549 put_along_axis : Put elements by matching the array and the index arrays
550
551 Examples
552 --------
553 >>> import numpy as np
554 >>> a = np.arange(5)
555 >>> np.put(a, [0, 2], [-44, -55])
556 >>> a
557 array([-44, 1, -55, 3, 4])
558
559 >>> a = np.arange(5)
560 >>> np.put(a, 22, -5, mode='clip')
561 >>> a
562 array([ 0, 1, 2, 3, -5])
563
564 """
565 try:
566 put = a.put
567 except AttributeError as e:
568 raise TypeError("argument 1 must be numpy.ndarray, "
569 "not {name}".format(name=type(a).__name__)) from e
570
571 return put(ind, v, mode=mode)
572
573
574def _swapaxes_dispatcher(a, axis1, axis2):
575 return (a,)
576
577
578@array_function_dispatch(_swapaxes_dispatcher)
579def swapaxes(a, axis1, axis2):
580 """
581 Interchange two axes of an array.
582
583 Parameters
584 ----------
585 a : array_like
586 Input array.
587 axis1 : int
588 First axis.
589 axis2 : int
590 Second axis.
591
592 Returns
593 -------
594 a_swapped : ndarray
595 For NumPy >= 1.10.0, if `a` is an ndarray, then a view of `a` is
596 returned; otherwise a new array is created. For earlier NumPy
597 versions a view of `a` is returned only if the order of the
598 axes is changed, otherwise the input array is returned.
599
600 Examples
601 --------
602 >>> import numpy as np
603 >>> x = np.array([[1,2,3]])
604 >>> np.swapaxes(x,0,1)
605 array([[1],
606 [2],
607 [3]])
608
609 >>> x = np.array([[[0,1],[2,3]],[[4,5],[6,7]]])
610 >>> x
611 array([[[0, 1],
612 [2, 3]],
613 [[4, 5],
614 [6, 7]]])
615
616 >>> np.swapaxes(x,0,2)
617 array([[[0, 4],
618 [2, 6]],
619 [[1, 5],
620 [3, 7]]])
621
622 """
623 return _wrapfunc(a, 'swapaxes', axis1, axis2)
624
625
626def _transpose_dispatcher(a, axes=None):
627 return (a,)
628
629
630@array_function_dispatch(_transpose_dispatcher)
631def transpose(a, axes=None):
632 """
633 Returns an array with axes transposed.
634
635 For a 1-D array, this returns an unchanged view of the original array, as a
636 transposed vector is simply the same vector.
637 To convert a 1-D array into a 2-D column vector, an additional dimension
638 must be added, e.g., ``np.atleast_2d(a).T`` achieves this, as does
639 ``a[:, np.newaxis]``.
640 For a 2-D array, this is the standard matrix transpose.
641 For an n-D array, if axes are given, their order indicates how the
642 axes are permuted (see Examples). If axes are not provided, then
643 ``transpose(a).shape == a.shape[::-1]``.
644
645 Parameters
646 ----------
647 a : array_like
648 Input array.
649 axes : tuple or list of ints, optional
650 If specified, it must be a tuple or list which contains a permutation
651 of [0, 1, ..., N-1] where N is the number of axes of `a`. Negative
652 indices can also be used to specify axes. The i-th axis of the returned
653 array will correspond to the axis numbered ``axes[i]`` of the input.
654 If not specified, defaults to ``range(a.ndim)[::-1]``, which reverses
655 the order of the axes.
656
657 Returns
658 -------
659 p : ndarray
660 `a` with its axes permuted. A view is returned whenever possible.
661
662 See Also
663 --------
664 ndarray.transpose : Equivalent method.
665 moveaxis : Move axes of an array to new positions.
666 argsort : Return the indices that would sort an array.
667
668 Notes
669 -----
670 Use ``transpose(a, argsort(axes))`` to invert the transposition of tensors
671 when using the `axes` keyword argument.
672
673 Examples
674 --------
675 >>> import numpy as np
676 >>> a = np.array([[1, 2], [3, 4]])
677 >>> a
678 array([[1, 2],
679 [3, 4]])
680 >>> np.transpose(a)
681 array([[1, 3],
682 [2, 4]])
683
684 >>> a = np.array([1, 2, 3, 4])
685 >>> a
686 array([1, 2, 3, 4])
687 >>> np.transpose(a)
688 array([1, 2, 3, 4])
689
690 >>> a = np.ones((1, 2, 3))
691 >>> np.transpose(a, (1, 0, 2)).shape
692 (2, 1, 3)
693
694 >>> a = np.ones((2, 3, 4, 5))
695 >>> np.transpose(a).shape
696 (5, 4, 3, 2)
697
698 >>> a = np.arange(3*4*5).reshape((3, 4, 5))
699 >>> np.transpose(a, (-1, 0, -2)).shape
700 (5, 3, 4)
701
702 """
703 return _wrapfunc(a, 'transpose', axes)
704
705
706def _matrix_transpose_dispatcher(x):
707 return (x,)
708
709@array_function_dispatch(_matrix_transpose_dispatcher)
710def matrix_transpose(x, /):
711 """
712 Transposes a matrix (or a stack of matrices) ``x``.
713
714 This function is Array API compatible.
715
716 Parameters
717 ----------
718 x : array_like
719 Input array having shape (..., M, N) and whose two innermost
720 dimensions form ``MxN`` matrices.
721
722 Returns
723 -------
724 out : ndarray
725 An array containing the transpose for each matrix and having shape
726 (..., N, M).
727
728 See Also
729 --------
730 transpose : Generic transpose method.
731
732 Examples
733 --------
734 >>> import numpy as np
735 >>> np.matrix_transpose([[1, 2], [3, 4]])
736 array([[1, 3],
737 [2, 4]])
738
739 >>> np.matrix_transpose([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
740 array([[[1, 3],
741 [2, 4]],
742 [[5, 7],
743 [6, 8]]])
744
745 """
746 x = asanyarray(x)
747 if x.ndim < 2:
748 raise ValueError(
749 f"Input array must be at least 2-dimensional, but it is {x.ndim}"
750 )
751 return swapaxes(x, -1, -2)
752
753
754def _partition_dispatcher(a, kth, axis=None, kind=None, order=None):
755 return (a,)
756
757
758@array_function_dispatch(_partition_dispatcher)
759def partition(a, kth, axis=-1, kind='introselect', order=None):
760 """
761 Return a partitioned copy of an array.
762
763 Creates a copy of the array and partially sorts it in such a way that
764 the value of the element in k-th position is in the position it would be
765 in a sorted array. In the output array, all elements smaller than the k-th
766 element are located to the left of this element and all equal or greater
767 are located to its right. The ordering of the elements in the two
768 partitions on the either side of the k-th element in the output array is
769 undefined.
770
771 Parameters
772 ----------
773 a : array_like
774 Array to be sorted.
775 kth : int or sequence of ints
776 Element index to partition by. The k-th value of the element
777 will be in its final sorted position and all smaller elements
778 will be moved before it and all equal or greater elements behind
779 it. The order of all elements in the partitions is undefined. If
780 provided with a sequence of k-th it will partition all elements
781 indexed by k-th of them into their sorted position at once.
782
783 .. deprecated:: 1.22.0
784 Passing booleans as index is deprecated.
785 axis : int or None, optional
786 Axis along which to sort. If None, the array is flattened before
787 sorting. The default is -1, which sorts along the last axis.
788 kind : {'introselect'}, optional
789 Selection algorithm. Default is 'introselect'.
790 order : str or list of str, optional
791 When `a` is an array with fields defined, this argument
792 specifies which fields to compare first, second, etc. A single
793 field can be specified as a string. Not all fields need be
794 specified, but unspecified fields will still be used, in the
795 order in which they come up in the dtype, to break ties.
796
797 Returns
798 -------
799 partitioned_array : ndarray
800 Array of the same type and shape as `a`.
801
802 See Also
803 --------
804 ndarray.partition : Method to sort an array in-place.
805 argpartition : Indirect partition.
806 sort : Full sorting
807
808 Notes
809 -----
810 The various selection algorithms are characterized by their average
811 speed, worst case performance, work space size, and whether they are
812 stable. A stable sort keeps items with the same key in the same
813 relative order. The available algorithms have the following
814 properties:
815
816 ================= ======= ============= ============ =======
817 kind speed worst case work space stable
818 ================= ======= ============= ============ =======
819 'introselect' 1 O(n) 0 no
820 ================= ======= ============= ============ =======
821
822 All the partition algorithms make temporary copies of the data when
823 partitioning along any but the last axis. Consequently,
824 partitioning along the last axis is faster and uses less space than
825 partitioning along any other axis.
826
827 The sort order for complex numbers is lexicographic. If both the
828 real and imaginary parts are non-nan then the order is determined by
829 the real parts except when they are equal, in which case the order
830 is determined by the imaginary parts.
831
832 The sort order of ``np.nan`` is bigger than ``np.inf``.
833
834 Examples
835 --------
836 >>> import numpy as np
837 >>> a = np.array([7, 1, 7, 7, 1, 5, 7, 2, 3, 2, 6, 2, 3, 0])
838 >>> p = np.partition(a, 4)
839 >>> p
840 array([0, 1, 2, 1, 2, 5, 2, 3, 3, 6, 7, 7, 7, 7]) # may vary
841
842 ``p[4]`` is 2; all elements in ``p[:4]`` are less than or equal
843 to ``p[4]``, and all elements in ``p[5:]`` are greater than or
844 equal to ``p[4]``. The partition is::
845
846 [0, 1, 2, 1], [2], [5, 2, 3, 3, 6, 7, 7, 7, 7]
847
848 The next example shows the use of multiple values passed to `kth`.
849
850 >>> p2 = np.partition(a, (4, 8))
851 >>> p2
852 array([0, 1, 2, 1, 2, 3, 3, 2, 5, 6, 7, 7, 7, 7])
853
854 ``p2[4]`` is 2 and ``p2[8]`` is 5. All elements in ``p2[:4]``
855 are less than or equal to ``p2[4]``, all elements in ``p2[5:8]``
856 are greater than or equal to ``p2[4]`` and less than or equal to
857 ``p2[8]``, and all elements in ``p2[9:]`` are greater than or
858 equal to ``p2[8]``. The partition is::
859
860 [0, 1, 2, 1], [2], [3, 3, 2], [5], [6, 7, 7, 7, 7]
861 """
862 if axis is None:
863 # flatten returns (1, N) for np.matrix, so always use the last axis
864 a = asanyarray(a).flatten()
865 axis = -1
866 else:
867 a = asanyarray(a).copy(order="K")
868 a.partition(kth, axis=axis, kind=kind, order=order)
869 return a
870
871
872def _argpartition_dispatcher(a, kth, axis=None, kind=None, order=None):
873 return (a,)
874
875
876@array_function_dispatch(_argpartition_dispatcher)
877def argpartition(a, kth, axis=-1, kind='introselect', order=None):
878 """
879 Perform an indirect partition along the given axis using the
880 algorithm specified by the `kind` keyword. It returns an array of
881 indices of the same shape as `a` that index data along the given
882 axis in partitioned order.
883
884 Parameters
885 ----------
886 a : array_like
887 Array to sort.
888 kth : int or sequence of ints
889 Element index to partition by. The k-th element will be in its
890 final sorted position and all smaller elements will be moved
891 before it and all larger elements behind it. The order of all
892 elements in the partitions is undefined. If provided with a
893 sequence of k-th it will partition all of them into their sorted
894 position at once.
895
896 .. deprecated:: 1.22.0
897 Passing booleans as index is deprecated.
898 axis : int or None, optional
899 Axis along which to sort. The default is -1 (the last axis). If
900 None, the flattened array is used.
901 kind : {'introselect'}, optional
902 Selection algorithm. Default is 'introselect'
903 order : str or list of str, optional
904 When `a` is an array with fields defined, this argument
905 specifies which fields to compare first, second, etc. A single
906 field can be specified as a string, and not all fields need be
907 specified, but unspecified fields will still be used, in the
908 order in which they come up in the dtype, to break ties.
909
910 Returns
911 -------
912 index_array : ndarray, int
913 Array of indices that partition `a` along the specified axis.
914 If `a` is one-dimensional, ``a[index_array]`` yields a partitioned `a`.
915 More generally, ``np.take_along_axis(a, index_array, axis=axis)``
916 always yields the partitioned `a`, irrespective of dimensionality.
917
918 See Also
919 --------
920 partition : Describes partition algorithms used.
921 ndarray.partition : Inplace partition.
922 argsort : Full indirect sort.
923 take_along_axis : Apply ``index_array`` from argpartition
924 to an array as if by calling partition.
925
926 Notes
927 -----
928 The returned indices are not guaranteed to be sorted according to
929 the values. Furthermore, the default selection algorithm ``introselect``
930 is unstable, and hence the returned indices are not guaranteed
931 to be the earliest/latest occurrence of the element.
932
933 `argpartition` works for real/complex inputs with nan values,
934 see `partition` for notes on the enhanced sort order and
935 different selection algorithms.
936
937 Examples
938 --------
939 One dimensional array:
940
941 >>> import numpy as np
942 >>> x = np.array([3, 4, 2, 1])
943 >>> x[np.argpartition(x, 3)]
944 array([2, 1, 3, 4]) # may vary
945 >>> x[np.argpartition(x, (1, 3))]
946 array([1, 2, 3, 4]) # may vary
947
948 >>> x = [3, 4, 2, 1]
949 >>> np.array(x)[np.argpartition(x, 3)]
950 array([2, 1, 3, 4]) # may vary
951
952 Multi-dimensional array:
953
954 >>> x = np.array([[3, 4, 2], [1, 3, 1]])
955 >>> index_array = np.argpartition(x, kth=1, axis=-1)
956 >>> # below is the same as np.partition(x, kth=1)
957 >>> np.take_along_axis(x, index_array, axis=-1)
958 array([[2, 3, 4],
959 [1, 1, 3]])
960
961 """
962 return _wrapfunc(a, 'argpartition', kth, axis=axis, kind=kind, order=order)
963
964
965def _sort_dispatcher(a, axis=None, kind=None, order=None, *, stable=None):
966 return (a,)
967
968
969@array_function_dispatch(_sort_dispatcher)
970def sort(a, axis=-1, kind=None, order=None, *, stable=None):
971 """
972 Return a sorted copy of an array.
973
974 Parameters
975 ----------
976 a : array_like
977 Array to be sorted.
978 axis : int or None, optional
979 Axis along which to sort. If None, the array is flattened before
980 sorting. The default is -1, which sorts along the last axis.
981 kind : {'quicksort', 'mergesort', 'heapsort', 'stable'}, optional
982 Sorting algorithm. The default is 'quicksort'. Note that both 'stable'
983 and 'mergesort' use timsort or radix sort under the covers and,
984 in general, the actual implementation will vary with data type.
985 The 'mergesort' option is retained for backwards compatibility.
986 order : str or list of str, optional
987 When `a` is an array with fields defined, this argument specifies
988 which fields to compare first, second, etc. A single field can
989 be specified as a string, and not all fields need be specified,
990 but unspecified fields will still be used, in the order in which
991 they come up in the dtype, to break ties.
992 stable : bool, optional
993 Sort stability. If ``True``, the returned array will maintain
994 the relative order of ``a`` values which compare as equal.
995 If ``False`` or ``None``, this is not guaranteed. Internally,
996 this option selects ``kind='stable'``. Default: ``None``.
997
998 .. versionadded:: 2.0.0
999
1000 Returns
1001 -------
1002 sorted_array : ndarray
1003 Array of the same type and shape as `a`.
1004
1005 See Also
1006 --------
1007 ndarray.sort : Method to sort an array in-place.
1008 argsort : Indirect sort.
1009 lexsort : Indirect stable sort on multiple keys.
1010 searchsorted : Find elements in a sorted array.
1011 partition : Partial sort.
1012
1013 Notes
1014 -----
1015 The various sorting algorithms are characterized by their average speed,
1016 worst case performance, work space size, and whether they are stable. A
1017 stable sort keeps items with the same key in the same relative
1018 order. The four algorithms implemented in NumPy have the following
1019 properties:
1020
1021 =========== ======= ============= ============ ========
1022 kind speed worst case work space stable
1023 =========== ======= ============= ============ ========
1024 'quicksort' 1 O(n^2) 0 no
1025 'heapsort' 3 O(n*log(n)) 0 no
1026 'mergesort' 2 O(n*log(n)) ~n/2 yes
1027 'timsort' 2 O(n*log(n)) ~n/2 yes
1028 =========== ======= ============= ============ ========
1029
1030 .. note:: The datatype determines which of 'mergesort' or 'timsort'
1031 is actually used, even if 'mergesort' is specified. User selection
1032 at a finer scale is not currently available.
1033
1034 For performance, ``sort`` makes a temporary copy if needed to make the data
1035 `contiguous <https://numpy.org/doc/stable/glossary.html#term-contiguous>`_
1036 in memory along the sort axis. For even better performance and reduced
1037 memory consumption, ensure that the array is already contiguous along the
1038 sort axis.
1039
1040 The sort order for complex numbers is lexicographic. If both the real
1041 and imaginary parts are non-nan then the order is determined by the
1042 real parts except when they are equal, in which case the order is
1043 determined by the imaginary parts.
1044
1045 Previous to numpy 1.4.0 sorting real and complex arrays containing nan
1046 values led to undefined behaviour. In numpy versions >= 1.4.0 nan
1047 values are sorted to the end. The extended sort order is:
1048
1049 * Real: [R, nan]
1050 * Complex: [R + Rj, R + nanj, nan + Rj, nan + nanj]
1051
1052 where R is a non-nan real value. Complex values with the same nan
1053 placements are sorted according to the non-nan part if it exists.
1054 Non-nan values are sorted as before.
1055
1056 quicksort has been changed to:
1057 `introsort <https://en.wikipedia.org/wiki/Introsort>`_.
1058 When sorting does not make enough progress it switches to
1059 `heapsort <https://en.wikipedia.org/wiki/Heapsort>`_.
1060 This implementation makes quicksort O(n*log(n)) in the worst case.
1061
1062 'stable' automatically chooses the best stable sorting algorithm
1063 for the data type being sorted.
1064 It, along with 'mergesort' is currently mapped to
1065 `timsort <https://en.wikipedia.org/wiki/Timsort>`_
1066 or `radix sort <https://en.wikipedia.org/wiki/Radix_sort>`_
1067 depending on the data type.
1068 API forward compatibility currently limits the
1069 ability to select the implementation and it is hardwired for the different
1070 data types.
1071
1072 Timsort is added for better performance on already or nearly
1073 sorted data. On random data timsort is almost identical to
1074 mergesort. It is now used for stable sort while quicksort is still the
1075 default sort if none is chosen. For timsort details, refer to
1076 `CPython listsort.txt
1077 <https://github.com/python/cpython/blob/3.7/Objects/listsort.txt>`_
1078 'mergesort' and 'stable' are mapped to radix sort for integer data types.
1079 Radix sort is an O(n) sort instead of O(n log n).
1080
1081 NaT now sorts to the end of arrays for consistency with NaN.
1082
1083 Examples
1084 --------
1085 >>> import numpy as np
1086 >>> a = np.array([[1,4],[3,1]])
1087 >>> np.sort(a) # sort along the last axis
1088 array([[1, 4],
1089 [1, 3]])
1090 >>> np.sort(a, axis=None) # sort the flattened array
1091 array([1, 1, 3, 4])
1092 >>> np.sort(a, axis=0) # sort along the first axis
1093 array([[1, 1],
1094 [3, 4]])
1095
1096 Use the `order` keyword to specify a field to use when sorting a
1097 structured array:
1098
1099 >>> dtype = [('name', 'S10'), ('height', float), ('age', int)]
1100 >>> values = [('Arthur', 1.8, 41), ('Lancelot', 1.9, 38),
1101 ... ('Galahad', 1.7, 38)]
1102 >>> a = np.array(values, dtype=dtype) # create a structured array
1103 >>> np.sort(a, order='height') # doctest: +SKIP
1104 array([('Galahad', 1.7, 38), ('Arthur', 1.8, 41),
1105 ('Lancelot', 1.8999999999999999, 38)],
1106 dtype=[('name', '|S10'), ('height', '<f8'), ('age', '<i4')])
1107
1108 Sort by age, then height if ages are equal:
1109
1110 >>> np.sort(a, order=['age', 'height']) # doctest: +SKIP
1111 array([('Galahad', 1.7, 38), ('Lancelot', 1.8999999999999999, 38),
1112 ('Arthur', 1.8, 41)],
1113 dtype=[('name', '|S10'), ('height', '<f8'), ('age', '<i4')])
1114
1115 """
1116 if axis is None:
1117 # flatten returns (1, N) for np.matrix, so always use the last axis
1118 a = asanyarray(a).flatten()
1119 axis = -1
1120 else:
1121 a = asanyarray(a).copy(order="K")
1122 a.sort(axis=axis, kind=kind, order=order, stable=stable)
1123 return a
1124
1125
1126def _argsort_dispatcher(a, axis=None, kind=None, order=None, *, stable=None):
1127 return (a,)
1128
1129
1130@array_function_dispatch(_argsort_dispatcher)
1131def argsort(a, axis=-1, kind=None, order=None, *, stable=None):
1132 """
1133 Returns the indices that would sort an array.
1134
1135 Perform an indirect sort along the given axis using the algorithm specified
1136 by the `kind` keyword. It returns an array of indices of the same shape as
1137 `a` that index data along the given axis in sorted order.
1138
1139 Parameters
1140 ----------
1141 a : array_like
1142 Array to sort.
1143 axis : int or None, optional
1144 Axis along which to sort. The default is -1 (the last axis). If None,
1145 the flattened array is used.
1146 kind : {'quicksort', 'mergesort', 'heapsort', 'stable'}, optional
1147 Sorting algorithm. The default is 'quicksort'. Note that both 'stable'
1148 and 'mergesort' use timsort under the covers and, in general, the
1149 actual implementation will vary with data type. The 'mergesort' option
1150 is retained for backwards compatibility.
1151 order : str or list of str, optional
1152 When `a` is an array with fields defined, this argument specifies
1153 which fields to compare first, second, etc. A single field can
1154 be specified as a string, and not all fields need be specified,
1155 but unspecified fields will still be used, in the order in which
1156 they come up in the dtype, to break ties.
1157 stable : bool, optional
1158 Sort stability. If ``True``, the returned array will maintain
1159 the relative order of ``a`` values which compare as equal.
1160 If ``False`` or ``None``, this is not guaranteed. Internally,
1161 this option selects ``kind='stable'``. Default: ``None``.
1162
1163 .. versionadded:: 2.0.0
1164
1165 Returns
1166 -------
1167 index_array : ndarray, int
1168 Array of indices that sort `a` along the specified `axis`.
1169 If `a` is one-dimensional, ``a[index_array]`` yields a sorted `a`.
1170 More generally, ``np.take_along_axis(a, index_array, axis=axis)``
1171 always yields the sorted `a`, irrespective of dimensionality.
1172
1173 See Also
1174 --------
1175 sort : Describes sorting algorithms used.
1176 lexsort : Indirect stable sort with multiple keys.
1177 ndarray.sort : Inplace sort.
1178 argpartition : Indirect partial sort.
1179 take_along_axis : Apply ``index_array`` from argsort
1180 to an array as if by calling sort.
1181
1182 Notes
1183 -----
1184 See `sort` for notes on the different sorting algorithms.
1185
1186 As of NumPy 1.4.0 `argsort` works with real/complex arrays containing
1187 nan values. The enhanced sort order is documented in `sort`.
1188
1189 Examples
1190 --------
1191 One dimensional array:
1192
1193 >>> import numpy as np
1194 >>> x = np.array([3, 1, 2])
1195 >>> np.argsort(x)
1196 array([1, 2, 0])
1197
1198 Two-dimensional array:
1199
1200 >>> x = np.array([[0, 3], [2, 2]])
1201 >>> x
1202 array([[0, 3],
1203 [2, 2]])
1204
1205 >>> ind = np.argsort(x, axis=0) # sorts along first axis (down)
1206 >>> ind
1207 array([[0, 1],
1208 [1, 0]])
1209 >>> np.take_along_axis(x, ind, axis=0) # same as np.sort(x, axis=0)
1210 array([[0, 2],
1211 [2, 3]])
1212
1213 >>> ind = np.argsort(x, axis=1) # sorts along last axis (across)
1214 >>> ind
1215 array([[0, 1],
1216 [0, 1]])
1217 >>> np.take_along_axis(x, ind, axis=1) # same as np.sort(x, axis=1)
1218 array([[0, 3],
1219 [2, 2]])
1220
1221 Indices of the sorted elements of a N-dimensional array:
1222
1223 >>> ind = np.unravel_index(np.argsort(x, axis=None), x.shape)
1224 >>> ind
1225 (array([0, 1, 1, 0]), array([0, 0, 1, 1]))
1226 >>> x[ind] # same as np.sort(x, axis=None)
1227 array([0, 2, 2, 3])
1228
1229 Sorting with keys:
1230
1231 >>> x = np.array([(1, 0), (0, 1)], dtype=[('x', '<i4'), ('y', '<i4')])
1232 >>> x
1233 array([(1, 0), (0, 1)],
1234 dtype=[('x', '<i4'), ('y', '<i4')])
1235
1236 >>> np.argsort(x, order=('x','y'))
1237 array([1, 0])
1238
1239 >>> np.argsort(x, order=('y','x'))
1240 array([0, 1])
1241
1242 """
1243 return _wrapfunc(
1244 a, 'argsort', axis=axis, kind=kind, order=order, stable=stable
1245 )
1246
1247def _argmax_dispatcher(a, axis=None, out=None, *, keepdims=np._NoValue):
1248 return (a, out)
1249
1250
1251@array_function_dispatch(_argmax_dispatcher)
1252def argmax(a, axis=None, out=None, *, keepdims=np._NoValue):
1253 """
1254 Returns the indices of the maximum values along an axis.
1255
1256 Parameters
1257 ----------
1258 a : array_like
1259 Input array.
1260 axis : int, optional
1261 By default, the index is into the flattened array, otherwise
1262 along the specified axis.
1263 out : array, optional
1264 If provided, the result will be inserted into this array. It should
1265 be of the appropriate shape and dtype.
1266 keepdims : bool, optional
1267 If this is set to True, the axes which are reduced are left
1268 in the result as dimensions with size one. With this option,
1269 the result will broadcast correctly against the array.
1270
1271 .. versionadded:: 1.22.0
1272
1273 Returns
1274 -------
1275 index_array : ndarray of ints
1276 Array of indices into the array. It has the same shape as ``a.shape``
1277 with the dimension along `axis` removed. If `keepdims` is set to True,
1278 then the size of `axis` will be 1 with the resulting array having same
1279 shape as ``a.shape``.
1280
1281 See Also
1282 --------
1283 ndarray.argmax, argmin
1284 amax : The maximum value along a given axis.
1285 unravel_index : Convert a flat index into an index tuple.
1286 take_along_axis : Apply ``np.expand_dims(index_array, axis)``
1287 from argmax to an array as if by calling max.
1288
1289 Notes
1290 -----
1291 In case of multiple occurrences of the maximum values, the indices
1292 corresponding to the first occurrence are returned.
1293
1294 Examples
1295 --------
1296 >>> import numpy as np
1297 >>> a = np.arange(6).reshape(2,3) + 10
1298 >>> a
1299 array([[10, 11, 12],
1300 [13, 14, 15]])
1301 >>> np.argmax(a)
1302 5
1303 >>> np.argmax(a, axis=0)
1304 array([1, 1, 1])
1305 >>> np.argmax(a, axis=1)
1306 array([2, 2])
1307
1308 Indexes of the maximal elements of a N-dimensional array:
1309
1310 >>> ind = np.unravel_index(np.argmax(a, axis=None), a.shape)
1311 >>> ind
1312 (1, 2)
1313 >>> a[ind]
1314 15
1315
1316 >>> b = np.arange(6)
1317 >>> b[1] = 5
1318 >>> b
1319 array([0, 5, 2, 3, 4, 5])
1320 >>> np.argmax(b) # Only the first occurrence is returned.
1321 1
1322
1323 >>> x = np.array([[4,2,3], [1,0,3]])
1324 >>> index_array = np.argmax(x, axis=-1)
1325 >>> # Same as np.amax(x, axis=-1, keepdims=True)
1326 >>> np.take_along_axis(x, np.expand_dims(index_array, axis=-1), axis=-1)
1327 array([[4],
1328 [3]])
1329 >>> # Same as np.amax(x, axis=-1)
1330 >>> np.take_along_axis(x, np.expand_dims(index_array, axis=-1),
1331 ... axis=-1).squeeze(axis=-1)
1332 array([4, 3])
1333
1334 Setting `keepdims` to `True`,
1335
1336 >>> x = np.arange(24).reshape((2, 3, 4))
1337 >>> res = np.argmax(x, axis=1, keepdims=True)
1338 >>> res.shape
1339 (2, 1, 4)
1340 """
1341 kwds = {'keepdims': keepdims} if keepdims is not np._NoValue else {}
1342 return _wrapfunc(a, 'argmax', axis=axis, out=out, **kwds)
1343
1344
1345def _argmin_dispatcher(a, axis=None, out=None, *, keepdims=np._NoValue):
1346 return (a, out)
1347
1348
1349@array_function_dispatch(_argmin_dispatcher)
1350def argmin(a, axis=None, out=None, *, keepdims=np._NoValue):
1351 """
1352 Returns the indices of the minimum values along an axis.
1353
1354 Parameters
1355 ----------
1356 a : array_like
1357 Input array.
1358 axis : int, optional
1359 By default, the index is into the flattened array, otherwise
1360 along the specified axis.
1361 out : array, optional
1362 If provided, the result will be inserted into this array. It should
1363 be of the appropriate shape and dtype.
1364 keepdims : bool, optional
1365 If this is set to True, the axes which are reduced are left
1366 in the result as dimensions with size one. With this option,
1367 the result will broadcast correctly against the array.
1368
1369 .. versionadded:: 1.22.0
1370
1371 Returns
1372 -------
1373 index_array : ndarray of ints
1374 Array of indices into the array. It has the same shape as `a.shape`
1375 with the dimension along `axis` removed. If `keepdims` is set to True,
1376 then the size of `axis` will be 1 with the resulting array having same
1377 shape as `a.shape`.
1378
1379 See Also
1380 --------
1381 ndarray.argmin, argmax
1382 amin : The minimum value along a given axis.
1383 unravel_index : Convert a flat index into an index tuple.
1384 take_along_axis : Apply ``np.expand_dims(index_array, axis)``
1385 from argmin to an array as if by calling min.
1386
1387 Notes
1388 -----
1389 In case of multiple occurrences of the minimum values, the indices
1390 corresponding to the first occurrence are returned.
1391
1392 Examples
1393 --------
1394 >>> import numpy as np
1395 >>> a = np.arange(6).reshape(2,3) + 10
1396 >>> a
1397 array([[10, 11, 12],
1398 [13, 14, 15]])
1399 >>> np.argmin(a)
1400 0
1401 >>> np.argmin(a, axis=0)
1402 array([0, 0, 0])
1403 >>> np.argmin(a, axis=1)
1404 array([0, 0])
1405
1406 Indices of the minimum elements of a N-dimensional array:
1407
1408 >>> ind = np.unravel_index(np.argmin(a, axis=None), a.shape)
1409 >>> ind
1410 (0, 0)
1411 >>> a[ind]
1412 10
1413
1414 >>> b = np.arange(6) + 10
1415 >>> b[4] = 10
1416 >>> b
1417 array([10, 11, 12, 13, 10, 15])
1418 >>> np.argmin(b) # Only the first occurrence is returned.
1419 0
1420
1421 >>> x = np.array([[4,2,3], [1,0,3]])
1422 >>> index_array = np.argmin(x, axis=-1)
1423 >>> # Same as np.amin(x, axis=-1, keepdims=True)
1424 >>> np.take_along_axis(x, np.expand_dims(index_array, axis=-1), axis=-1)
1425 array([[2],
1426 [0]])
1427 >>> # Same as np.amax(x, axis=-1)
1428 >>> np.take_along_axis(x, np.expand_dims(index_array, axis=-1),
1429 ... axis=-1).squeeze(axis=-1)
1430 array([2, 0])
1431
1432 Setting `keepdims` to `True`,
1433
1434 >>> x = np.arange(24).reshape((2, 3, 4))
1435 >>> res = np.argmin(x, axis=1, keepdims=True)
1436 >>> res.shape
1437 (2, 1, 4)
1438 """
1439 kwds = {'keepdims': keepdims} if keepdims is not np._NoValue else {}
1440 return _wrapfunc(a, 'argmin', axis=axis, out=out, **kwds)
1441
1442
1443def _searchsorted_dispatcher(a, v, side=None, sorter=None):
1444 return (a, v, sorter)
1445
1446
1447@array_function_dispatch(_searchsorted_dispatcher)
1448def searchsorted(a, v, side='left', sorter=None):
1449 """
1450 Find indices where elements should be inserted to maintain order.
1451
1452 Find the indices into a sorted array `a` such that, if the
1453 corresponding elements in `v` were inserted before the indices, the
1454 order of `a` would be preserved.
1455
1456 Assuming that `a` is sorted:
1457
1458 ====== ============================
1459 `side` returned index `i` satisfies
1460 ====== ============================
1461 left ``a[i-1] < v <= a[i]``
1462 right ``a[i-1] <= v < a[i]``
1463 ====== ============================
1464
1465 Parameters
1466 ----------
1467 a : 1-D array_like
1468 Input array. If `sorter` is None, then it must be sorted in
1469 ascending order, otherwise `sorter` must be an array of indices
1470 that sort it.
1471 v : array_like
1472 Values to insert into `a`.
1473 side : {'left', 'right'}, optional
1474 If 'left', the index of the first suitable location found is given.
1475 If 'right', return the last such index. If there is no suitable
1476 index, return either 0 or N (where N is the length of `a`).
1477 sorter : 1-D array_like, optional
1478 Optional array of integer indices that sort array a into ascending
1479 order. They are typically the result of argsort.
1480
1481 Returns
1482 -------
1483 indices : int or array of ints
1484 Array of insertion points with the same shape as `v`,
1485 or an integer if `v` is a scalar.
1486
1487 See Also
1488 --------
1489 sort : Return a sorted copy of an array.
1490 histogram : Produce histogram from 1-D data.
1491
1492 Notes
1493 -----
1494 Binary search is used to find the required insertion points.
1495
1496 As of NumPy 1.4.0 `searchsorted` works with real/complex arrays containing
1497 `nan` values. The enhanced sort order is documented in `sort`.
1498
1499 This function uses the same algorithm as the builtin python
1500 `bisect.bisect_left` (``side='left'``) and `bisect.bisect_right`
1501 (``side='right'``) functions, which is also vectorized
1502 in the `v` argument.
1503
1504 Examples
1505 --------
1506 >>> import numpy as np
1507 >>> np.searchsorted([11,12,13,14,15], 13)
1508 2
1509 >>> np.searchsorted([11,12,13,14,15], 13, side='right')
1510 3
1511 >>> np.searchsorted([11,12,13,14,15], [-10, 20, 12, 13])
1512 array([0, 5, 1, 2])
1513
1514 When `sorter` is used, the returned indices refer to the sorted
1515 array of `a` and not `a` itself:
1516
1517 >>> a = np.array([40, 10, 20, 30])
1518 >>> sorter = np.argsort(a)
1519 >>> sorter
1520 array([1, 2, 3, 0]) # Indices that would sort the array 'a'
1521 >>> result = np.searchsorted(a, 25, sorter=sorter)
1522 >>> result
1523 2
1524 >>> a[sorter[result]]
1525 30 # The element at index 2 of the sorted array is 30.
1526 """
1527 return _wrapfunc(a, 'searchsorted', v, side=side, sorter=sorter)
1528
1529
1530def _resize_dispatcher(a, new_shape):
1531 return (a,)
1532
1533
1534@array_function_dispatch(_resize_dispatcher)
1535def resize(a, new_shape):
1536 """
1537 Return a new array with the specified shape.
1538
1539 If the new array is larger than the original array, then the new
1540 array is filled with repeated copies of `a`. Note that this behavior
1541 is different from a.resize(new_shape) which fills with zeros instead
1542 of repeated copies of `a`.
1543
1544 Parameters
1545 ----------
1546 a : array_like
1547 Array to be resized.
1548
1549 new_shape : int or tuple of int
1550 Shape of resized array.
1551
1552 Returns
1553 -------
1554 reshaped_array : ndarray
1555 The new array is formed from the data in the old array, repeated
1556 if necessary to fill out the required number of elements. The
1557 data are repeated iterating over the array in C-order.
1558
1559 See Also
1560 --------
1561 numpy.reshape : Reshape an array without changing the total size.
1562 numpy.pad : Enlarge and pad an array.
1563 numpy.repeat : Repeat elements of an array.
1564 ndarray.resize : resize an array in-place.
1565
1566 Notes
1567 -----
1568 When the total size of the array does not change `~numpy.reshape` should
1569 be used. In most other cases either indexing (to reduce the size)
1570 or padding (to increase the size) may be a more appropriate solution.
1571
1572 Warning: This functionality does **not** consider axes separately,
1573 i.e. it does not apply interpolation/extrapolation.
1574 It fills the return array with the required number of elements, iterating
1575 over `a` in C-order, disregarding axes (and cycling back from the start if
1576 the new shape is larger). This functionality is therefore not suitable to
1577 resize images, or data where each axis represents a separate and distinct
1578 entity.
1579
1580 Examples
1581 --------
1582 >>> import numpy as np
1583 >>> a = np.array([[0,1],[2,3]])
1584 >>> np.resize(a,(2,3))
1585 array([[0, 1, 2],
1586 [3, 0, 1]])
1587 >>> np.resize(a,(1,4))
1588 array([[0, 1, 2, 3]])
1589 >>> np.resize(a,(2,4))
1590 array([[0, 1, 2, 3],
1591 [0, 1, 2, 3]])
1592
1593 """
1594 if isinstance(new_shape, (int, nt.integer)):
1595 new_shape = (new_shape,)
1596
1597 a = ravel(a)
1598
1599 new_size = 1
1600 for dim_length in new_shape:
1601 new_size *= dim_length
1602 if dim_length < 0:
1603 raise ValueError(
1604 'all elements of `new_shape` must be non-negative'
1605 )
1606
1607 if a.size == 0 or new_size == 0:
1608 # First case must zero fill. The second would have repeats == 0.
1609 return np.zeros_like(a, shape=new_shape)
1610
1611 repeats = -(-new_size // a.size) # ceil division
1612 a = concatenate((a,) * repeats)[:new_size]
1613
1614 return reshape(a, new_shape)
1615
1616
1617def _squeeze_dispatcher(a, axis=None):
1618 return (a,)
1619
1620
1621@array_function_dispatch(_squeeze_dispatcher)
1622def squeeze(a, axis=None):
1623 """
1624 Remove axes of length one from `a`.
1625
1626 Parameters
1627 ----------
1628 a : array_like
1629 Input data.
1630 axis : None or int or tuple of ints, optional
1631 Selects a subset of the entries of length one in the
1632 shape. If an axis is selected with shape entry greater than
1633 one, an error is raised.
1634
1635 Returns
1636 -------
1637 squeezed : ndarray
1638 The input array, but with all or a subset of the
1639 dimensions of length 1 removed. This is always `a` itself
1640 or a view into `a`. Note that if all axes are squeezed,
1641 the result is a 0d array and not a scalar.
1642
1643 Raises
1644 ------
1645 ValueError
1646 If `axis` is not None, and an axis being squeezed is not of length 1
1647
1648 See Also
1649 --------
1650 expand_dims : The inverse operation, adding entries of length one
1651 reshape : Insert, remove, and combine dimensions, and resize existing ones
1652
1653 Examples
1654 --------
1655 >>> import numpy as np
1656 >>> x = np.array([[[0], [1], [2]]])
1657 >>> x.shape
1658 (1, 3, 1)
1659 >>> np.squeeze(x).shape
1660 (3,)
1661 >>> np.squeeze(x, axis=0).shape
1662 (3, 1)
1663 >>> np.squeeze(x, axis=1).shape
1664 Traceback (most recent call last):
1665 ...
1666 ValueError: cannot select an axis to squeeze out which has size
1667 not equal to one
1668 >>> np.squeeze(x, axis=2).shape
1669 (1, 3)
1670 >>> x = np.array([[1234]])
1671 >>> x.shape
1672 (1, 1)
1673 >>> np.squeeze(x)
1674 array(1234) # 0d array
1675 >>> np.squeeze(x).shape
1676 ()
1677 >>> np.squeeze(x)[()]
1678 1234
1679
1680 """
1681 try:
1682 squeeze = a.squeeze
1683 except AttributeError:
1684 return _wrapit(a, 'squeeze', axis=axis)
1685 if axis is None:
1686 return squeeze()
1687 else:
1688 return squeeze(axis=axis)
1689
1690
1691def _diagonal_dispatcher(a, offset=None, axis1=None, axis2=None):
1692 return (a,)
1693
1694
1695@array_function_dispatch(_diagonal_dispatcher)
1696def diagonal(a, offset=0, axis1=0, axis2=1):
1697 """
1698 Return specified diagonals.
1699
1700 If `a` is 2-D, returns the diagonal of `a` with the given offset,
1701 i.e., the collection of elements of the form ``a[i, i+offset]``. If
1702 `a` has more than two dimensions, then the axes specified by `axis1`
1703 and `axis2` are used to determine the 2-D sub-array whose diagonal is
1704 returned. The shape of the resulting array can be determined by
1705 removing `axis1` and `axis2` and appending an index to the right equal
1706 to the size of the resulting diagonals.
1707
1708 In versions of NumPy prior to 1.7, this function always returned a new,
1709 independent array containing a copy of the values in the diagonal.
1710
1711 In NumPy 1.7 and 1.8, it continues to return a copy of the diagonal,
1712 but depending on this fact is deprecated. Writing to the resulting
1713 array continues to work as it used to, but a FutureWarning is issued.
1714
1715 Starting in NumPy 1.9 it returns a read-only view on the original array.
1716 Attempting to write to the resulting array will produce an error.
1717
1718 In some future release, it will return a read/write view and writing to
1719 the returned array will alter your original array. The returned array
1720 will have the same type as the input array.
1721
1722 If you don't write to the array returned by this function, then you can
1723 just ignore all of the above.
1724
1725 If you depend on the current behavior, then we suggest copying the
1726 returned array explicitly, i.e., use ``np.diagonal(a).copy()`` instead
1727 of just ``np.diagonal(a)``. This will work with both past and future
1728 versions of NumPy.
1729
1730 Parameters
1731 ----------
1732 a : array_like
1733 Array from which the diagonals are taken.
1734 offset : int, optional
1735 Offset of the diagonal from the main diagonal. Can be positive or
1736 negative. Defaults to main diagonal (0).
1737 axis1 : int, optional
1738 Axis to be used as the first axis of the 2-D sub-arrays from which
1739 the diagonals should be taken. Defaults to first axis (0).
1740 axis2 : int, optional
1741 Axis to be used as the second axis of the 2-D sub-arrays from
1742 which the diagonals should be taken. Defaults to second axis (1).
1743
1744 Returns
1745 -------
1746 array_of_diagonals : ndarray
1747 If `a` is 2-D, then a 1-D array containing the diagonal and of the
1748 same type as `a` is returned unless `a` is a `matrix`, in which case
1749 a 1-D array rather than a (2-D) `matrix` is returned in order to
1750 maintain backward compatibility.
1751
1752 If ``a.ndim > 2``, then the dimensions specified by `axis1` and `axis2`
1753 are removed, and a new axis inserted at the end corresponding to the
1754 diagonal.
1755
1756 Raises
1757 ------
1758 ValueError
1759 If the dimension of `a` is less than 2.
1760
1761 See Also
1762 --------
1763 diag : MATLAB work-a-like for 1-D and 2-D arrays.
1764 diagflat : Create diagonal arrays.
1765 trace : Sum along diagonals.
1766
1767 Examples
1768 --------
1769 >>> import numpy as np
1770 >>> a = np.arange(4).reshape(2,2)
1771 >>> a
1772 array([[0, 1],
1773 [2, 3]])
1774 >>> a.diagonal()
1775 array([0, 3])
1776 >>> a.diagonal(1)
1777 array([1])
1778
1779 A 3-D example:
1780
1781 >>> a = np.arange(8).reshape(2,2,2); a
1782 array([[[0, 1],
1783 [2, 3]],
1784 [[4, 5],
1785 [6, 7]]])
1786 >>> a.diagonal(0, # Main diagonals of two arrays created by skipping
1787 ... 0, # across the outer(left)-most axis last and
1788 ... 1) # the "middle" (row) axis first.
1789 array([[0, 6],
1790 [1, 7]])
1791
1792 The sub-arrays whose main diagonals we just obtained; note that each
1793 corresponds to fixing the right-most (column) axis, and that the
1794 diagonals are "packed" in rows.
1795
1796 >>> a[:,:,0] # main diagonal is [0 6]
1797 array([[0, 2],
1798 [4, 6]])
1799 >>> a[:,:,1] # main diagonal is [1 7]
1800 array([[1, 3],
1801 [5, 7]])
1802
1803 The anti-diagonal can be obtained by reversing the order of elements
1804 using either `numpy.flipud` or `numpy.fliplr`.
1805
1806 >>> a = np.arange(9).reshape(3, 3)
1807 >>> a
1808 array([[0, 1, 2],
1809 [3, 4, 5],
1810 [6, 7, 8]])
1811 >>> np.fliplr(a).diagonal() # Horizontal flip
1812 array([2, 4, 6])
1813 >>> np.flipud(a).diagonal() # Vertical flip
1814 array([6, 4, 2])
1815
1816 Note that the order in which the diagonal is retrieved varies depending
1817 on the flip function.
1818 """
1819 if isinstance(a, np.matrix):
1820 # Make diagonal of matrix 1-D to preserve backward compatibility.
1821 return asarray(a).diagonal(offset=offset, axis1=axis1, axis2=axis2)
1822 else:
1823 return asanyarray(a).diagonal(offset=offset, axis1=axis1, axis2=axis2)
1824
1825
1826def _trace_dispatcher(
1827 a, offset=None, axis1=None, axis2=None, dtype=None, out=None):
1828 return (a, out)
1829
1830
1831@array_function_dispatch(_trace_dispatcher)
1832def trace(a, offset=0, axis1=0, axis2=1, dtype=None, out=None):
1833 """
1834 Return the sum along diagonals of the array.
1835
1836 If `a` is 2-D, the sum along its diagonal with the given offset
1837 is returned, i.e., the sum of elements ``a[i,i+offset]`` for all i.
1838
1839 If `a` has more than two dimensions, then the axes specified by axis1 and
1840 axis2 are used to determine the 2-D sub-arrays whose traces are returned.
1841 The shape of the resulting array is the same as that of `a` with `axis1`
1842 and `axis2` removed.
1843
1844 Parameters
1845 ----------
1846 a : array_like
1847 Input array, from which the diagonals are taken.
1848 offset : int, optional
1849 Offset of the diagonal from the main diagonal. Can be both positive
1850 and negative. Defaults to 0.
1851 axis1, axis2 : int, optional
1852 Axes to be used as the first and second axis of the 2-D sub-arrays
1853 from which the diagonals should be taken. Defaults are the first two
1854 axes of `a`.
1855 dtype : dtype, optional
1856 Determines the data-type of the returned array and of the accumulator
1857 where the elements are summed. If dtype has the value None and `a` is
1858 of integer type of precision less than the default integer
1859 precision, then the default integer precision is used. Otherwise,
1860 the precision is the same as that of `a`.
1861 out : ndarray, optional
1862 Array into which the output is placed. Its type is preserved and
1863 it must be of the right shape to hold the output.
1864
1865 Returns
1866 -------
1867 sum_along_diagonals : ndarray
1868 If `a` is 2-D, the sum along the diagonal is returned. If `a` has
1869 larger dimensions, then an array of sums along diagonals is returned.
1870
1871 See Also
1872 --------
1873 diag, diagonal, diagflat
1874
1875 Examples
1876 --------
1877 >>> import numpy as np
1878 >>> np.trace(np.eye(3))
1879 3.0
1880 >>> a = np.arange(8).reshape((2,2,2))
1881 >>> np.trace(a)
1882 array([6, 8])
1883
1884 >>> a = np.arange(24).reshape((2,2,2,3))
1885 >>> np.trace(a).shape
1886 (2, 3)
1887
1888 """
1889 if isinstance(a, np.matrix):
1890 # Get trace of matrix via an array to preserve backward compatibility.
1891 return asarray(a).trace(
1892 offset=offset, axis1=axis1, axis2=axis2, dtype=dtype, out=out
1893 )
1894 else:
1895 return asanyarray(a).trace(
1896 offset=offset, axis1=axis1, axis2=axis2, dtype=dtype, out=out
1897 )
1898
1899
1900def _ravel_dispatcher(a, order=None):
1901 return (a,)
1902
1903
1904@array_function_dispatch(_ravel_dispatcher)
1905def ravel(a, order='C'):
1906 """Return a contiguous flattened array.
1907
1908 A 1-D array, containing the elements of the input, is returned. A copy is
1909 made only if needed.
1910
1911 As of NumPy 1.10, the returned array will have the same type as the input
1912 array. (for example, a masked array will be returned for a masked array
1913 input)
1914
1915 Parameters
1916 ----------
1917 a : array_like
1918 Input array. The elements in `a` are read in the order specified by
1919 `order`, and packed as a 1-D array.
1920 order : {'C','F', 'A', 'K'}, optional
1921
1922 The elements of `a` are read using this index order. 'C' means
1923 to index the elements in row-major, C-style order,
1924 with the last axis index changing fastest, back to the first
1925 axis index changing slowest. 'F' means to index the elements
1926 in column-major, Fortran-style order, with the
1927 first index changing fastest, and the last index changing
1928 slowest. Note that the 'C' and 'F' options take no account of
1929 the memory layout of the underlying array, and only refer to
1930 the order of axis indexing. 'A' means to read the elements in
1931 Fortran-like index order if `a` is Fortran *contiguous* in
1932 memory, C-like order otherwise. 'K' means to read the
1933 elements in the order they occur in memory, except for
1934 reversing the data when strides are negative. By default, 'C'
1935 index order is used.
1936
1937 Returns
1938 -------
1939 y : array_like
1940 y is a contiguous 1-D array of the same subtype as `a`,
1941 with shape ``(a.size,)``.
1942 Note that matrices are special cased for backward compatibility,
1943 if `a` is a matrix, then y is a 1-D ndarray.
1944
1945 See Also
1946 --------
1947 ndarray.flat : 1-D iterator over an array.
1948 ndarray.flatten : 1-D array copy of the elements of an array
1949 in row-major order.
1950 ndarray.reshape : Change the shape of an array without changing its data.
1951
1952 Notes
1953 -----
1954 In row-major, C-style order, in two dimensions, the row index
1955 varies the slowest, and the column index the quickest. This can
1956 be generalized to multiple dimensions, where row-major order
1957 implies that the index along the first axis varies slowest, and
1958 the index along the last quickest. The opposite holds for
1959 column-major, Fortran-style index ordering.
1960
1961 When a view is desired in as many cases as possible, ``arr.reshape(-1)``
1962 may be preferable. However, ``ravel`` supports ``K`` in the optional
1963 ``order`` argument while ``reshape`` does not.
1964
1965 Examples
1966 --------
1967 It is equivalent to ``reshape(-1, order=order)``.
1968
1969 >>> import numpy as np
1970 >>> x = np.array([[1, 2, 3], [4, 5, 6]])
1971 >>> np.ravel(x)
1972 array([1, 2, 3, 4, 5, 6])
1973
1974 >>> x.reshape(-1)
1975 array([1, 2, 3, 4, 5, 6])
1976
1977 >>> np.ravel(x, order='F')
1978 array([1, 4, 2, 5, 3, 6])
1979
1980 When ``order`` is 'A', it will preserve the array's 'C' or 'F' ordering:
1981
1982 >>> np.ravel(x.T)
1983 array([1, 4, 2, 5, 3, 6])
1984 >>> np.ravel(x.T, order='A')
1985 array([1, 2, 3, 4, 5, 6])
1986
1987 When ``order`` is 'K', it will preserve orderings that are neither 'C'
1988 nor 'F', but won't reverse axes:
1989
1990 >>> a = np.arange(3)[::-1]; a
1991 array([2, 1, 0])
1992 >>> a.ravel(order='C')
1993 array([2, 1, 0])
1994 >>> a.ravel(order='K')
1995 array([2, 1, 0])
1996
1997 >>> a = np.arange(12).reshape(2,3,2).swapaxes(1,2); a
1998 array([[[ 0, 2, 4],
1999 [ 1, 3, 5]],
2000 [[ 6, 8, 10],
2001 [ 7, 9, 11]]])
2002 >>> a.ravel(order='C')
2003 array([ 0, 2, 4, 1, 3, 5, 6, 8, 10, 7, 9, 11])
2004 >>> a.ravel(order='K')
2005 array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
2006
2007 """
2008 if isinstance(a, np.matrix):
2009 return asarray(a).ravel(order=order)
2010 else:
2011 return asanyarray(a).ravel(order=order)
2012
2013
2014def _nonzero_dispatcher(a):
2015 return (a,)
2016
2017
2018@array_function_dispatch(_nonzero_dispatcher)
2019def nonzero(a):
2020 """
2021 Return the indices of the elements that are non-zero.
2022
2023 Returns a tuple of arrays, one for each dimension of `a`,
2024 containing the indices of the non-zero elements in that
2025 dimension. The values in `a` are always tested and returned in
2026 row-major, C-style order.
2027
2028 To group the indices by element, rather than dimension, use `argwhere`,
2029 which returns a row for each non-zero element.
2030
2031 .. note::
2032
2033 When called on a zero-d array or scalar, ``nonzero(a)`` is treated
2034 as ``nonzero(atleast_1d(a))``.
2035
2036 .. deprecated:: 1.17.0
2037
2038 Use `atleast_1d` explicitly if this behavior is deliberate.
2039
2040 Parameters
2041 ----------
2042 a : array_like
2043 Input array.
2044
2045 Returns
2046 -------
2047 tuple_of_arrays : tuple
2048 Indices of elements that are non-zero.
2049
2050 See Also
2051 --------
2052 flatnonzero :
2053 Return indices that are non-zero in the flattened version of the input
2054 array.
2055 ndarray.nonzero :
2056 Equivalent ndarray method.
2057 count_nonzero :
2058 Counts the number of non-zero elements in the input array.
2059
2060 Notes
2061 -----
2062 While the nonzero values can be obtained with ``a[nonzero(a)]``, it is
2063 recommended to use ``x[x.astype(bool)]`` or ``x[x != 0]`` instead, which
2064 will correctly handle 0-d arrays.
2065
2066 Examples
2067 --------
2068 >>> import numpy as np
2069 >>> x = np.array([[3, 0, 0], [0, 4, 0], [5, 6, 0]])
2070 >>> x
2071 array([[3, 0, 0],
2072 [0, 4, 0],
2073 [5, 6, 0]])
2074 >>> np.nonzero(x)
2075 (array([0, 1, 2, 2]), array([0, 1, 0, 1]))
2076
2077 >>> x[np.nonzero(x)]
2078 array([3, 4, 5, 6])
2079 >>> np.transpose(np.nonzero(x))
2080 array([[0, 0],
2081 [1, 1],
2082 [2, 0],
2083 [2, 1]])
2084
2085 A common use for ``nonzero`` is to find the indices of an array, where
2086 a condition is True. Given an array `a`, the condition `a` > 3 is a
2087 boolean array and since False is interpreted as 0, np.nonzero(a > 3)
2088 yields the indices of the `a` where the condition is true.
2089
2090 >>> a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
2091 >>> a > 3
2092 array([[False, False, False],
2093 [ True, True, True],
2094 [ True, True, True]])
2095 >>> np.nonzero(a > 3)
2096 (array([1, 1, 1, 2, 2, 2]), array([0, 1, 2, 0, 1, 2]))
2097
2098 Using this result to index `a` is equivalent to using the mask directly:
2099
2100 >>> a[np.nonzero(a > 3)]
2101 array([4, 5, 6, 7, 8, 9])
2102 >>> a[a > 3] # prefer this spelling
2103 array([4, 5, 6, 7, 8, 9])
2104
2105 ``nonzero`` can also be called as a method of the array.
2106
2107 >>> (a > 3).nonzero()
2108 (array([1, 1, 1, 2, 2, 2]), array([0, 1, 2, 0, 1, 2]))
2109
2110 """
2111 return _wrapfunc(a, 'nonzero')
2112
2113
2114def _shape_dispatcher(a):
2115 return (a,)
2116
2117
2118@array_function_dispatch(_shape_dispatcher)
2119def shape(a):
2120 """
2121 Return the shape of an array.
2122
2123 Parameters
2124 ----------
2125 a : array_like
2126 Input array.
2127
2128 Returns
2129 -------
2130 shape : tuple of ints
2131 The elements of the shape tuple give the lengths of the
2132 corresponding array dimensions.
2133
2134 See Also
2135 --------
2136 len : ``len(a)`` is equivalent to ``np.shape(a)[0]`` for N-D arrays with
2137 ``N>=1``.
2138 ndarray.shape : Equivalent array method.
2139
2140 Examples
2141 --------
2142 >>> import numpy as np
2143 >>> np.shape(np.eye(3))
2144 (3, 3)
2145 >>> np.shape([[1, 3]])
2146 (1, 2)
2147 >>> np.shape([0])
2148 (1,)
2149 >>> np.shape(0)
2150 ()
2151
2152 >>> a = np.array([(1, 2), (3, 4), (5, 6)],
2153 ... dtype=[('x', 'i4'), ('y', 'i4')])
2154 >>> np.shape(a)
2155 (3,)
2156 >>> a.shape
2157 (3,)
2158
2159 """
2160 try:
2161 result = a.shape
2162 except AttributeError:
2163 result = asarray(a).shape
2164 return result
2165
2166
2167def _compress_dispatcher(condition, a, axis=None, out=None):
2168 return (condition, a, out)
2169
2170
2171@array_function_dispatch(_compress_dispatcher)
2172def compress(condition, a, axis=None, out=None):
2173 """
2174 Return selected slices of an array along given axis.
2175
2176 When working along a given axis, a slice along that axis is returned in
2177 `output` for each index where `condition` evaluates to True. When
2178 working on a 1-D array, `compress` is equivalent to `extract`.
2179
2180 Parameters
2181 ----------
2182 condition : 1-D array of bools
2183 Array that selects which entries to return. If len(condition)
2184 is less than the size of `a` along the given axis, then output is
2185 truncated to the length of the condition array.
2186 a : array_like
2187 Array from which to extract a part.
2188 axis : int, optional
2189 Axis along which to take slices. If None (default), work on the
2190 flattened array.
2191 out : ndarray, optional
2192 Output array. Its type is preserved and it must be of the right
2193 shape to hold the output.
2194
2195 Returns
2196 -------
2197 compressed_array : ndarray
2198 A copy of `a` without the slices along axis for which `condition`
2199 is false.
2200
2201 See Also
2202 --------
2203 take, choose, diag, diagonal, select
2204 ndarray.compress : Equivalent method in ndarray
2205 extract : Equivalent method when working on 1-D arrays
2206 :ref:`ufuncs-output-type`
2207
2208 Examples
2209 --------
2210 >>> import numpy as np
2211 >>> a = np.array([[1, 2], [3, 4], [5, 6]])
2212 >>> a
2213 array([[1, 2],
2214 [3, 4],
2215 [5, 6]])
2216 >>> np.compress([0, 1], a, axis=0)
2217 array([[3, 4]])
2218 >>> np.compress([False, True, True], a, axis=0)
2219 array([[3, 4],
2220 [5, 6]])
2221 >>> np.compress([False, True], a, axis=1)
2222 array([[2],
2223 [4],
2224 [6]])
2225
2226 Working on the flattened array does not return slices along an axis but
2227 selects elements.
2228
2229 >>> np.compress([False, True], a)
2230 array([2])
2231
2232 """
2233 return _wrapfunc(a, 'compress', condition, axis=axis, out=out)
2234
2235
2236def _clip_dispatcher(a, a_min=None, a_max=None, out=None, *, min=None,
2237 max=None, **kwargs):
2238 return (a, a_min, a_max, out, min, max)
2239
2240
2241@array_function_dispatch(_clip_dispatcher)
2242def clip(a, a_min=np._NoValue, a_max=np._NoValue, out=None, *,
2243 min=np._NoValue, max=np._NoValue, **kwargs):
2244 """
2245 Clip (limit) the values in an array.
2246
2247 Given an interval, values outside the interval are clipped to
2248 the interval edges. For example, if an interval of ``[0, 1]``
2249 is specified, values smaller than 0 become 0, and values larger
2250 than 1 become 1.
2251
2252 Equivalent to but faster than ``np.minimum(a_max, np.maximum(a, a_min))``.
2253
2254 No check is performed to ensure ``a_min < a_max``.
2255
2256 Parameters
2257 ----------
2258 a : array_like
2259 Array containing elements to clip.
2260 a_min, a_max : array_like or None
2261 Minimum and maximum value. If ``None``, clipping is not performed on
2262 the corresponding edge. If both ``a_min`` and ``a_max`` are ``None``,
2263 the elements of the returned array stay the same. Both are broadcasted
2264 against ``a``.
2265 out : ndarray, optional
2266 The results will be placed in this array. It may be the input
2267 array for in-place clipping. `out` must be of the right shape
2268 to hold the output. Its type is preserved.
2269 min, max : array_like or None
2270 Array API compatible alternatives for ``a_min`` and ``a_max``
2271 arguments. Either ``a_min`` and ``a_max`` or ``min`` and ``max``
2272 can be passed at the same time. Default: ``None``.
2273
2274 .. versionadded:: 2.1.0
2275 **kwargs
2276 For other keyword-only arguments, see the
2277 :ref:`ufunc docs <ufuncs.kwargs>`.
2278
2279 Returns
2280 -------
2281 clipped_array : ndarray
2282 An array with the elements of `a`, but where values
2283 < `a_min` are replaced with `a_min`, and those > `a_max`
2284 with `a_max`.
2285
2286 See Also
2287 --------
2288 :ref:`ufuncs-output-type`
2289
2290 Notes
2291 -----
2292 When `a_min` is greater than `a_max`, `clip` returns an
2293 array in which all values are equal to `a_max`,
2294 as shown in the second example.
2295
2296 Examples
2297 --------
2298 >>> import numpy as np
2299 >>> a = np.arange(10)
2300 >>> a
2301 array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
2302 >>> np.clip(a, 1, 8)
2303 array([1, 1, 2, 3, 4, 5, 6, 7, 8, 8])
2304 >>> np.clip(a, 8, 1)
2305 array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1])
2306 >>> np.clip(a, 3, 6, out=a)
2307 array([3, 3, 3, 3, 4, 5, 6, 6, 6, 6])
2308 >>> a
2309 array([3, 3, 3, 3, 4, 5, 6, 6, 6, 6])
2310 >>> a = np.arange(10)
2311 >>> a
2312 array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
2313 >>> np.clip(a, [3, 4, 1, 1, 1, 4, 4, 4, 4, 4], 8)
2314 array([3, 4, 2, 3, 4, 5, 6, 7, 8, 8])
2315
2316 """
2317 if a_min is np._NoValue and a_max is np._NoValue:
2318 a_min = None if min is np._NoValue else min
2319 a_max = None if max is np._NoValue else max
2320 elif a_min is np._NoValue:
2321 raise TypeError("clip() missing 1 required positional "
2322 "argument: 'a_min'")
2323 elif a_max is np._NoValue:
2324 raise TypeError("clip() missing 1 required positional "
2325 "argument: 'a_max'")
2326 elif min is not np._NoValue or max is not np._NoValue:
2327 raise ValueError("Passing `min` or `max` keyword argument when "
2328 "`a_min` and `a_max` are provided is forbidden.")
2329
2330 return _wrapfunc(a, 'clip', a_min, a_max, out=out, **kwargs)
2331
2332
2333def _sum_dispatcher(a, axis=None, dtype=None, out=None, keepdims=None,
2334 initial=None, where=None):
2335 return (a, out)
2336
2337
2338@array_function_dispatch(_sum_dispatcher)
2339def sum(a, axis=None, dtype=None, out=None, keepdims=np._NoValue,
2340 initial=np._NoValue, where=np._NoValue):
2341 """
2342 Sum of array elements over a given axis.
2343
2344 Parameters
2345 ----------
2346 a : array_like
2347 Elements to sum.
2348 axis : None or int or tuple of ints, optional
2349 Axis or axes along which a sum is performed. The default,
2350 axis=None, will sum all of the elements of the input array. If
2351 axis is negative it counts from the last to the first axis. If
2352 axis is a tuple of ints, a sum is performed on all of the axes
2353 specified in the tuple instead of a single axis or all the axes as
2354 before.
2355 dtype : dtype, optional
2356 The type of the returned array and of the accumulator in which the
2357 elements are summed. The dtype of `a` is used by default unless `a`
2358 has an integer dtype of less precision than the default platform
2359 integer. In that case, if `a` is signed then the platform integer
2360 is used while if `a` is unsigned then an unsigned integer of the
2361 same precision as the platform integer is used.
2362 out : ndarray, optional
2363 Alternative output array in which to place the result. It must have
2364 the same shape as the expected output, but the type of the output
2365 values will be cast if necessary.
2366 keepdims : bool, optional
2367 If this is set to True, the axes which are reduced are left
2368 in the result as dimensions with size one. With this option,
2369 the result will broadcast correctly against the input array.
2370
2371 If the default value is passed, then `keepdims` will not be
2372 passed through to the `sum` method of sub-classes of
2373 `ndarray`, however any non-default value will be. If the
2374 sub-class' method does not implement `keepdims` any
2375 exceptions will be raised.
2376 initial : scalar, optional
2377 Starting value for the sum. See `~numpy.ufunc.reduce` for details.
2378 where : array_like of bool, optional
2379 Elements to include in the sum. See `~numpy.ufunc.reduce` for details.
2380
2381 Returns
2382 -------
2383 sum_along_axis : ndarray
2384 An array with the same shape as `a`, with the specified
2385 axis removed. If `a` is a 0-d array, or if `axis` is None, a scalar
2386 is returned. If an output array is specified, a reference to
2387 `out` is returned.
2388
2389 See Also
2390 --------
2391 ndarray.sum : Equivalent method.
2392 add: ``numpy.add.reduce`` equivalent function.
2393 cumsum : Cumulative sum of array elements.
2394 trapezoid : Integration of array values using composite trapezoidal rule.
2395
2396 mean, average
2397
2398 Notes
2399 -----
2400 Arithmetic is modular when using integer types, and no error is
2401 raised on overflow.
2402
2403 The sum of an empty array is the neutral element 0:
2404
2405 >>> np.sum([])
2406 0.0
2407
2408 For floating point numbers the numerical precision of sum (and
2409 ``np.add.reduce``) is in general limited by directly adding each number
2410 individually to the result causing rounding errors in every step.
2411 However, often numpy will use a numerically better approach (partial
2412 pairwise summation) leading to improved precision in many use-cases.
2413 This improved precision is always provided when no ``axis`` is given.
2414 When ``axis`` is given, it will depend on which axis is summed.
2415 Technically, to provide the best speed possible, the improved precision
2416 is only used when the summation is along the fast axis in memory.
2417 Note that the exact precision may vary depending on other parameters.
2418 In contrast to NumPy, Python's ``math.fsum`` function uses a slower but
2419 more precise approach to summation.
2420 Especially when summing a large number of lower precision floating point
2421 numbers, such as ``float32``, numerical errors can become significant.
2422 In such cases it can be advisable to use `dtype="float64"` to use a higher
2423 precision for the output.
2424
2425 Examples
2426 --------
2427 >>> import numpy as np
2428 >>> np.sum([0.5, 1.5])
2429 2.0
2430 >>> np.sum([0.5, 0.7, 0.2, 1.5], dtype=np.int32)
2431 np.int32(1)
2432 >>> np.sum([[0, 1], [0, 5]])
2433 6
2434 >>> np.sum([[0, 1], [0, 5]], axis=0)
2435 array([0, 6])
2436 >>> np.sum([[0, 1], [0, 5]], axis=1)
2437 array([1, 5])
2438 >>> np.sum([[0, 1], [np.nan, 5]], where=[False, True], axis=1)
2439 array([1., 5.])
2440
2441 If the accumulator is too small, overflow occurs:
2442
2443 >>> np.ones(128, dtype=np.int8).sum(dtype=np.int8)
2444 np.int8(-128)
2445
2446 You can also start the sum with a value other than zero:
2447
2448 >>> np.sum([10], initial=5)
2449 15
2450 """
2451 if isinstance(a, _gentype):
2452 # 2018-02-25, 1.15.0
2453 warnings.warn(
2454 "Calling np.sum(generator) is deprecated, and in the future will "
2455 "give a different result. Use np.sum(np.fromiter(generator)) or "
2456 "the python sum builtin instead.",
2457 DeprecationWarning, stacklevel=2
2458 )
2459
2460 res = _sum_(a)
2461 if out is not None:
2462 out[...] = res
2463 return out
2464 return res
2465
2466 return _wrapreduction(
2467 a, np.add, 'sum', axis, dtype, out,
2468 keepdims=keepdims, initial=initial, where=where
2469 )
2470
2471
2472def _any_dispatcher(a, axis=None, out=None, keepdims=None, *,
2473 where=np._NoValue):
2474 return (a, where, out)
2475
2476
2477@array_function_dispatch(_any_dispatcher)
2478def any(a, axis=None, out=None, keepdims=np._NoValue, *, where=np._NoValue):
2479 """
2480 Test whether any array element along a given axis evaluates to True.
2481
2482 Returns single boolean if `axis` is ``None``
2483
2484 Parameters
2485 ----------
2486 a : array_like
2487 Input array or object that can be converted to an array.
2488 axis : None or int or tuple of ints, optional
2489 Axis or axes along which a logical OR reduction is performed.
2490 The default (``axis=None``) is to perform a logical OR over all
2491 the dimensions of the input array. `axis` may be negative, in
2492 which case it counts from the last to the first axis. If this
2493 is a tuple of ints, a reduction is performed on multiple
2494 axes, instead of a single axis or all the axes as before.
2495 out : ndarray, optional
2496 Alternate output array in which to place the result. It must have
2497 the same shape as the expected output and its type is preserved
2498 (e.g., if it is of type float, then it will remain so, returning
2499 1.0 for True and 0.0 for False, regardless of the type of `a`).
2500 See :ref:`ufuncs-output-type` for more details.
2501
2502 keepdims : bool, optional
2503 If this is set to True, the axes which are reduced are left
2504 in the result as dimensions with size one. With this option,
2505 the result will broadcast correctly against the input array.
2506
2507 If the default value is passed, then `keepdims` will not be
2508 passed through to the `any` method of sub-classes of
2509 `ndarray`, however any non-default value will be. If the
2510 sub-class' method does not implement `keepdims` any
2511 exceptions will be raised.
2512
2513 where : array_like of bool, optional
2514 Elements to include in checking for any `True` values.
2515 See `~numpy.ufunc.reduce` for details.
2516
2517 .. versionadded:: 1.20.0
2518
2519 Returns
2520 -------
2521 any : bool or ndarray
2522 A new boolean or `ndarray` is returned unless `out` is specified,
2523 in which case a reference to `out` is returned.
2524
2525 See Also
2526 --------
2527 ndarray.any : equivalent method
2528
2529 all : Test whether all elements along a given axis evaluate to True.
2530
2531 Notes
2532 -----
2533 Not a Number (NaN), positive infinity and negative infinity evaluate
2534 to `True` because these are not equal to zero.
2535
2536 .. versionchanged:: 2.0
2537 Before NumPy 2.0, ``any`` did not return booleans for object dtype
2538 input arrays.
2539 This behavior is still available via ``np.logical_or.reduce``.
2540
2541 Examples
2542 --------
2543 >>> import numpy as np
2544 >>> np.any([[True, False], [True, True]])
2545 True
2546
2547 >>> np.any([[True, False, True ],
2548 ... [False, False, False]], axis=0)
2549 array([ True, False, True])
2550
2551 >>> np.any([-1, 0, 5])
2552 True
2553
2554 >>> np.any([[np.nan], [np.inf]], axis=1, keepdims=True)
2555 array([[ True],
2556 [ True]])
2557
2558 >>> np.any([[True, False], [False, False]], where=[[False], [True]])
2559 False
2560
2561 >>> a = np.array([[1, 0, 0],
2562 ... [0, 0, 1],
2563 ... [0, 0, 0]])
2564 >>> np.any(a, axis=0)
2565 array([ True, False, True])
2566 >>> np.any(a, axis=1)
2567 array([ True, True, False])
2568
2569 >>> o=np.array(False)
2570 >>> z=np.any([-1, 4, 5], out=o)
2571 >>> z, o
2572 (array(True), array(True))
2573 >>> # Check now that z is a reference to o
2574 >>> z is o
2575 True
2576 >>> id(z), id(o) # identity of z and o # doctest: +SKIP
2577 (191614240, 191614240)
2578
2579 """
2580 return _wrapreduction_any_all(a, np.logical_or, 'any', axis, out,
2581 keepdims=keepdims, where=where)
2582
2583
2584def _all_dispatcher(a, axis=None, out=None, keepdims=None, *,
2585 where=None):
2586 return (a, where, out)
2587
2588
2589@array_function_dispatch(_all_dispatcher)
2590def all(a, axis=None, out=None, keepdims=np._NoValue, *, where=np._NoValue):
2591 """
2592 Test whether all array elements along a given axis evaluate to True.
2593
2594 Parameters
2595 ----------
2596 a : array_like
2597 Input array or object that can be converted to an array.
2598 axis : None or int or tuple of ints, optional
2599 Axis or axes along which a logical AND reduction is performed.
2600 The default (``axis=None``) is to perform a logical AND over all
2601 the dimensions of the input array. `axis` may be negative, in
2602 which case it counts from the last to the first axis. If this
2603 is a tuple of ints, a reduction is performed on multiple
2604 axes, instead of a single axis or all the axes as before.
2605 out : ndarray, optional
2606 Alternate output array in which to place the result.
2607 It must have the same shape as the expected output and its
2608 type is preserved (e.g., if ``dtype(out)`` is float, the result
2609 will consist of 0.0's and 1.0's). See :ref:`ufuncs-output-type`
2610 for more details.
2611
2612 keepdims : bool, optional
2613 If this is set to True, the axes which are reduced are left
2614 in the result as dimensions with size one. With this option,
2615 the result will broadcast correctly against the input array.
2616
2617 If the default value is passed, then `keepdims` will not be
2618 passed through to the `all` method of sub-classes of
2619 `ndarray`, however any non-default value will be. If the
2620 sub-class' method does not implement `keepdims` any
2621 exceptions will be raised.
2622
2623 where : array_like of bool, optional
2624 Elements to include in checking for all `True` values.
2625 See `~numpy.ufunc.reduce` for details.
2626
2627 .. versionadded:: 1.20.0
2628
2629 Returns
2630 -------
2631 all : ndarray, bool
2632 A new boolean or array is returned unless `out` is specified,
2633 in which case a reference to `out` is returned.
2634
2635 See Also
2636 --------
2637 ndarray.all : equivalent method
2638
2639 any : Test whether any element along a given axis evaluates to True.
2640
2641 Notes
2642 -----
2643 Not a Number (NaN), positive infinity and negative infinity
2644 evaluate to `True` because these are not equal to zero.
2645
2646 .. versionchanged:: 2.0
2647 Before NumPy 2.0, ``all`` did not return booleans for object dtype
2648 input arrays.
2649 This behavior is still available via ``np.logical_and.reduce``.
2650
2651 Examples
2652 --------
2653 >>> import numpy as np
2654 >>> np.all([[True,False],[True,True]])
2655 False
2656
2657 >>> np.all([[True,False],[True,True]], axis=0)
2658 array([ True, False])
2659
2660 >>> np.all([-1, 4, 5])
2661 True
2662
2663 >>> np.all([1.0, np.nan])
2664 True
2665
2666 >>> np.all([[True, True], [False, True]], where=[[True], [False]])
2667 True
2668
2669 >>> o=np.array(False)
2670 >>> z=np.all([-1, 4, 5], out=o)
2671 >>> id(z), id(o), z
2672 (28293632, 28293632, array(True)) # may vary
2673
2674 """
2675 return _wrapreduction_any_all(a, np.logical_and, 'all', axis, out,
2676 keepdims=keepdims, where=where)
2677
2678
2679def _cumulative_func(x, func, axis, dtype, out, include_initial):
2680 x = np.atleast_1d(x)
2681 x_ndim = x.ndim
2682 if axis is None:
2683 if x_ndim >= 2:
2684 raise ValueError("For arrays which have more than one dimension "
2685 "``axis`` argument is required.")
2686 axis = 0
2687
2688 if out is not None and include_initial:
2689 item = [slice(None)] * x_ndim
2690 item[axis] = slice(1, None)
2691 func.accumulate(x, axis=axis, dtype=dtype, out=out[tuple(item)])
2692 item[axis] = 0
2693 out[tuple(item)] = func.identity
2694 return out
2695
2696 res = func.accumulate(x, axis=axis, dtype=dtype, out=out)
2697 if include_initial:
2698 initial_shape = list(x.shape)
2699 initial_shape[axis] = 1
2700 res = np.concat(
2701 [np.full_like(res, func.identity, shape=initial_shape), res],
2702 axis=axis,
2703 )
2704
2705 return res
2706
2707
2708def _cumulative_prod_dispatcher(x, /, *, axis=None, dtype=None, out=None,
2709 include_initial=None):
2710 return (x, out)
2711
2712
2713@array_function_dispatch(_cumulative_prod_dispatcher)
2714def cumulative_prod(x, /, *, axis=None, dtype=None, out=None,
2715 include_initial=False):
2716 """
2717 Return the cumulative product of elements along a given axis.
2718
2719 This function is an Array API compatible alternative to `numpy.cumprod`.
2720
2721 Parameters
2722 ----------
2723 x : array_like
2724 Input array.
2725 axis : int, optional
2726 Axis along which the cumulative product is computed. The default
2727 (None) is only allowed for one-dimensional arrays. For arrays
2728 with more than one dimension ``axis`` is required.
2729 dtype : dtype, optional
2730 Type of the returned array, as well as of the accumulator in which
2731 the elements are multiplied. If ``dtype`` is not specified, it
2732 defaults to the dtype of ``x``, unless ``x`` has an integer dtype
2733 with a precision less than that of the default platform integer.
2734 In that case, the default platform integer is used instead.
2735 out : ndarray, optional
2736 Alternative output array in which to place the result. It must
2737 have the same shape and buffer length as the expected output
2738 but the type of the resulting values will be cast if necessary.
2739 See :ref:`ufuncs-output-type` for more details.
2740 include_initial : bool, optional
2741 Boolean indicating whether to include the initial value (ones) as
2742 the first value in the output. With ``include_initial=True``
2743 the shape of the output is different than the shape of the input.
2744 Default: ``False``.
2745
2746 Returns
2747 -------
2748 cumulative_prod_along_axis : ndarray
2749 A new array holding the result is returned unless ``out`` is
2750 specified, in which case a reference to ``out`` is returned. The
2751 result has the same shape as ``x`` if ``include_initial=False``.
2752
2753 Notes
2754 -----
2755 Arithmetic is modular when using integer types, and no error is
2756 raised on overflow.
2757
2758 Examples
2759 --------
2760 >>> a = np.array([1, 2, 3])
2761 >>> np.cumulative_prod(a) # intermediate results 1, 1*2
2762 ... # total product 1*2*3 = 6
2763 array([1, 2, 6])
2764 >>> a = np.array([1, 2, 3, 4, 5, 6])
2765 >>> np.cumulative_prod(a, dtype=float) # specify type of output
2766 array([ 1., 2., 6., 24., 120., 720.])
2767
2768 The cumulative product for each column (i.e., over the rows) of ``b``:
2769
2770 >>> b = np.array([[1, 2, 3], [4, 5, 6]])
2771 >>> np.cumulative_prod(b, axis=0)
2772 array([[ 1, 2, 3],
2773 [ 4, 10, 18]])
2774
2775 The cumulative product for each row (i.e. over the columns) of ``b``:
2776
2777 >>> np.cumulative_prod(b, axis=1)
2778 array([[ 1, 2, 6],
2779 [ 4, 20, 120]])
2780
2781 """
2782 return _cumulative_func(x, um.multiply, axis, dtype, out, include_initial)
2783
2784
2785def _cumulative_sum_dispatcher(x, /, *, axis=None, dtype=None, out=None,
2786 include_initial=None):
2787 return (x, out)
2788
2789
2790@array_function_dispatch(_cumulative_sum_dispatcher)
2791def cumulative_sum(x, /, *, axis=None, dtype=None, out=None,
2792 include_initial=False):
2793 """
2794 Return the cumulative sum of the elements along a given axis.
2795
2796 This function is an Array API compatible alternative to `numpy.cumsum`.
2797
2798 Parameters
2799 ----------
2800 x : array_like
2801 Input array.
2802 axis : int, optional
2803 Axis along which the cumulative sum is computed. The default
2804 (None) is only allowed for one-dimensional arrays. For arrays
2805 with more than one dimension ``axis`` is required.
2806 dtype : dtype, optional
2807 Type of the returned array and of the accumulator in which the
2808 elements are summed. If ``dtype`` is not specified, it defaults
2809 to the dtype of ``x``, unless ``x`` has an integer dtype with
2810 a precision less than that of the default platform integer.
2811 In that case, the default platform integer is used.
2812 out : ndarray, optional
2813 Alternative output array in which to place the result. It must
2814 have the same shape and buffer length as the expected output
2815 but the type will be cast if necessary. See :ref:`ufuncs-output-type`
2816 for more details.
2817 include_initial : bool, optional
2818 Boolean indicating whether to include the initial value (zeros) as
2819 the first value in the output. With ``include_initial=True``
2820 the shape of the output is different than the shape of the input.
2821 Default: ``False``.
2822
2823 Returns
2824 -------
2825 cumulative_sum_along_axis : ndarray
2826 A new array holding the result is returned unless ``out`` is
2827 specified, in which case a reference to ``out`` is returned. The
2828 result has the same shape as ``x`` if ``include_initial=False``.
2829
2830 See Also
2831 --------
2832 sum : Sum array elements.
2833 trapezoid : Integration of array values using composite trapezoidal rule.
2834 diff : Calculate the n-th discrete difference along given axis.
2835
2836 Notes
2837 -----
2838 Arithmetic is modular when using integer types, and no error is
2839 raised on overflow.
2840
2841 ``cumulative_sum(a)[-1]`` may not be equal to ``sum(a)`` for
2842 floating-point values since ``sum`` may use a pairwise summation routine,
2843 reducing the roundoff-error. See `sum` for more information.
2844
2845 Examples
2846 --------
2847 >>> a = np.array([1, 2, 3, 4, 5, 6])
2848 >>> a
2849 array([1, 2, 3, 4, 5, 6])
2850 >>> np.cumulative_sum(a)
2851 array([ 1, 3, 6, 10, 15, 21])
2852 >>> np.cumulative_sum(a, dtype=float) # specifies type of output value(s)
2853 array([ 1., 3., 6., 10., 15., 21.])
2854
2855 >>> b = np.array([[1, 2, 3], [4, 5, 6]])
2856 >>> np.cumulative_sum(b,axis=0) # sum over rows for each of the 3 columns
2857 array([[1, 2, 3],
2858 [5, 7, 9]])
2859 >>> np.cumulative_sum(b,axis=1) # sum over columns for each of the 2 rows
2860 array([[ 1, 3, 6],
2861 [ 4, 9, 15]])
2862
2863 ``cumulative_sum(c)[-1]`` may not be equal to ``sum(c)``
2864
2865 >>> c = np.array([1, 2e-9, 3e-9] * 1000000)
2866 >>> np.cumulative_sum(c)[-1]
2867 1000000.0050045159
2868 >>> c.sum()
2869 1000000.0050000029
2870
2871 """
2872 return _cumulative_func(x, um.add, axis, dtype, out, include_initial)
2873
2874
2875def _cumsum_dispatcher(a, axis=None, dtype=None, out=None):
2876 return (a, out)
2877
2878
2879@array_function_dispatch(_cumsum_dispatcher)
2880def cumsum(a, axis=None, dtype=None, out=None):
2881 """
2882 Return the cumulative sum of the elements along a given axis.
2883
2884 Parameters
2885 ----------
2886 a : array_like
2887 Input array.
2888 axis : int, optional
2889 Axis along which the cumulative sum is computed. The default
2890 (None) is to compute the cumsum over the flattened array.
2891 dtype : dtype, optional
2892 Type of the returned array and of the accumulator in which the
2893 elements are summed. If `dtype` is not specified, it defaults
2894 to the dtype of `a`, unless `a` has an integer dtype with a
2895 precision less than that of the default platform integer. In
2896 that case, the default platform integer is used.
2897 out : ndarray, optional
2898 Alternative output array in which to place the result. It must
2899 have the same shape and buffer length as the expected output
2900 but the type will be cast if necessary. See :ref:`ufuncs-output-type`
2901 for more details.
2902
2903 Returns
2904 -------
2905 cumsum_along_axis : ndarray.
2906 A new array holding the result is returned unless `out` is
2907 specified, in which case a reference to `out` is returned. The
2908 result has the same size as `a`, and the same shape as `a` if
2909 `axis` is not None or `a` is a 1-d array.
2910
2911 See Also
2912 --------
2913 cumulative_sum : Array API compatible alternative for ``cumsum``.
2914 sum : Sum array elements.
2915 trapezoid : Integration of array values using composite trapezoidal rule.
2916 diff : Calculate the n-th discrete difference along given axis.
2917
2918 Notes
2919 -----
2920 Arithmetic is modular when using integer types, and no error is
2921 raised on overflow.
2922
2923 ``cumsum(a)[-1]`` may not be equal to ``sum(a)`` for floating-point
2924 values since ``sum`` may use a pairwise summation routine, reducing
2925 the roundoff-error. See `sum` for more information.
2926
2927 Examples
2928 --------
2929 >>> import numpy as np
2930 >>> a = np.array([[1,2,3], [4,5,6]])
2931 >>> a
2932 array([[1, 2, 3],
2933 [4, 5, 6]])
2934 >>> np.cumsum(a)
2935 array([ 1, 3, 6, 10, 15, 21])
2936 >>> np.cumsum(a, dtype=float) # specifies type of output value(s)
2937 array([ 1., 3., 6., 10., 15., 21.])
2938
2939 >>> np.cumsum(a,axis=0) # sum over rows for each of the 3 columns
2940 array([[1, 2, 3],
2941 [5, 7, 9]])
2942 >>> np.cumsum(a,axis=1) # sum over columns for each of the 2 rows
2943 array([[ 1, 3, 6],
2944 [ 4, 9, 15]])
2945
2946 ``cumsum(b)[-1]`` may not be equal to ``sum(b)``
2947
2948 >>> b = np.array([1, 2e-9, 3e-9] * 1000000)
2949 >>> b.cumsum()[-1]
2950 1000000.0050045159
2951 >>> b.sum()
2952 1000000.0050000029
2953
2954 """
2955 return _wrapfunc(a, 'cumsum', axis=axis, dtype=dtype, out=out)
2956
2957
2958def _ptp_dispatcher(a, axis=None, out=None, keepdims=None):
2959 return (a, out)
2960
2961
2962@array_function_dispatch(_ptp_dispatcher)
2963def ptp(a, axis=None, out=None, keepdims=np._NoValue):
2964 """
2965 Range of values (maximum - minimum) along an axis.
2966
2967 The name of the function comes from the acronym for 'peak to peak'.
2968
2969 .. warning::
2970 `ptp` preserves the data type of the array. This means the
2971 return value for an input of signed integers with n bits
2972 (e.g. `numpy.int8`, `numpy.int16`, etc) is also a signed integer
2973 with n bits. In that case, peak-to-peak values greater than
2974 ``2**(n-1)-1`` will be returned as negative values. An example
2975 with a work-around is shown below.
2976
2977 Parameters
2978 ----------
2979 a : array_like
2980 Input values.
2981 axis : None or int or tuple of ints, optional
2982 Axis along which to find the peaks. By default, flatten the
2983 array. `axis` may be negative, in
2984 which case it counts from the last to the first axis.
2985 If this is a tuple of ints, a reduction is performed on multiple
2986 axes, instead of a single axis or all the axes as before.
2987 out : array_like
2988 Alternative output array in which to place the result. It must
2989 have the same shape and buffer length as the expected output,
2990 but the type of the output values will be cast if necessary.
2991
2992 keepdims : bool, optional
2993 If this is set to True, the axes which are reduced are left
2994 in the result as dimensions with size one. With this option,
2995 the result will broadcast correctly against the input array.
2996
2997 If the default value is passed, then `keepdims` will not be
2998 passed through to the `ptp` method of sub-classes of
2999 `ndarray`, however any non-default value will be. If the
3000 sub-class' method does not implement `keepdims` any
3001 exceptions will be raised.
3002
3003 Returns
3004 -------
3005 ptp : ndarray or scalar
3006 The range of a given array - `scalar` if array is one-dimensional
3007 or a new array holding the result along the given axis
3008
3009 Examples
3010 --------
3011 >>> import numpy as np
3012 >>> x = np.array([[4, 9, 2, 10],
3013 ... [6, 9, 7, 12]])
3014
3015 >>> np.ptp(x, axis=1)
3016 array([8, 6])
3017
3018 >>> np.ptp(x, axis=0)
3019 array([2, 0, 5, 2])
3020
3021 >>> np.ptp(x)
3022 10
3023
3024 This example shows that a negative value can be returned when
3025 the input is an array of signed integers.
3026
3027 >>> y = np.array([[1, 127],
3028 ... [0, 127],
3029 ... [-1, 127],
3030 ... [-2, 127]], dtype=np.int8)
3031 >>> np.ptp(y, axis=1)
3032 array([ 126, 127, -128, -127], dtype=int8)
3033
3034 A work-around is to use the `view()` method to view the result as
3035 unsigned integers with the same bit width:
3036
3037 >>> np.ptp(y, axis=1).view(np.uint8)
3038 array([126, 127, 128, 129], dtype=uint8)
3039
3040 """
3041 kwargs = {}
3042 if keepdims is not np._NoValue:
3043 kwargs['keepdims'] = keepdims
3044 return _methods._ptp(a, axis=axis, out=out, **kwargs)
3045
3046
3047def _max_dispatcher(a, axis=None, out=None, keepdims=None, initial=None,
3048 where=None):
3049 return (a, out)
3050
3051
3052@array_function_dispatch(_max_dispatcher)
3053@set_module('numpy')
3054def max(a, axis=None, out=None, keepdims=np._NoValue, initial=np._NoValue,
3055 where=np._NoValue):
3056 """
3057 Return the maximum of an array or maximum along an axis.
3058
3059 Parameters
3060 ----------
3061 a : array_like
3062 Input data.
3063 axis : None or int or tuple of ints, optional
3064 Axis or axes along which to operate. By default, flattened input is
3065 used. If this is a tuple of ints, the maximum is selected over
3066 multiple axes, instead of a single axis or all the axes as before.
3067
3068 out : ndarray, optional
3069 Alternative output array in which to place the result. Must
3070 be of the same shape and buffer length as the expected output.
3071 See :ref:`ufuncs-output-type` for more details.
3072
3073 keepdims : bool, optional
3074 If this is set to True, the axes which are reduced are left
3075 in the result as dimensions with size one. With this option,
3076 the result will broadcast correctly against the input array.
3077
3078 If the default value is passed, then `keepdims` will not be
3079 passed through to the ``max`` method of sub-classes of
3080 `ndarray`, however any non-default value will be. If the
3081 sub-class' method does not implement `keepdims` any
3082 exceptions will be raised.
3083
3084 initial : scalar, optional
3085 The minimum value of an output element. Must be present to allow
3086 computation on empty slice. See `~numpy.ufunc.reduce` for details.
3087
3088 where : array_like of bool, optional
3089 Elements to compare for the maximum. See `~numpy.ufunc.reduce`
3090 for details.
3091
3092 Returns
3093 -------
3094 max : ndarray or scalar
3095 Maximum of `a`. If `axis` is None, the result is a scalar value.
3096 If `axis` is an int, the result is an array of dimension
3097 ``a.ndim - 1``. If `axis` is a tuple, the result is an array of
3098 dimension ``a.ndim - len(axis)``.
3099
3100 See Also
3101 --------
3102 amin :
3103 The minimum value of an array along a given axis, propagating any NaNs.
3104 nanmax :
3105 The maximum value of an array along a given axis, ignoring any NaNs.
3106 maximum :
3107 Element-wise maximum of two arrays, propagating any NaNs.
3108 fmax :
3109 Element-wise maximum of two arrays, ignoring any NaNs.
3110 argmax :
3111 Return the indices of the maximum values.
3112
3113 nanmin, minimum, fmin
3114
3115 Notes
3116 -----
3117 NaN values are propagated, that is if at least one item is NaN, the
3118 corresponding max value will be NaN as well. To ignore NaN values
3119 (MATLAB behavior), please use nanmax.
3120
3121 Don't use `~numpy.max` for element-wise comparison of 2 arrays; when
3122 ``a.shape[0]`` is 2, ``maximum(a[0], a[1])`` is faster than
3123 ``max(a, axis=0)``.
3124
3125 Examples
3126 --------
3127 >>> import numpy as np
3128 >>> a = np.arange(4).reshape((2,2))
3129 >>> a
3130 array([[0, 1],
3131 [2, 3]])
3132 >>> np.max(a) # Maximum of the flattened array
3133 3
3134 >>> np.max(a, axis=0) # Maxima along the first axis
3135 array([2, 3])
3136 >>> np.max(a, axis=1) # Maxima along the second axis
3137 array([1, 3])
3138 >>> np.max(a, where=[False, True], initial=-1, axis=0)
3139 array([-1, 3])
3140 >>> b = np.arange(5, dtype=float)
3141 >>> b[2] = np.nan
3142 >>> np.max(b)
3143 np.float64(nan)
3144 >>> np.max(b, where=~np.isnan(b), initial=-1)
3145 4.0
3146 >>> np.nanmax(b)
3147 4.0
3148
3149 You can use an initial value to compute the maximum of an empty slice, or
3150 to initialize it to a different value:
3151
3152 >>> np.max([[-50], [10]], axis=-1, initial=0)
3153 array([ 0, 10])
3154
3155 Notice that the initial value is used as one of the elements for which the
3156 maximum is determined, unlike for the default argument Python's max
3157 function, which is only used for empty iterables.
3158
3159 >>> np.max([5], initial=6)
3160 6
3161 >>> max([5], default=6)
3162 5
3163 """
3164 return _wrapreduction(a, np.maximum, 'max', axis, None, out,
3165 keepdims=keepdims, initial=initial, where=where)
3166
3167
3168@array_function_dispatch(_max_dispatcher)
3169def amax(a, axis=None, out=None, keepdims=np._NoValue, initial=np._NoValue,
3170 where=np._NoValue):
3171 """
3172 Return the maximum of an array or maximum along an axis.
3173
3174 `amax` is an alias of `~numpy.max`.
3175
3176 See Also
3177 --------
3178 max : alias of this function
3179 ndarray.max : equivalent method
3180 """
3181 return _wrapreduction(a, np.maximum, 'max', axis, None, out,
3182 keepdims=keepdims, initial=initial, where=where)
3183
3184
3185def _min_dispatcher(a, axis=None, out=None, keepdims=None, initial=None,
3186 where=None):
3187 return (a, out)
3188
3189
3190@array_function_dispatch(_min_dispatcher)
3191def min(a, axis=None, out=None, keepdims=np._NoValue, initial=np._NoValue,
3192 where=np._NoValue):
3193 """
3194 Return the minimum of an array or minimum along an axis.
3195
3196 Parameters
3197 ----------
3198 a : array_like
3199 Input data.
3200 axis : None or int or tuple of ints, optional
3201 Axis or axes along which to operate. By default, flattened input is
3202 used.
3203
3204 If this is a tuple of ints, the minimum is selected over multiple axes,
3205 instead of a single axis or all the axes as before.
3206 out : ndarray, optional
3207 Alternative output array in which to place the result. Must
3208 be of the same shape and buffer length as the expected output.
3209 See :ref:`ufuncs-output-type` for more details.
3210
3211 keepdims : bool, optional
3212 If this is set to True, the axes which are reduced are left
3213 in the result as dimensions with size one. With this option,
3214 the result will broadcast correctly against the input array.
3215
3216 If the default value is passed, then `keepdims` will not be
3217 passed through to the ``min`` method of sub-classes of
3218 `ndarray`, however any non-default value will be. If the
3219 sub-class' method does not implement `keepdims` any
3220 exceptions will be raised.
3221
3222 initial : scalar, optional
3223 The maximum value of an output element. Must be present to allow
3224 computation on empty slice. See `~numpy.ufunc.reduce` for details.
3225
3226 where : array_like of bool, optional
3227 Elements to compare for the minimum. See `~numpy.ufunc.reduce`
3228 for details.
3229
3230 Returns
3231 -------
3232 min : ndarray or scalar
3233 Minimum of `a`. If `axis` is None, the result is a scalar value.
3234 If `axis` is an int, the result is an array of dimension
3235 ``a.ndim - 1``. If `axis` is a tuple, the result is an array of
3236 dimension ``a.ndim - len(axis)``.
3237
3238 See Also
3239 --------
3240 amax :
3241 The maximum value of an array along a given axis, propagating any NaNs.
3242 nanmin :
3243 The minimum value of an array along a given axis, ignoring any NaNs.
3244 minimum :
3245 Element-wise minimum of two arrays, propagating any NaNs.
3246 fmin :
3247 Element-wise minimum of two arrays, ignoring any NaNs.
3248 argmin :
3249 Return the indices of the minimum values.
3250
3251 nanmax, maximum, fmax
3252
3253 Notes
3254 -----
3255 NaN values are propagated, that is if at least one item is NaN, the
3256 corresponding min value will be NaN as well. To ignore NaN values
3257 (MATLAB behavior), please use nanmin.
3258
3259 Don't use `~numpy.min` for element-wise comparison of 2 arrays; when
3260 ``a.shape[0]`` is 2, ``minimum(a[0], a[1])`` is faster than
3261 ``min(a, axis=0)``.
3262
3263 Examples
3264 --------
3265 >>> import numpy as np
3266 >>> a = np.arange(4).reshape((2,2))
3267 >>> a
3268 array([[0, 1],
3269 [2, 3]])
3270 >>> np.min(a) # Minimum of the flattened array
3271 0
3272 >>> np.min(a, axis=0) # Minima along the first axis
3273 array([0, 1])
3274 >>> np.min(a, axis=1) # Minima along the second axis
3275 array([0, 2])
3276 >>> np.min(a, where=[False, True], initial=10, axis=0)
3277 array([10, 1])
3278
3279 >>> b = np.arange(5, dtype=float)
3280 >>> b[2] = np.nan
3281 >>> np.min(b)
3282 np.float64(nan)
3283 >>> np.min(b, where=~np.isnan(b), initial=10)
3284 0.0
3285 >>> np.nanmin(b)
3286 0.0
3287
3288 >>> np.min([[-50], [10]], axis=-1, initial=0)
3289 array([-50, 0])
3290
3291 Notice that the initial value is used as one of the elements for which the
3292 minimum is determined, unlike for the default argument Python's max
3293 function, which is only used for empty iterables.
3294
3295 Notice that this isn't the same as Python's ``default`` argument.
3296
3297 >>> np.min([6], initial=5)
3298 5
3299 >>> min([6], default=5)
3300 6
3301 """
3302 return _wrapreduction(a, np.minimum, 'min', axis, None, out,
3303 keepdims=keepdims, initial=initial, where=where)
3304
3305
3306@array_function_dispatch(_min_dispatcher)
3307def amin(a, axis=None, out=None, keepdims=np._NoValue, initial=np._NoValue,
3308 where=np._NoValue):
3309 """
3310 Return the minimum of an array or minimum along an axis.
3311
3312 `amin` is an alias of `~numpy.min`.
3313
3314 See Also
3315 --------
3316 min : alias of this function
3317 ndarray.min : equivalent method
3318 """
3319 return _wrapreduction(a, np.minimum, 'min', axis, None, out,
3320 keepdims=keepdims, initial=initial, where=where)
3321
3322
3323def _prod_dispatcher(a, axis=None, dtype=None, out=None, keepdims=None,
3324 initial=None, where=None):
3325 return (a, out)
3326
3327
3328@array_function_dispatch(_prod_dispatcher)
3329def prod(a, axis=None, dtype=None, out=None, keepdims=np._NoValue,
3330 initial=np._NoValue, where=np._NoValue):
3331 """
3332 Return the product of array elements over a given axis.
3333
3334 Parameters
3335 ----------
3336 a : array_like
3337 Input data.
3338 axis : None or int or tuple of ints, optional
3339 Axis or axes along which a product is performed. The default,
3340 axis=None, will calculate the product of all the elements in the
3341 input array. If axis is negative it counts from the last to the
3342 first axis.
3343
3344 If axis is a tuple of ints, a product is performed on all of the
3345 axes specified in the tuple instead of a single axis or all the
3346 axes as before.
3347 dtype : dtype, optional
3348 The type of the returned array, as well as of the accumulator in
3349 which the elements are multiplied. The dtype of `a` is used by
3350 default unless `a` has an integer dtype of less precision than the
3351 default platform integer. In that case, if `a` is signed then the
3352 platform integer is used while if `a` is unsigned then an unsigned
3353 integer of the same precision as the platform integer is used.
3354 out : ndarray, optional
3355 Alternative output array in which to place the result. It must have
3356 the same shape as the expected output, but the type of the output
3357 values will be cast if necessary.
3358 keepdims : bool, optional
3359 If this is set to True, the axes which are reduced are left in the
3360 result as dimensions with size one. With this option, the result
3361 will broadcast correctly against the input array.
3362
3363 If the default value is passed, then `keepdims` will not be
3364 passed through to the `prod` method of sub-classes of
3365 `ndarray`, however any non-default value will be. If the
3366 sub-class' method does not implement `keepdims` any
3367 exceptions will be raised.
3368 initial : scalar, optional
3369 The starting value for this product. See `~numpy.ufunc.reduce`
3370 for details.
3371 where : array_like of bool, optional
3372 Elements to include in the product. See `~numpy.ufunc.reduce`
3373 for details.
3374
3375 Returns
3376 -------
3377 product_along_axis : ndarray, see `dtype` parameter above.
3378 An array shaped as `a` but with the specified axis removed.
3379 Returns a reference to `out` if specified.
3380
3381 See Also
3382 --------
3383 ndarray.prod : equivalent method
3384 :ref:`ufuncs-output-type`
3385
3386 Notes
3387 -----
3388 Arithmetic is modular when using integer types, and no error is
3389 raised on overflow. That means that, on a 32-bit platform:
3390
3391 >>> x = np.array([536870910, 536870910, 536870910, 536870910])
3392 >>> np.prod(x)
3393 16 # may vary
3394
3395 The product of an empty array is the neutral element 1:
3396
3397 >>> np.prod([])
3398 1.0
3399
3400 Examples
3401 --------
3402 By default, calculate the product of all elements:
3403
3404 >>> import numpy as np
3405 >>> np.prod([1.,2.])
3406 2.0
3407
3408 Even when the input array is two-dimensional:
3409
3410 >>> a = np.array([[1., 2.], [3., 4.]])
3411 >>> np.prod(a)
3412 24.0
3413
3414 But we can also specify the axis over which to multiply:
3415
3416 >>> np.prod(a, axis=1)
3417 array([ 2., 12.])
3418 >>> np.prod(a, axis=0)
3419 array([3., 8.])
3420
3421 Or select specific elements to include:
3422
3423 >>> np.prod([1., np.nan, 3.], where=[True, False, True])
3424 3.0
3425
3426 If the type of `x` is unsigned, then the output type is
3427 the unsigned platform integer:
3428
3429 >>> x = np.array([1, 2, 3], dtype=np.uint8)
3430 >>> np.prod(x).dtype == np.uint
3431 True
3432
3433 If `x` is of a signed integer type, then the output type
3434 is the default platform integer:
3435
3436 >>> x = np.array([1, 2, 3], dtype=np.int8)
3437 >>> np.prod(x).dtype == int
3438 True
3439
3440 You can also start the product with a value other than one:
3441
3442 >>> np.prod([1, 2], initial=5)
3443 10
3444 """
3445 return _wrapreduction(a, np.multiply, 'prod', axis, dtype, out,
3446 keepdims=keepdims, initial=initial, where=where)
3447
3448
3449def _cumprod_dispatcher(a, axis=None, dtype=None, out=None):
3450 return (a, out)
3451
3452
3453@array_function_dispatch(_cumprod_dispatcher)
3454def cumprod(a, axis=None, dtype=None, out=None):
3455 """
3456 Return the cumulative product of elements along a given axis.
3457
3458 Parameters
3459 ----------
3460 a : array_like
3461 Input array.
3462 axis : int, optional
3463 Axis along which the cumulative product is computed. By default
3464 the input is flattened.
3465 dtype : dtype, optional
3466 Type of the returned array, as well as of the accumulator in which
3467 the elements are multiplied. If *dtype* is not specified, it
3468 defaults to the dtype of `a`, unless `a` has an integer dtype with
3469 a precision less than that of the default platform integer. In
3470 that case, the default platform integer is used instead.
3471 out : ndarray, optional
3472 Alternative output array in which to place the result. It must
3473 have the same shape and buffer length as the expected output
3474 but the type of the resulting values will be cast if necessary.
3475
3476 Returns
3477 -------
3478 cumprod : ndarray
3479 A new array holding the result is returned unless `out` is
3480 specified, in which case a reference to out is returned.
3481
3482 See Also
3483 --------
3484 cumulative_prod : Array API compatible alternative for ``cumprod``.
3485 :ref:`ufuncs-output-type`
3486
3487 Notes
3488 -----
3489 Arithmetic is modular when using integer types, and no error is
3490 raised on overflow.
3491
3492 Examples
3493 --------
3494 >>> import numpy as np
3495 >>> a = np.array([1,2,3])
3496 >>> np.cumprod(a) # intermediate results 1, 1*2
3497 ... # total product 1*2*3 = 6
3498 array([1, 2, 6])
3499 >>> a = np.array([[1, 2, 3], [4, 5, 6]])
3500 >>> np.cumprod(a, dtype=float) # specify type of output
3501 array([ 1., 2., 6., 24., 120., 720.])
3502
3503 The cumulative product for each column (i.e., over the rows) of `a`:
3504
3505 >>> np.cumprod(a, axis=0)
3506 array([[ 1, 2, 3],
3507 [ 4, 10, 18]])
3508
3509 The cumulative product for each row (i.e. over the columns) of `a`:
3510
3511 >>> np.cumprod(a,axis=1)
3512 array([[ 1, 2, 6],
3513 [ 4, 20, 120]])
3514
3515 """
3516 return _wrapfunc(a, 'cumprod', axis=axis, dtype=dtype, out=out)
3517
3518
3519def _ndim_dispatcher(a):
3520 return (a,)
3521
3522
3523@array_function_dispatch(_ndim_dispatcher)
3524def ndim(a):
3525 """
3526 Return the number of dimensions of an array.
3527
3528 Parameters
3529 ----------
3530 a : array_like
3531 Input array. If it is not already an ndarray, a conversion is
3532 attempted.
3533
3534 Returns
3535 -------
3536 number_of_dimensions : int
3537 The number of dimensions in `a`. Scalars are zero-dimensional.
3538
3539 See Also
3540 --------
3541 ndarray.ndim : equivalent method
3542 shape : dimensions of array
3543 ndarray.shape : dimensions of array
3544
3545 Examples
3546 --------
3547 >>> import numpy as np
3548 >>> np.ndim([[1,2,3],[4,5,6]])
3549 2
3550 >>> np.ndim(np.array([[1,2,3],[4,5,6]]))
3551 2
3552 >>> np.ndim(1)
3553 0
3554
3555 """
3556 try:
3557 return a.ndim
3558 except AttributeError:
3559 return asarray(a).ndim
3560
3561
3562def _size_dispatcher(a, axis=None):
3563 return (a,)
3564
3565
3566@array_function_dispatch(_size_dispatcher)
3567def size(a, axis=None):
3568 """
3569 Return the number of elements along a given axis.
3570
3571 Parameters
3572 ----------
3573 a : array_like
3574 Input data.
3575 axis : int, optional
3576 Axis along which the elements are counted. By default, give
3577 the total number of elements.
3578
3579 Returns
3580 -------
3581 element_count : int
3582 Number of elements along the specified axis.
3583
3584 See Also
3585 --------
3586 shape : dimensions of array
3587 ndarray.shape : dimensions of array
3588 ndarray.size : number of elements in array
3589
3590 Examples
3591 --------
3592 >>> import numpy as np
3593 >>> a = np.array([[1,2,3],[4,5,6]])
3594 >>> np.size(a)
3595 6
3596 >>> np.size(a,1)
3597 3
3598 >>> np.size(a,0)
3599 2
3600
3601 """
3602 if axis is None:
3603 try:
3604 return a.size
3605 except AttributeError:
3606 return asarray(a).size
3607 else:
3608 try:
3609 return a.shape[axis]
3610 except AttributeError:
3611 return asarray(a).shape[axis]
3612
3613
3614def _round_dispatcher(a, decimals=None, out=None):
3615 return (a, out)
3616
3617
3618@array_function_dispatch(_round_dispatcher)
3619def round(a, decimals=0, out=None):
3620 """
3621 Evenly round to the given number of decimals.
3622
3623 Parameters
3624 ----------
3625 a : array_like
3626 Input data.
3627 decimals : int, optional
3628 Number of decimal places to round to (default: 0). If
3629 decimals is negative, it specifies the number of positions to
3630 the left of the decimal point.
3631 out : ndarray, optional
3632 Alternative output array in which to place the result. It must have
3633 the same shape as the expected output, but the type of the output
3634 values will be cast if necessary. See :ref:`ufuncs-output-type`
3635 for more details.
3636
3637 Returns
3638 -------
3639 rounded_array : ndarray
3640 An array of the same type as `a`, containing the rounded values.
3641 Unless `out` was specified, a new array is created. A reference to
3642 the result is returned.
3643
3644 The real and imaginary parts of complex numbers are rounded
3645 separately. The result of rounding a float is a float.
3646
3647 See Also
3648 --------
3649 ndarray.round : equivalent method
3650 around : an alias for this function
3651 ceil, fix, floor, rint, trunc
3652
3653
3654 Notes
3655 -----
3656 For values exactly halfway between rounded decimal values, NumPy
3657 rounds to the nearest even value. Thus 1.5 and 2.5 round to 2.0,
3658 -0.5 and 0.5 round to 0.0, etc.
3659
3660 ``np.round`` uses a fast but sometimes inexact algorithm to round
3661 floating-point datatypes. For positive `decimals` it is equivalent to
3662 ``np.true_divide(np.rint(a * 10**decimals), 10**decimals)``, which has
3663 error due to the inexact representation of decimal fractions in the IEEE
3664 floating point standard [1]_ and errors introduced when scaling by powers
3665 of ten. For instance, note the extra "1" in the following:
3666
3667 >>> np.round(56294995342131.5, 3)
3668 56294995342131.51
3669
3670 If your goal is to print such values with a fixed number of decimals, it is
3671 preferable to use numpy's float printing routines to limit the number of
3672 printed decimals:
3673
3674 >>> np.format_float_positional(56294995342131.5, precision=3)
3675 '56294995342131.5'
3676
3677 The float printing routines use an accurate but much more computationally
3678 demanding algorithm to compute the number of digits after the decimal
3679 point.
3680
3681 Alternatively, Python's builtin `round` function uses a more accurate
3682 but slower algorithm for 64-bit floating point values:
3683
3684 >>> round(56294995342131.5, 3)
3685 56294995342131.5
3686 >>> np.round(16.055, 2), round(16.055, 2) # equals 16.0549999999999997
3687 (16.06, 16.05)
3688
3689
3690 References
3691 ----------
3692 .. [1] "Lecture Notes on the Status of IEEE 754", William Kahan,
3693 https://people.eecs.berkeley.edu/~wkahan/ieee754status/IEEE754.PDF
3694
3695 Examples
3696 --------
3697 >>> import numpy as np
3698 >>> np.round([0.37, 1.64])
3699 array([0., 2.])
3700 >>> np.round([0.37, 1.64], decimals=1)
3701 array([0.4, 1.6])
3702 >>> np.round([.5, 1.5, 2.5, 3.5, 4.5]) # rounds to nearest even value
3703 array([0., 2., 2., 4., 4.])
3704 >>> np.round([1,2,3,11], decimals=1) # ndarray of ints is returned
3705 array([ 1, 2, 3, 11])
3706 >>> np.round([1,2,3,11], decimals=-1)
3707 array([ 0, 0, 0, 10])
3708
3709 """
3710 return _wrapfunc(a, 'round', decimals=decimals, out=out)
3711
3712
3713@array_function_dispatch(_round_dispatcher)
3714def around(a, decimals=0, out=None):
3715 """
3716 Round an array to the given number of decimals.
3717
3718 `around` is an alias of `~numpy.round`.
3719
3720 See Also
3721 --------
3722 ndarray.round : equivalent method
3723 round : alias for this function
3724 ceil, fix, floor, rint, trunc
3725
3726 """
3727 return _wrapfunc(a, 'round', decimals=decimals, out=out)
3728
3729
3730def _mean_dispatcher(a, axis=None, dtype=None, out=None, keepdims=None, *,
3731 where=None):
3732 return (a, where, out)
3733
3734
3735@array_function_dispatch(_mean_dispatcher)
3736def mean(a, axis=None, dtype=None, out=None, keepdims=np._NoValue, *,
3737 where=np._NoValue):
3738 """
3739 Compute the arithmetic mean along the specified axis.
3740
3741 Returns the average of the array elements. The average is taken over
3742 the flattened array by default, otherwise over the specified axis.
3743 `float64` intermediate and return values are used for integer inputs.
3744
3745 Parameters
3746 ----------
3747 a : array_like
3748 Array containing numbers whose mean is desired. If `a` is not an
3749 array, a conversion is attempted.
3750 axis : None or int or tuple of ints, optional
3751 Axis or axes along which the means are computed. The default is to
3752 compute the mean of the flattened array.
3753
3754 If this is a tuple of ints, a mean is performed over multiple axes,
3755 instead of a single axis or all the axes as before.
3756 dtype : data-type, optional
3757 Type to use in computing the mean. For integer inputs, the default
3758 is `float64`; for floating point inputs, it is the same as the
3759 input dtype.
3760 out : ndarray, optional
3761 Alternate output array in which to place the result. The default
3762 is ``None``; if provided, it must have the same shape as the
3763 expected output, but the type will be cast if necessary.
3764 See :ref:`ufuncs-output-type` for more details.
3765 See :ref:`ufuncs-output-type` for more details.
3766
3767 keepdims : bool, optional
3768 If this is set to True, the axes which are reduced are left
3769 in the result as dimensions with size one. With this option,
3770 the result will broadcast correctly against the input array.
3771
3772 If the default value is passed, then `keepdims` will not be
3773 passed through to the `mean` method of sub-classes of
3774 `ndarray`, however any non-default value will be. If the
3775 sub-class' method does not implement `keepdims` any
3776 exceptions will be raised.
3777
3778 where : array_like of bool, optional
3779 Elements to include in the mean. See `~numpy.ufunc.reduce` for details.
3780
3781 .. versionadded:: 1.20.0
3782
3783 Returns
3784 -------
3785 m : ndarray, see dtype parameter above
3786 If `out=None`, returns a new array containing the mean values,
3787 otherwise a reference to the output array is returned.
3788
3789 See Also
3790 --------
3791 average : Weighted average
3792 std, var, nanmean, nanstd, nanvar
3793
3794 Notes
3795 -----
3796 The arithmetic mean is the sum of the elements along the axis divided
3797 by the number of elements.
3798
3799 Note that for floating-point input, the mean is computed using the
3800 same precision the input has. Depending on the input data, this can
3801 cause the results to be inaccurate, especially for `float32` (see
3802 example below). Specifying a higher-precision accumulator using the
3803 `dtype` keyword can alleviate this issue.
3804
3805 By default, `float16` results are computed using `float32` intermediates
3806 for extra precision.
3807
3808 Examples
3809 --------
3810 >>> import numpy as np
3811 >>> a = np.array([[1, 2], [3, 4]])
3812 >>> np.mean(a)
3813 2.5
3814 >>> np.mean(a, axis=0)
3815 array([2., 3.])
3816 >>> np.mean(a, axis=1)
3817 array([1.5, 3.5])
3818
3819 In single precision, `mean` can be inaccurate:
3820
3821 >>> a = np.zeros((2, 512*512), dtype=np.float32)
3822 >>> a[0, :] = 1.0
3823 >>> a[1, :] = 0.1
3824 >>> np.mean(a)
3825 np.float32(0.54999924)
3826
3827 Computing the mean in float64 is more accurate:
3828
3829 >>> np.mean(a, dtype=np.float64)
3830 0.55000000074505806 # may vary
3831
3832 Computing the mean in timedelta64 is available:
3833
3834 >>> b = np.array([1, 3], dtype="timedelta64[D]")
3835 >>> np.mean(b)
3836 np.timedelta64(2,'D')
3837
3838 Specifying a where argument:
3839
3840 >>> a = np.array([[5, 9, 13], [14, 10, 12], [11, 15, 19]])
3841 >>> np.mean(a)
3842 12.0
3843 >>> np.mean(a, where=[[True], [False], [False]])
3844 9.0
3845
3846 """
3847 kwargs = {}
3848 if keepdims is not np._NoValue:
3849 kwargs['keepdims'] = keepdims
3850 if where is not np._NoValue:
3851 kwargs['where'] = where
3852 if type(a) is not mu.ndarray:
3853 try:
3854 mean = a.mean
3855 except AttributeError:
3856 pass
3857 else:
3858 return mean(axis=axis, dtype=dtype, out=out, **kwargs)
3859
3860 return _methods._mean(a, axis=axis, dtype=dtype,
3861 out=out, **kwargs)
3862
3863
3864def _std_dispatcher(a, axis=None, dtype=None, out=None, ddof=None,
3865 keepdims=None, *, where=None, mean=None, correction=None):
3866 return (a, where, out, mean)
3867
3868
3869@array_function_dispatch(_std_dispatcher)
3870def std(a, axis=None, dtype=None, out=None, ddof=0, keepdims=np._NoValue, *,
3871 where=np._NoValue, mean=np._NoValue, correction=np._NoValue):
3872 r"""
3873 Compute the standard deviation along the specified axis.
3874
3875 Returns the standard deviation, a measure of the spread of a distribution,
3876 of the array elements. The standard deviation is computed for the
3877 flattened array by default, otherwise over the specified axis.
3878
3879 Parameters
3880 ----------
3881 a : array_like
3882 Calculate the standard deviation of these values.
3883 axis : None or int or tuple of ints, optional
3884 Axis or axes along which the standard deviation is computed. The
3885 default is to compute the standard deviation of the flattened array.
3886 If this is a tuple of ints, a standard deviation is performed over
3887 multiple axes, instead of a single axis or all the axes as before.
3888 dtype : dtype, optional
3889 Type to use in computing the standard deviation. For arrays of
3890 integer type the default is float64, for arrays of float types it is
3891 the same as the array type.
3892 out : ndarray, optional
3893 Alternative output array in which to place the result. It must have
3894 the same shape as the expected output but the type (of the calculated
3895 values) will be cast if necessary.
3896 See :ref:`ufuncs-output-type` for more details.
3897 ddof : {int, float}, optional
3898 Means Delta Degrees of Freedom. The divisor used in calculations
3899 is ``N - ddof``, where ``N`` represents the number of elements.
3900 By default `ddof` is zero. See Notes for details about use of `ddof`.
3901 keepdims : bool, optional
3902 If this is set to True, the axes which are reduced are left
3903 in the result as dimensions with size one. With this option,
3904 the result will broadcast correctly against the input array.
3905
3906 If the default value is passed, then `keepdims` will not be
3907 passed through to the `std` method of sub-classes of
3908 `ndarray`, however any non-default value will be. If the
3909 sub-class' method does not implement `keepdims` any
3910 exceptions will be raised.
3911 where : array_like of bool, optional
3912 Elements to include in the standard deviation.
3913 See `~numpy.ufunc.reduce` for details.
3914
3915 .. versionadded:: 1.20.0
3916
3917 mean : array_like, optional
3918 Provide the mean to prevent its recalculation. The mean should have
3919 a shape as if it was calculated with ``keepdims=True``.
3920 The axis for the calculation of the mean should be the same as used in
3921 the call to this std function.
3922
3923 .. versionadded:: 2.0.0
3924
3925 correction : {int, float}, optional
3926 Array API compatible name for the ``ddof`` parameter. Only one of them
3927 can be provided at the same time.
3928
3929 .. versionadded:: 2.0.0
3930
3931 Returns
3932 -------
3933 standard_deviation : ndarray, see dtype parameter above.
3934 If `out` is None, return a new array containing the standard deviation,
3935 otherwise return a reference to the output array.
3936
3937 See Also
3938 --------
3939 var, mean, nanmean, nanstd, nanvar
3940 :ref:`ufuncs-output-type`
3941
3942 Notes
3943 -----
3944 There are several common variants of the array standard deviation
3945 calculation. Assuming the input `a` is a one-dimensional NumPy array
3946 and ``mean`` is either provided as an argument or computed as
3947 ``a.mean()``, NumPy computes the standard deviation of an array as::
3948
3949 N = len(a)
3950 d2 = abs(a - mean)**2 # abs is for complex `a`
3951 var = d2.sum() / (N - ddof) # note use of `ddof`
3952 std = var**0.5
3953
3954 Different values of the argument `ddof` are useful in different
3955 contexts. NumPy's default ``ddof=0`` corresponds with the expression:
3956
3957 .. math::
3958
3959 \sqrt{\frac{\sum_i{|a_i - \bar{a}|^2 }}{N}}
3960
3961 which is sometimes called the "population standard deviation" in the field
3962 of statistics because it applies the definition of standard deviation to
3963 `a` as if `a` were a complete population of possible observations.
3964
3965 Many other libraries define the standard deviation of an array
3966 differently, e.g.:
3967
3968 .. math::
3969
3970 \sqrt{\frac{\sum_i{|a_i - \bar{a}|^2 }}{N - 1}}
3971
3972 In statistics, the resulting quantity is sometimes called the "sample
3973 standard deviation" because if `a` is a random sample from a larger
3974 population, this calculation provides the square root of an unbiased
3975 estimate of the variance of the population. The use of :math:`N-1` in the
3976 denominator is often called "Bessel's correction" because it corrects for
3977 bias (toward lower values) in the variance estimate introduced when the
3978 sample mean of `a` is used in place of the true mean of the population.
3979 The resulting estimate of the standard deviation is still biased, but less
3980 than it would have been without the correction. For this quantity, use
3981 ``ddof=1``.
3982
3983 Note that, for complex numbers, `std` takes the absolute
3984 value before squaring, so that the result is always real and nonnegative.
3985
3986 For floating-point input, the standard deviation is computed using the same
3987 precision the input has. Depending on the input data, this can cause
3988 the results to be inaccurate, especially for float32 (see example below).
3989 Specifying a higher-accuracy accumulator using the `dtype` keyword can
3990 alleviate this issue.
3991
3992 Examples
3993 --------
3994 >>> import numpy as np
3995 >>> a = np.array([[1, 2], [3, 4]])
3996 >>> np.std(a)
3997 1.1180339887498949 # may vary
3998 >>> np.std(a, axis=0)
3999 array([1., 1.])
4000 >>> np.std(a, axis=1)
4001 array([0.5, 0.5])
4002
4003 In single precision, std() can be inaccurate:
4004
4005 >>> a = np.zeros((2, 512*512), dtype=np.float32)
4006 >>> a[0, :] = 1.0
4007 >>> a[1, :] = 0.1
4008 >>> np.std(a)
4009 np.float32(0.45000005)
4010
4011 Computing the standard deviation in float64 is more accurate:
4012
4013 >>> np.std(a, dtype=np.float64)
4014 0.44999999925494177 # may vary
4015
4016 Specifying a where argument:
4017
4018 >>> a = np.array([[14, 8, 11, 10], [7, 9, 10, 11], [10, 15, 5, 10]])
4019 >>> np.std(a)
4020 2.614064523559687 # may vary
4021 >>> np.std(a, where=[[True], [True], [False]])
4022 2.0
4023
4024 Using the mean keyword to save computation time:
4025
4026 >>> import numpy as np
4027 >>> from timeit import timeit
4028 >>> a = np.array([[14, 8, 11, 10], [7, 9, 10, 11], [10, 15, 5, 10]])
4029 >>> mean = np.mean(a, axis=1, keepdims=True)
4030 >>>
4031 >>> g = globals()
4032 >>> n = 10000
4033 >>> t1 = timeit("std = np.std(a, axis=1, mean=mean)", globals=g, number=n)
4034 >>> t2 = timeit("std = np.std(a, axis=1)", globals=g, number=n)
4035 >>> print(f'Percentage execution time saved {100*(t2-t1)/t2:.0f}%')
4036 #doctest: +SKIP
4037 Percentage execution time saved 30%
4038
4039 """
4040 kwargs = {}
4041 if keepdims is not np._NoValue:
4042 kwargs['keepdims'] = keepdims
4043 if where is not np._NoValue:
4044 kwargs['where'] = where
4045 if mean is not np._NoValue:
4046 kwargs['mean'] = mean
4047
4048 if correction != np._NoValue:
4049 if ddof != 0:
4050 raise ValueError(
4051 "ddof and correction can't be provided simultaneously."
4052 )
4053 else:
4054 ddof = correction
4055
4056 if type(a) is not mu.ndarray:
4057 try:
4058 std = a.std
4059 except AttributeError:
4060 pass
4061 else:
4062 return std(axis=axis, dtype=dtype, out=out, ddof=ddof, **kwargs)
4063
4064 return _methods._std(a, axis=axis, dtype=dtype, out=out, ddof=ddof,
4065 **kwargs)
4066
4067
4068def _var_dispatcher(a, axis=None, dtype=None, out=None, ddof=None,
4069 keepdims=None, *, where=None, mean=None, correction=None):
4070 return (a, where, out, mean)
4071
4072
4073@array_function_dispatch(_var_dispatcher)
4074def var(a, axis=None, dtype=None, out=None, ddof=0, keepdims=np._NoValue, *,
4075 where=np._NoValue, mean=np._NoValue, correction=np._NoValue):
4076 r"""
4077 Compute the variance along the specified axis.
4078
4079 Returns the variance of the array elements, a measure of the spread of a
4080 distribution. The variance is computed for the flattened array by
4081 default, otherwise over the specified axis.
4082
4083 Parameters
4084 ----------
4085 a : array_like
4086 Array containing numbers whose variance is desired. If `a` is not an
4087 array, a conversion is attempted.
4088 axis : None or int or tuple of ints, optional
4089 Axis or axes along which the variance is computed. The default is to
4090 compute the variance of the flattened array.
4091 If this is a tuple of ints, a variance is performed over multiple axes,
4092 instead of a single axis or all the axes as before.
4093 dtype : data-type, optional
4094 Type to use in computing the variance. For arrays of integer type
4095 the default is `float64`; for arrays of float types it is the same as
4096 the array type.
4097 out : ndarray, optional
4098 Alternate output array in which to place the result. It must have
4099 the same shape as the expected output, but the type is cast if
4100 necessary.
4101 ddof : {int, float}, optional
4102 "Delta Degrees of Freedom": the divisor used in the calculation is
4103 ``N - ddof``, where ``N`` represents the number of elements. By
4104 default `ddof` is zero. See notes for details about use of `ddof`.
4105 keepdims : bool, optional
4106 If this is set to True, the axes which are reduced are left
4107 in the result as dimensions with size one. With this option,
4108 the result will broadcast correctly against the input array.
4109
4110 If the default value is passed, then `keepdims` will not be
4111 passed through to the `var` method of sub-classes of
4112 `ndarray`, however any non-default value will be. If the
4113 sub-class' method does not implement `keepdims` any
4114 exceptions will be raised.
4115 where : array_like of bool, optional
4116 Elements to include in the variance. See `~numpy.ufunc.reduce` for
4117 details.
4118
4119 .. versionadded:: 1.20.0
4120
4121 mean : array like, optional
4122 Provide the mean to prevent its recalculation. The mean should have
4123 a shape as if it was calculated with ``keepdims=True``.
4124 The axis for the calculation of the mean should be the same as used in
4125 the call to this var function.
4126
4127 .. versionadded:: 2.0.0
4128
4129 correction : {int, float}, optional
4130 Array API compatible name for the ``ddof`` parameter. Only one of them
4131 can be provided at the same time.
4132
4133 .. versionadded:: 2.0.0
4134
4135 Returns
4136 -------
4137 variance : ndarray, see dtype parameter above
4138 If ``out=None``, returns a new array containing the variance;
4139 otherwise, a reference to the output array is returned.
4140
4141 See Also
4142 --------
4143 std, mean, nanmean, nanstd, nanvar
4144 :ref:`ufuncs-output-type`
4145
4146 Notes
4147 -----
4148 There are several common variants of the array variance calculation.
4149 Assuming the input `a` is a one-dimensional NumPy array and ``mean`` is
4150 either provided as an argument or computed as ``a.mean()``, NumPy
4151 computes the variance of an array as::
4152
4153 N = len(a)
4154 d2 = abs(a - mean)**2 # abs is for complex `a`
4155 var = d2.sum() / (N - ddof) # note use of `ddof`
4156
4157 Different values of the argument `ddof` are useful in different
4158 contexts. NumPy's default ``ddof=0`` corresponds with the expression:
4159
4160 .. math::
4161
4162 \frac{\sum_i{|a_i - \bar{a}|^2 }}{N}
4163
4164 which is sometimes called the "population variance" in the field of
4165 statistics because it applies the definition of variance to `a` as if `a`
4166 were a complete population of possible observations.
4167
4168 Many other libraries define the variance of an array differently, e.g.:
4169
4170 .. math::
4171
4172 \frac{\sum_i{|a_i - \bar{a}|^2}}{N - 1}
4173
4174 In statistics, the resulting quantity is sometimes called the "sample
4175 variance" because if `a` is a random sample from a larger population,
4176 this calculation provides an unbiased estimate of the variance of the
4177 population. The use of :math:`N-1` in the denominator is often called
4178 "Bessel's correction" because it corrects for bias (toward lower values)
4179 in the variance estimate introduced when the sample mean of `a` is used
4180 in place of the true mean of the population. For this quantity, use
4181 ``ddof=1``.
4182
4183 Note that for complex numbers, the absolute value is taken before
4184 squaring, so that the result is always real and nonnegative.
4185
4186 For floating-point input, the variance is computed using the same
4187 precision the input has. Depending on the input data, this can cause
4188 the results to be inaccurate, especially for `float32` (see example
4189 below). Specifying a higher-accuracy accumulator using the ``dtype``
4190 keyword can alleviate this issue.
4191
4192 Examples
4193 --------
4194 >>> import numpy as np
4195 >>> a = np.array([[1, 2], [3, 4]])
4196 >>> np.var(a)
4197 1.25
4198 >>> np.var(a, axis=0)
4199 array([1., 1.])
4200 >>> np.var(a, axis=1)
4201 array([0.25, 0.25])
4202
4203 In single precision, var() can be inaccurate:
4204
4205 >>> a = np.zeros((2, 512*512), dtype=np.float32)
4206 >>> a[0, :] = 1.0
4207 >>> a[1, :] = 0.1
4208 >>> np.var(a)
4209 np.float32(0.20250003)
4210
4211 Computing the variance in float64 is more accurate:
4212
4213 >>> np.var(a, dtype=np.float64)
4214 0.20249999932944759 # may vary
4215 >>> ((1-0.55)**2 + (0.1-0.55)**2)/2
4216 0.2025
4217
4218 Specifying a where argument:
4219
4220 >>> a = np.array([[14, 8, 11, 10], [7, 9, 10, 11], [10, 15, 5, 10]])
4221 >>> np.var(a)
4222 6.833333333333333 # may vary
4223 >>> np.var(a, where=[[True], [True], [False]])
4224 4.0
4225
4226 Using the mean keyword to save computation time:
4227
4228 >>> import numpy as np
4229 >>> from timeit import timeit
4230 >>>
4231 >>> a = np.array([[14, 8, 11, 10], [7, 9, 10, 11], [10, 15, 5, 10]])
4232 >>> mean = np.mean(a, axis=1, keepdims=True)
4233 >>>
4234 >>> g = globals()
4235 >>> n = 10000
4236 >>> t1 = timeit("var = np.var(a, axis=1, mean=mean)", globals=g, number=n)
4237 >>> t2 = timeit("var = np.var(a, axis=1)", globals=g, number=n)
4238 >>> print(f'Percentage execution time saved {100*(t2-t1)/t2:.0f}%')
4239 #doctest: +SKIP
4240 Percentage execution time saved 32%
4241
4242 """
4243 kwargs = {}
4244 if keepdims is not np._NoValue:
4245 kwargs['keepdims'] = keepdims
4246 if where is not np._NoValue:
4247 kwargs['where'] = where
4248 if mean is not np._NoValue:
4249 kwargs['mean'] = mean
4250
4251 if correction != np._NoValue:
4252 if ddof != 0:
4253 raise ValueError(
4254 "ddof and correction can't be provided simultaneously."
4255 )
4256 else:
4257 ddof = correction
4258
4259 if type(a) is not mu.ndarray:
4260 try:
4261 var = a.var
4262
4263 except AttributeError:
4264 pass
4265 else:
4266 return var(axis=axis, dtype=dtype, out=out, ddof=ddof, **kwargs)
4267
4268 return _methods._var(a, axis=axis, dtype=dtype, out=out, ddof=ddof,
4269 **kwargs)