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