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