Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.9/dist-packages/numpy/core/fromnumeric.py: 41%
382 statements
« prev ^ index » next coverage.py v7.4.4, created at 2024-04-03 06:39 +0000
« prev ^ index » next coverage.py v7.4.4, created at 2024-04-03 06:39 +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 . import _methods
17_dt_ = nt.sctype2char
19# functions that are methods
20__all__ = [
21 'all', 'alltrue', 'amax', 'amin', 'any', 'argmax',
22 'argmin', 'argpartition', 'argsort', 'around', 'choose', 'clip',
23 'compress', 'cumprod', 'cumproduct', 'cumsum', 'diagonal', 'mean',
24 'max', 'min',
25 'ndim', 'nonzero', 'partition', 'prod', 'product', 'ptp', 'put',
26 'ravel', 'repeat', 'reshape', 'resize', 'round', 'round_',
27 'searchsorted', 'shape', 'size', 'sometrue', 'sort', 'squeeze',
28 'std', 'sum', 'swapaxes', 'take', 'trace', 'transpose', 'var',
29]
31_gentype = types.GeneratorType
32# save away Python sum
33_sum_ = sum
35array_function_dispatch = functools.partial(
36 overrides.array_function_dispatch, module='numpy')
39# functions that are now methods
40def _wrapit(obj, method, *args, **kwds):
41 try:
42 wrap = obj.__array_wrap__
43 except AttributeError:
44 wrap = None
45 result = getattr(asarray(obj), method)(*args, **kwds)
46 if wrap:
47 if not isinstance(result, mu.ndarray):
48 result = asarray(result)
49 result = wrap(result)
50 return result
53def _wrapfunc(obj, method, *args, **kwds):
54 bound = getattr(obj, method, None)
55 if bound is None:
56 return _wrapit(obj, method, *args, **kwds)
58 try:
59 return bound(*args, **kwds)
60 except TypeError:
61 # A TypeError occurs if the object does have such a method in its
62 # class, but its signature is not identical to that of NumPy's. This
63 # situation has occurred in the case of a downstream library like
64 # 'pandas'.
65 #
66 # Call _wrapit from within the except clause to ensure a potential
67 # exception has a traceback chain.
68 return _wrapit(obj, method, *args, **kwds)
71def _wrapreduction(obj, ufunc, method, axis, dtype, out, **kwargs):
72 passkwargs = {k: v for k, v in kwargs.items()
73 if v is not np._NoValue}
75 if type(obj) is not mu.ndarray:
76 try:
77 reduction = getattr(obj, method)
78 except AttributeError:
79 pass
80 else:
81 # This branch is needed for reductions like any which don't
82 # support a dtype.
83 if dtype is not None:
84 return reduction(axis=axis, dtype=dtype, out=out, **passkwargs)
85 else:
86 return reduction(axis=axis, out=out, **passkwargs)
88 return ufunc.reduce(obj, axis, dtype, out, **passkwargs)
91def _take_dispatcher(a, indices, axis=None, out=None, mode=None):
92 return (a, out)
95@array_function_dispatch(_take_dispatcher)
96def take(a, indices, axis=None, out=None, mode='raise'):
97 """
98 Take elements from an array along an axis.
100 When axis is not None, this function does the same thing as "fancy"
101 indexing (indexing arrays using arrays); however, it can be easier to use
102 if you need elements along a given axis. A call such as
103 ``np.take(arr, indices, axis=3)`` is equivalent to
104 ``arr[:,:,:,indices,...]``.
106 Explained without fancy indexing, this is equivalent to the following use
107 of `ndindex`, which sets each of ``ii``, ``jj``, and ``kk`` to a tuple of
108 indices::
110 Ni, Nk = a.shape[:axis], a.shape[axis+1:]
111 Nj = indices.shape
112 for ii in ndindex(Ni):
113 for jj in ndindex(Nj):
114 for kk in ndindex(Nk):
115 out[ii + jj + kk] = a[ii + (indices[jj],) + kk]
117 Parameters
118 ----------
119 a : array_like (Ni..., M, Nk...)
120 The source array.
121 indices : array_like (Nj...)
122 The indices of the values to extract.
124 .. versionadded:: 1.8.0
126 Also allow scalars for indices.
127 axis : int, optional
128 The axis over which to select values. By default, the flattened
129 input array is used.
130 out : ndarray, optional (Ni..., Nj..., Nk...)
131 If provided, the result will be placed in this array. It should
132 be of the appropriate shape and dtype. Note that `out` is always
133 buffered if `mode='raise'`; use other modes for better performance.
134 mode : {'raise', 'wrap', 'clip'}, optional
135 Specifies how out-of-bounds indices will behave.
137 * 'raise' -- raise an error (default)
138 * 'wrap' -- wrap around
139 * 'clip' -- clip to the range
141 'clip' mode means that all indices that are too large are replaced
142 by the index that addresses the last element along that axis. Note
143 that this disables indexing with negative numbers.
145 Returns
146 -------
147 out : ndarray (Ni..., Nj..., Nk...)
148 The returned array has the same type as `a`.
150 See Also
151 --------
152 compress : Take elements using a boolean mask
153 ndarray.take : equivalent method
154 take_along_axis : Take elements by matching the array and the index arrays
156 Notes
157 -----
159 By eliminating the inner loop in the description above, and using `s_` to
160 build simple slice objects, `take` can be expressed in terms of applying
161 fancy indexing to each 1-d slice::
163 Ni, Nk = a.shape[:axis], a.shape[axis+1:]
164 for ii in ndindex(Ni):
165 for kk in ndindex(Nj):
166 out[ii + s_[...,] + kk] = a[ii + s_[:,] + kk][indices]
168 For this reason, it is equivalent to (but faster than) the following use
169 of `apply_along_axis`::
171 out = np.apply_along_axis(lambda a_1d: a_1d[indices], axis, a)
173 Examples
174 --------
175 >>> a = [4, 3, 5, 7, 6, 8]
176 >>> indices = [0, 1, 4]
177 >>> np.take(a, indices)
178 array([4, 3, 6])
180 In this example if `a` is an ndarray, "fancy" indexing can be used.
182 >>> a = np.array(a)
183 >>> a[indices]
184 array([4, 3, 6])
186 If `indices` is not one dimensional, the output also has these dimensions.
188 >>> np.take(a, [[0, 1], [2, 3]])
189 array([[4, 3],
190 [5, 7]])
191 """
192 return _wrapfunc(a, 'take', indices, axis=axis, out=out, mode=mode)
195def _reshape_dispatcher(a, newshape, order=None):
196 return (a,)
199# not deprecated --- copy if necessary, view otherwise
200@array_function_dispatch(_reshape_dispatcher)
201def reshape(a, newshape, order='C'):
202 """
203 Gives a new shape to an array without changing its data.
205 Parameters
206 ----------
207 a : array_like
208 Array to be reshaped.
209 newshape : int or tuple of ints
210 The new shape should be compatible with the original shape. If
211 an integer, then the result will be a 1-D array of that length.
212 One shape dimension can be -1. In this case, the value is
213 inferred from the length of the array and remaining dimensions.
214 order : {'C', 'F', 'A'}, optional
215 Read the elements of `a` using this index order, and place the
216 elements into the reshaped array using this index order. 'C'
217 means to read / write the elements using C-like index order,
218 with the last axis index changing fastest, back to the first
219 axis index changing slowest. 'F' means to read / write the
220 elements using Fortran-like index order, with the first index
221 changing fastest, and the last index changing slowest. Note that
222 the 'C' and 'F' options take no account of the memory layout of
223 the underlying array, and only refer to the order of indexing.
224 'A' means to read / write the elements in Fortran-like index
225 order if `a` is Fortran *contiguous* in memory, C-like order
226 otherwise.
228 Returns
229 -------
230 reshaped_array : ndarray
231 This will be a new view object if possible; otherwise, it will
232 be a copy. Note there is no guarantee of the *memory layout* (C- or
233 Fortran- contiguous) of the returned array.
235 See Also
236 --------
237 ndarray.reshape : Equivalent method.
239 Notes
240 -----
241 It is not always possible to change the shape of an array without copying
242 the data.
244 The `order` keyword gives the index ordering both for *fetching* the values
245 from `a`, and then *placing* the values into the output array.
246 For example, let's say you have an array:
248 >>> a = np.arange(6).reshape((3, 2))
249 >>> a
250 array([[0, 1],
251 [2, 3],
252 [4, 5]])
254 You can think of reshaping as first raveling the array (using the given
255 index order), then inserting the elements from the raveled array into the
256 new array using the same kind of index ordering as was used for the
257 raveling.
259 >>> np.reshape(a, (2, 3)) # C-like index ordering
260 array([[0, 1, 2],
261 [3, 4, 5]])
262 >>> np.reshape(np.ravel(a), (2, 3)) # equivalent to C ravel then C reshape
263 array([[0, 1, 2],
264 [3, 4, 5]])
265 >>> np.reshape(a, (2, 3), order='F') # Fortran-like index ordering
266 array([[0, 4, 3],
267 [2, 1, 5]])
268 >>> np.reshape(np.ravel(a, order='F'), (2, 3), order='F')
269 array([[0, 4, 3],
270 [2, 1, 5]])
272 Examples
273 --------
274 >>> a = np.array([[1,2,3], [4,5,6]])
275 >>> np.reshape(a, 6)
276 array([1, 2, 3, 4, 5, 6])
277 >>> np.reshape(a, 6, order='F')
278 array([1, 4, 2, 5, 3, 6])
280 >>> np.reshape(a, (3,-1)) # the unspecified value is inferred to be 2
281 array([[1, 2],
282 [3, 4],
283 [5, 6]])
284 """
285 return _wrapfunc(a, 'reshape', newshape, order=order)
288def _choose_dispatcher(a, choices, out=None, mode=None):
289 yield a
290 yield from choices
291 yield out
294@array_function_dispatch(_choose_dispatcher)
295def choose(a, choices, out=None, mode='raise'):
296 """
297 Construct an array from an index array and a list of arrays to choose from.
299 First of all, if confused or uncertain, definitely look at the Examples -
300 in its full generality, this function is less simple than it might
301 seem from the following code description (below ndi =
302 `numpy.lib.index_tricks`):
304 ``np.choose(a,c) == np.array([c[a[I]][I] for I in ndi.ndindex(a.shape)])``.
306 But this omits some subtleties. Here is a fully general summary:
308 Given an "index" array (`a`) of integers and a sequence of ``n`` arrays
309 (`choices`), `a` and each choice array are first broadcast, as necessary,
310 to arrays of a common shape; calling these *Ba* and *Bchoices[i], i =
311 0,...,n-1* we have that, necessarily, ``Ba.shape == Bchoices[i].shape``
312 for each ``i``. Then, a new array with shape ``Ba.shape`` is created as
313 follows:
315 * if ``mode='raise'`` (the default), then, first of all, each element of
316 ``a`` (and thus ``Ba``) must be in the range ``[0, n-1]``; now, suppose
317 that ``i`` (in that range) is the value at the ``(j0, j1, ..., jm)``
318 position in ``Ba`` - then the value at the same position in the new array
319 is the value in ``Bchoices[i]`` at that same position;
321 * if ``mode='wrap'``, values in `a` (and thus `Ba`) may be any (signed)
322 integer; modular arithmetic is used to map integers outside the range
323 `[0, n-1]` back into that range; and then the new array is constructed
324 as above;
326 * if ``mode='clip'``, values in `a` (and thus ``Ba``) may be any (signed)
327 integer; negative integers are mapped to 0; values greater than ``n-1``
328 are mapped to ``n-1``; and then the new array is constructed as above.
330 Parameters
331 ----------
332 a : int array
333 This array must contain integers in ``[0, n-1]``, where ``n`` is the
334 number of choices, unless ``mode=wrap`` or ``mode=clip``, in which
335 cases any integers are permissible.
336 choices : sequence of arrays
337 Choice arrays. `a` and all of the choices must be broadcastable to the
338 same shape. If `choices` is itself an array (not recommended), then
339 its outermost dimension (i.e., the one corresponding to
340 ``choices.shape[0]``) is taken as defining the "sequence".
341 out : array, optional
342 If provided, the result will be inserted into this array. It should
343 be of the appropriate shape and dtype. Note that `out` is always
344 buffered if ``mode='raise'``; use other modes for better performance.
345 mode : {'raise' (default), 'wrap', 'clip'}, optional
346 Specifies how indices outside ``[0, n-1]`` will be treated:
348 * 'raise' : an exception is raised
349 * 'wrap' : value becomes value mod ``n``
350 * 'clip' : values < 0 are mapped to 0, values > n-1 are mapped to n-1
352 Returns
353 -------
354 merged_array : array
355 The merged result.
357 Raises
358 ------
359 ValueError: shape mismatch
360 If `a` and each choice array are not all broadcastable to the same
361 shape.
363 See Also
364 --------
365 ndarray.choose : equivalent method
366 numpy.take_along_axis : Preferable if `choices` is an array
368 Notes
369 -----
370 To reduce the chance of misinterpretation, even though the following
371 "abuse" is nominally supported, `choices` should neither be, nor be
372 thought of as, a single array, i.e., the outermost sequence-like container
373 should be either a list or a tuple.
375 Examples
376 --------
378 >>> choices = [[0, 1, 2, 3], [10, 11, 12, 13],
379 ... [20, 21, 22, 23], [30, 31, 32, 33]]
380 >>> np.choose([2, 3, 1, 0], choices
381 ... # the first element of the result will be the first element of the
382 ... # third (2+1) "array" in choices, namely, 20; the second element
383 ... # will be the second element of the fourth (3+1) choice array, i.e.,
384 ... # 31, etc.
385 ... )
386 array([20, 31, 12, 3])
387 >>> np.choose([2, 4, 1, 0], choices, mode='clip') # 4 goes to 3 (4-1)
388 array([20, 31, 12, 3])
389 >>> # because there are 4 choice arrays
390 >>> np.choose([2, 4, 1, 0], choices, mode='wrap') # 4 goes to (4 mod 4)
391 array([20, 1, 12, 3])
392 >>> # i.e., 0
394 A couple examples illustrating how choose broadcasts:
396 >>> a = [[1, 0, 1], [0, 1, 0], [1, 0, 1]]
397 >>> choices = [-10, 10]
398 >>> np.choose(a, choices)
399 array([[ 10, -10, 10],
400 [-10, 10, -10],
401 [ 10, -10, 10]])
403 >>> # With thanks to Anne Archibald
404 >>> a = np.array([0, 1]).reshape((2,1,1))
405 >>> c1 = np.array([1, 2, 3]).reshape((1,3,1))
406 >>> c2 = np.array([-1, -2, -3, -4, -5]).reshape((1,1,5))
407 >>> np.choose(a, (c1, c2)) # result is 2x3x5, res[0,:,:]=c1, res[1,:,:]=c2
408 array([[[ 1, 1, 1, 1, 1],
409 [ 2, 2, 2, 2, 2],
410 [ 3, 3, 3, 3, 3]],
411 [[-1, -2, -3, -4, -5],
412 [-1, -2, -3, -4, -5],
413 [-1, -2, -3, -4, -5]]])
415 """
416 return _wrapfunc(a, 'choose', choices, out=out, mode=mode)
419def _repeat_dispatcher(a, repeats, axis=None):
420 return (a,)
423@array_function_dispatch(_repeat_dispatcher)
424def repeat(a, repeats, axis=None):
425 """
426 Repeat each element of an array after themselves
428 Parameters
429 ----------
430 a : array_like
431 Input array.
432 repeats : int or array of ints
433 The number of repetitions for each element. `repeats` is broadcasted
434 to fit the shape of the given axis.
435 axis : int, optional
436 The axis along which to repeat values. By default, use the
437 flattened input array, and return a flat output array.
439 Returns
440 -------
441 repeated_array : ndarray
442 Output array which has the same shape as `a`, except along
443 the given axis.
445 See Also
446 --------
447 tile : Tile an array.
448 unique : Find the unique elements of an array.
450 Examples
451 --------
452 >>> np.repeat(3, 4)
453 array([3, 3, 3, 3])
454 >>> x = np.array([[1,2],[3,4]])
455 >>> np.repeat(x, 2)
456 array([1, 1, 2, 2, 3, 3, 4, 4])
457 >>> np.repeat(x, 3, axis=1)
458 array([[1, 1, 1, 2, 2, 2],
459 [3, 3, 3, 4, 4, 4]])
460 >>> np.repeat(x, [1, 2], axis=0)
461 array([[1, 2],
462 [3, 4],
463 [3, 4]])
465 """
466 return _wrapfunc(a, 'repeat', repeats, axis=axis)
469def _put_dispatcher(a, ind, v, mode=None):
470 return (a, ind, v)
473@array_function_dispatch(_put_dispatcher)
474def put(a, ind, v, mode='raise'):
475 """
476 Replaces specified elements of an array with given values.
478 The indexing works on the flattened target array. `put` is roughly
479 equivalent to:
481 ::
483 a.flat[ind] = v
485 Parameters
486 ----------
487 a : ndarray
488 Target array.
489 ind : array_like
490 Target indices, interpreted as integers.
491 v : array_like
492 Values to place in `a` at target indices. If `v` is shorter than
493 `ind` it will be repeated as necessary.
494 mode : {'raise', 'wrap', 'clip'}, optional
495 Specifies how out-of-bounds indices will behave.
497 * 'raise' -- raise an error (default)
498 * 'wrap' -- wrap around
499 * 'clip' -- clip to the range
501 'clip' mode means that all indices that are too large are replaced
502 by the index that addresses the last element along that axis. Note
503 that this disables indexing with negative numbers. In 'raise' mode,
504 if an exception occurs the target array may still be modified.
506 See Also
507 --------
508 putmask, place
509 put_along_axis : Put elements by matching the array and the index arrays
511 Examples
512 --------
513 >>> a = np.arange(5)
514 >>> np.put(a, [0, 2], [-44, -55])
515 >>> a
516 array([-44, 1, -55, 3, 4])
518 >>> a = np.arange(5)
519 >>> np.put(a, 22, -5, mode='clip')
520 >>> a
521 array([ 0, 1, 2, 3, -5])
523 """
524 try:
525 put = a.put
526 except AttributeError as e:
527 raise TypeError("argument 1 must be numpy.ndarray, "
528 "not {name}".format(name=type(a).__name__)) from e
530 return put(ind, v, mode=mode)
533def _swapaxes_dispatcher(a, axis1, axis2):
534 return (a,)
537@array_function_dispatch(_swapaxes_dispatcher)
538def swapaxes(a, axis1, axis2):
539 """
540 Interchange two axes of an array.
542 Parameters
543 ----------
544 a : array_like
545 Input array.
546 axis1 : int
547 First axis.
548 axis2 : int
549 Second axis.
551 Returns
552 -------
553 a_swapped : ndarray
554 For NumPy >= 1.10.0, if `a` is an ndarray, then a view of `a` is
555 returned; otherwise a new array is created. For earlier NumPy
556 versions a view of `a` is returned only if the order of the
557 axes is changed, otherwise the input array is returned.
559 Examples
560 --------
561 >>> x = np.array([[1,2,3]])
562 >>> np.swapaxes(x,0,1)
563 array([[1],
564 [2],
565 [3]])
567 >>> x = np.array([[[0,1],[2,3]],[[4,5],[6,7]]])
568 >>> x
569 array([[[0, 1],
570 [2, 3]],
571 [[4, 5],
572 [6, 7]]])
574 >>> np.swapaxes(x,0,2)
575 array([[[0, 4],
576 [2, 6]],
577 [[1, 5],
578 [3, 7]]])
580 """
581 return _wrapfunc(a, 'swapaxes', axis1, axis2)
584def _transpose_dispatcher(a, axes=None):
585 return (a,)
588@array_function_dispatch(_transpose_dispatcher)
589def transpose(a, axes=None):
590 """
591 Returns an array with axes transposed.
593 For a 1-D array, this returns an unchanged view of the original array, as a
594 transposed vector is simply the same vector.
595 To convert a 1-D array into a 2-D column vector, an additional dimension
596 must be added, e.g., ``np.atleast2d(a).T`` achieves this, as does
597 ``a[:, np.newaxis]``.
598 For a 2-D array, this is the standard matrix transpose.
599 For an n-D array, if axes are given, their order indicates how the
600 axes are permuted (see Examples). If axes are not provided, then
601 ``transpose(a).shape == a.shape[::-1]``.
603 Parameters
604 ----------
605 a : array_like
606 Input array.
607 axes : tuple or list of ints, optional
608 If specified, it must be a tuple or list which contains a permutation
609 of [0,1,...,N-1] where N is the number of axes of `a`. The `i`'th axis
610 of the returned array will correspond to the axis numbered ``axes[i]``
611 of the input. If not specified, defaults to ``range(a.ndim)[::-1]``,
612 which reverses the order of the axes.
614 Returns
615 -------
616 p : ndarray
617 `a` with its axes permuted. A view is returned whenever possible.
619 See Also
620 --------
621 ndarray.transpose : Equivalent method.
622 moveaxis : Move axes of an array to new positions.
623 argsort : Return the indices that would sort an array.
625 Notes
626 -----
627 Use ``transpose(a, argsort(axes))`` to invert the transposition of tensors
628 when using the `axes` keyword argument.
630 Examples
631 --------
632 >>> a = np.array([[1, 2], [3, 4]])
633 >>> a
634 array([[1, 2],
635 [3, 4]])
636 >>> np.transpose(a)
637 array([[1, 3],
638 [2, 4]])
640 >>> a = np.array([1, 2, 3, 4])
641 >>> a
642 array([1, 2, 3, 4])
643 >>> np.transpose(a)
644 array([1, 2, 3, 4])
646 >>> a = np.ones((1, 2, 3))
647 >>> np.transpose(a, (1, 0, 2)).shape
648 (2, 1, 3)
650 >>> a = np.ones((2, 3, 4, 5))
651 >>> np.transpose(a).shape
652 (5, 4, 3, 2)
654 """
655 return _wrapfunc(a, 'transpose', axes)
658def _partition_dispatcher(a, kth, axis=None, kind=None, order=None):
659 return (a,)
662@array_function_dispatch(_partition_dispatcher)
663def partition(a, kth, axis=-1, kind='introselect', order=None):
664 """
665 Return a partitioned copy of an array.
667 Creates a copy of the array with its elements rearranged in such a
668 way that the value of the element in k-th position is in the position
669 the value would be in a sorted array. In the partitioned array, all
670 elements before the k-th element are less than or equal to that
671 element, and all the elements after the k-th element are greater than
672 or equal to that element. The ordering of the elements in the two
673 partitions is undefined.
675 .. versionadded:: 1.8.0
677 Parameters
678 ----------
679 a : array_like
680 Array to be sorted.
681 kth : int or sequence of ints
682 Element index to partition by. The k-th value of the element
683 will be in its final sorted position and all smaller elements
684 will be moved before it and all equal or greater elements behind
685 it. The order of all elements in the partitions is undefined. If
686 provided with a sequence of k-th it will partition all elements
687 indexed by k-th of them into their sorted position at once.
689 .. deprecated:: 1.22.0
690 Passing booleans as index is deprecated.
691 axis : int or None, optional
692 Axis along which to sort. If None, the array is flattened before
693 sorting. The default is -1, which sorts along the last axis.
694 kind : {'introselect'}, optional
695 Selection algorithm. Default is 'introselect'.
696 order : str or list of str, optional
697 When `a` is an array with fields defined, this argument
698 specifies which fields to compare first, second, etc. A single
699 field can be specified as a string. Not all fields need be
700 specified, but unspecified fields will still be used, in the
701 order in which they come up in the dtype, to break ties.
703 Returns
704 -------
705 partitioned_array : ndarray
706 Array of the same type and shape as `a`.
708 See Also
709 --------
710 ndarray.partition : Method to sort an array in-place.
711 argpartition : Indirect partition.
712 sort : Full sorting
714 Notes
715 -----
716 The various selection algorithms are characterized by their average
717 speed, worst case performance, work space size, and whether they are
718 stable. A stable sort keeps items with the same key in the same
719 relative order. The available algorithms have the following
720 properties:
722 ================= ======= ============= ============ =======
723 kind speed worst case work space stable
724 ================= ======= ============= ============ =======
725 'introselect' 1 O(n) 0 no
726 ================= ======= ============= ============ =======
728 All the partition algorithms make temporary copies of the data when
729 partitioning along any but the last axis. Consequently,
730 partitioning along the last axis is faster and uses less space than
731 partitioning along any other axis.
733 The sort order for complex numbers is lexicographic. If both the
734 real and imaginary parts are non-nan then the order is determined by
735 the real parts except when they are equal, in which case the order
736 is determined by the imaginary parts.
738 Examples
739 --------
740 >>> a = np.array([7, 1, 7, 7, 1, 5, 7, 2, 3, 2, 6, 2, 3, 0])
741 >>> p = np.partition(a, 4)
742 >>> p
743 array([0, 1, 2, 1, 2, 5, 2, 3, 3, 6, 7, 7, 7, 7])
745 ``p[4]`` is 2; all elements in ``p[:4]`` are less than or equal
746 to ``p[4]``, and all elements in ``p[5:]`` are greater than or
747 equal to ``p[4]``. The partition is::
749 [0, 1, 2, 1], [2], [5, 2, 3, 3, 6, 7, 7, 7, 7]
751 The next example shows the use of multiple values passed to `kth`.
753 >>> p2 = np.partition(a, (4, 8))
754 >>> p2
755 array([0, 1, 2, 1, 2, 3, 3, 2, 5, 6, 7, 7, 7, 7])
757 ``p2[4]`` is 2 and ``p2[8]`` is 5. All elements in ``p2[:4]``
758 are less than or equal to ``p2[4]``, all elements in ``p2[5:8]``
759 are greater than or equal to ``p2[4]`` and less than or equal to
760 ``p2[8]``, and all elements in ``p2[9:]`` are greater than or
761 equal to ``p2[8]``. The partition is::
763 [0, 1, 2, 1], [2], [3, 3, 2], [5], [6, 7, 7, 7, 7]
764 """
765 if axis is None:
766 # flatten returns (1, N) for np.matrix, so always use the last axis
767 a = asanyarray(a).flatten()
768 axis = -1
769 else:
770 a = asanyarray(a).copy(order="K")
771 a.partition(kth, axis=axis, kind=kind, order=order)
772 return a
775def _argpartition_dispatcher(a, kth, axis=None, kind=None, order=None):
776 return (a,)
779@array_function_dispatch(_argpartition_dispatcher)
780def argpartition(a, kth, axis=-1, kind='introselect', order=None):
781 """
782 Perform an indirect partition along the given axis using the
783 algorithm specified by the `kind` keyword. It returns an array of
784 indices of the same shape as `a` that index data along the given
785 axis in partitioned order.
787 .. versionadded:: 1.8.0
789 Parameters
790 ----------
791 a : array_like
792 Array to sort.
793 kth : int or sequence of ints
794 Element index to partition by. The k-th element will be in its
795 final sorted position and all smaller elements will be moved
796 before it and all larger elements behind it. The order of all
797 elements in the partitions is undefined. If provided with a
798 sequence of k-th it will partition all of them into their sorted
799 position at once.
801 .. deprecated:: 1.22.0
802 Passing booleans as index is deprecated.
803 axis : int or None, optional
804 Axis along which to sort. The default is -1 (the last axis). If
805 None, the flattened array is used.
806 kind : {'introselect'}, optional
807 Selection algorithm. Default is 'introselect'
808 order : str or list of str, optional
809 When `a` is an array with fields defined, this argument
810 specifies which fields to compare first, second, etc. A single
811 field can be specified as a string, and not all fields need be
812 specified, but unspecified fields will still be used, in the
813 order in which they come up in the dtype, to break ties.
815 Returns
816 -------
817 index_array : ndarray, int
818 Array of indices that partition `a` along the specified axis.
819 If `a` is one-dimensional, ``a[index_array]`` yields a partitioned `a`.
820 More generally, ``np.take_along_axis(a, index_array, axis=axis)``
821 always yields the partitioned `a`, irrespective of dimensionality.
823 See Also
824 --------
825 partition : Describes partition algorithms used.
826 ndarray.partition : Inplace partition.
827 argsort : Full indirect sort.
828 take_along_axis : Apply ``index_array`` from argpartition
829 to an array as if by calling partition.
831 Notes
832 -----
833 See `partition` for notes on the different selection algorithms.
835 Examples
836 --------
837 One dimensional array:
839 >>> x = np.array([3, 4, 2, 1])
840 >>> x[np.argpartition(x, 3)]
841 array([2, 1, 3, 4])
842 >>> x[np.argpartition(x, (1, 3))]
843 array([1, 2, 3, 4])
845 >>> x = [3, 4, 2, 1]
846 >>> np.array(x)[np.argpartition(x, 3)]
847 array([2, 1, 3, 4])
849 Multi-dimensional array:
851 >>> x = np.array([[3, 4, 2], [1, 3, 1]])
852 >>> index_array = np.argpartition(x, kth=1, axis=-1)
853 >>> np.take_along_axis(x, index_array, axis=-1) # same as np.partition(x, kth=1)
854 array([[2, 3, 4],
855 [1, 1, 3]])
857 """
858 return _wrapfunc(a, 'argpartition', kth, axis=axis, kind=kind, order=order)
861def _sort_dispatcher(a, axis=None, kind=None, order=None):
862 return (a,)
865@array_function_dispatch(_sort_dispatcher)
866def sort(a, axis=-1, kind=None, order=None):
867 """
868 Return a sorted copy of an array.
870 Parameters
871 ----------
872 a : array_like
873 Array to be sorted.
874 axis : int or None, optional
875 Axis along which to sort. If None, the array is flattened before
876 sorting. The default is -1, which sorts along the last axis.
877 kind : {'quicksort', 'mergesort', 'heapsort', 'stable'}, optional
878 Sorting algorithm. The default is 'quicksort'. Note that both 'stable'
879 and 'mergesort' use timsort or radix sort under the covers and, in general,
880 the actual implementation will vary with data type. The 'mergesort' option
881 is retained for backwards compatibility.
883 .. versionchanged:: 1.15.0.
884 The 'stable' option was added.
886 order : str or list of str, optional
887 When `a` is an array with fields defined, this argument specifies
888 which fields to compare first, second, etc. A single field can
889 be specified as a string, and not all fields need be specified,
890 but unspecified fields will still be used, in the order in which
891 they come up in the dtype, to break ties.
893 Returns
894 -------
895 sorted_array : ndarray
896 Array of the same type and shape as `a`.
898 See Also
899 --------
900 ndarray.sort : Method to sort an array in-place.
901 argsort : Indirect sort.
902 lexsort : Indirect stable sort on multiple keys.
903 searchsorted : Find elements in a sorted array.
904 partition : Partial sort.
906 Notes
907 -----
908 The various sorting algorithms are characterized by their average speed,
909 worst case performance, work space size, and whether they are stable. A
910 stable sort keeps items with the same key in the same relative
911 order. The four algorithms implemented in NumPy have the following
912 properties:
914 =========== ======= ============= ============ ========
915 kind speed worst case work space stable
916 =========== ======= ============= ============ ========
917 'quicksort' 1 O(n^2) 0 no
918 'heapsort' 3 O(n*log(n)) 0 no
919 'mergesort' 2 O(n*log(n)) ~n/2 yes
920 'timsort' 2 O(n*log(n)) ~n/2 yes
921 =========== ======= ============= ============ ========
923 .. note:: The datatype determines which of 'mergesort' or 'timsort'
924 is actually used, even if 'mergesort' is specified. User selection
925 at a finer scale is not currently available.
927 All the sort algorithms make temporary copies of the data when
928 sorting along any but the last axis. Consequently, sorting along
929 the last axis is faster and uses less space than sorting along
930 any other axis.
932 The sort order for complex numbers is lexicographic. If both the real
933 and imaginary parts are non-nan then the order is determined by the
934 real parts except when they are equal, in which case the order is
935 determined by the imaginary parts.
937 Previous to numpy 1.4.0 sorting real and complex arrays containing nan
938 values led to undefined behaviour. In numpy versions >= 1.4.0 nan
939 values are sorted to the end. The extended sort order is:
941 * Real: [R, nan]
942 * Complex: [R + Rj, R + nanj, nan + Rj, nan + nanj]
944 where R is a non-nan real value. Complex values with the same nan
945 placements are sorted according to the non-nan part if it exists.
946 Non-nan values are sorted as before.
948 .. versionadded:: 1.12.0
950 quicksort has been changed to `introsort <https://en.wikipedia.org/wiki/Introsort>`_.
951 When sorting does not make enough progress it switches to
952 `heapsort <https://en.wikipedia.org/wiki/Heapsort>`_.
953 This implementation makes quicksort O(n*log(n)) in the worst case.
955 'stable' automatically chooses the best stable sorting algorithm
956 for the data type being sorted.
957 It, along with 'mergesort' is currently mapped to
958 `timsort <https://en.wikipedia.org/wiki/Timsort>`_
959 or `radix sort <https://en.wikipedia.org/wiki/Radix_sort>`_
960 depending on the data type.
961 API forward compatibility currently limits the
962 ability to select the implementation and it is hardwired for the different
963 data types.
965 .. versionadded:: 1.17.0
967 Timsort is added for better performance on already or nearly
968 sorted data. On random data timsort is almost identical to
969 mergesort. It is now used for stable sort while quicksort is still the
970 default sort if none is chosen. For timsort details, refer to
971 `CPython listsort.txt <https://github.com/python/cpython/blob/3.7/Objects/listsort.txt>`_.
972 'mergesort' and 'stable' are mapped to radix sort for integer data types. Radix sort is an
973 O(n) sort instead of O(n log n).
975 .. versionchanged:: 1.18.0
977 NaT now sorts to the end of arrays for consistency with NaN.
979 Examples
980 --------
981 >>> a = np.array([[1,4],[3,1]])
982 >>> np.sort(a) # sort along the last axis
983 array([[1, 4],
984 [1, 3]])
985 >>> np.sort(a, axis=None) # sort the flattened array
986 array([1, 1, 3, 4])
987 >>> np.sort(a, axis=0) # sort along the first axis
988 array([[1, 1],
989 [3, 4]])
991 Use the `order` keyword to specify a field to use when sorting a
992 structured array:
994 >>> dtype = [('name', 'S10'), ('height', float), ('age', int)]
995 >>> values = [('Arthur', 1.8, 41), ('Lancelot', 1.9, 38),
996 ... ('Galahad', 1.7, 38)]
997 >>> a = np.array(values, dtype=dtype) # create a structured array
998 >>> np.sort(a, order='height') # doctest: +SKIP
999 array([('Galahad', 1.7, 38), ('Arthur', 1.8, 41),
1000 ('Lancelot', 1.8999999999999999, 38)],
1001 dtype=[('name', '|S10'), ('height', '<f8'), ('age', '<i4')])
1003 Sort by age, then height if ages are equal:
1005 >>> np.sort(a, order=['age', 'height']) # doctest: +SKIP
1006 array([('Galahad', 1.7, 38), ('Lancelot', 1.8999999999999999, 38),
1007 ('Arthur', 1.8, 41)],
1008 dtype=[('name', '|S10'), ('height', '<f8'), ('age', '<i4')])
1010 """
1011 if axis is None:
1012 # flatten returns (1, N) for np.matrix, so always use the last axis
1013 a = asanyarray(a).flatten()
1014 axis = -1
1015 else:
1016 a = asanyarray(a).copy(order="K")
1017 a.sort(axis=axis, kind=kind, order=order)
1018 return a
1021def _argsort_dispatcher(a, axis=None, kind=None, order=None):
1022 return (a,)
1025@array_function_dispatch(_argsort_dispatcher)
1026def argsort(a, axis=-1, kind=None, order=None):
1027 """
1028 Returns the indices that would sort an array.
1030 Perform an indirect sort along the given axis using the algorithm specified
1031 by the `kind` keyword. It returns an array of indices of the same shape as
1032 `a` that index data along the given axis in sorted order.
1034 Parameters
1035 ----------
1036 a : array_like
1037 Array to sort.
1038 axis : int or None, optional
1039 Axis along which to sort. The default is -1 (the last axis). If None,
1040 the flattened array is used.
1041 kind : {'quicksort', 'mergesort', 'heapsort', 'stable'}, optional
1042 Sorting algorithm. The default is 'quicksort'. Note that both 'stable'
1043 and 'mergesort' use timsort under the covers and, in general, the
1044 actual implementation will vary with data type. The 'mergesort' option
1045 is retained for backwards compatibility.
1047 .. versionchanged:: 1.15.0.
1048 The 'stable' option was added.
1049 order : str or list of str, optional
1050 When `a` is an array with fields defined, this argument specifies
1051 which fields to compare first, second, etc. A single field can
1052 be specified as a string, and not all fields need be specified,
1053 but unspecified fields will still be used, in the order in which
1054 they come up in the dtype, to break ties.
1056 Returns
1057 -------
1058 index_array : ndarray, int
1059 Array of indices that sort `a` along the specified `axis`.
1060 If `a` is one-dimensional, ``a[index_array]`` yields a sorted `a`.
1061 More generally, ``np.take_along_axis(a, index_array, axis=axis)``
1062 always yields the sorted `a`, irrespective of dimensionality.
1064 See Also
1065 --------
1066 sort : Describes sorting algorithms used.
1067 lexsort : Indirect stable sort with multiple keys.
1068 ndarray.sort : Inplace sort.
1069 argpartition : Indirect partial sort.
1070 take_along_axis : Apply ``index_array`` from argsort
1071 to an array as if by calling sort.
1073 Notes
1074 -----
1075 See `sort` for notes on the different sorting algorithms.
1077 As of NumPy 1.4.0 `argsort` works with real/complex arrays containing
1078 nan values. The enhanced sort order is documented in `sort`.
1080 Examples
1081 --------
1082 One dimensional array:
1084 >>> x = np.array([3, 1, 2])
1085 >>> np.argsort(x)
1086 array([1, 2, 0])
1088 Two-dimensional array:
1090 >>> x = np.array([[0, 3], [2, 2]])
1091 >>> x
1092 array([[0, 3],
1093 [2, 2]])
1095 >>> ind = np.argsort(x, axis=0) # sorts along first axis (down)
1096 >>> ind
1097 array([[0, 1],
1098 [1, 0]])
1099 >>> np.take_along_axis(x, ind, axis=0) # same as np.sort(x, axis=0)
1100 array([[0, 2],
1101 [2, 3]])
1103 >>> ind = np.argsort(x, axis=1) # sorts along last axis (across)
1104 >>> ind
1105 array([[0, 1],
1106 [0, 1]])
1107 >>> np.take_along_axis(x, ind, axis=1) # same as np.sort(x, axis=1)
1108 array([[0, 3],
1109 [2, 2]])
1111 Indices of the sorted elements of a N-dimensional array:
1113 >>> ind = np.unravel_index(np.argsort(x, axis=None), x.shape)
1114 >>> ind
1115 (array([0, 1, 1, 0]), array([0, 0, 1, 1]))
1116 >>> x[ind] # same as np.sort(x, axis=None)
1117 array([0, 2, 2, 3])
1119 Sorting with keys:
1121 >>> x = np.array([(1, 0), (0, 1)], dtype=[('x', '<i4'), ('y', '<i4')])
1122 >>> x
1123 array([(1, 0), (0, 1)],
1124 dtype=[('x', '<i4'), ('y', '<i4')])
1126 >>> np.argsort(x, order=('x','y'))
1127 array([1, 0])
1129 >>> np.argsort(x, order=('y','x'))
1130 array([0, 1])
1132 """
1133 return _wrapfunc(a, 'argsort', axis=axis, kind=kind, order=order)
1136def _argmax_dispatcher(a, axis=None, out=None, *, keepdims=np._NoValue):
1137 return (a, out)
1140@array_function_dispatch(_argmax_dispatcher)
1141def argmax(a, axis=None, out=None, *, keepdims=np._NoValue):
1142 """
1143 Returns the indices of the maximum values along an axis.
1145 Parameters
1146 ----------
1147 a : array_like
1148 Input array.
1149 axis : int, optional
1150 By default, the index is into the flattened array, otherwise
1151 along the specified axis.
1152 out : array, optional
1153 If provided, the result will be inserted into this array. It should
1154 be of the appropriate shape and dtype.
1155 keepdims : bool, optional
1156 If this is set to True, the axes which are reduced are left
1157 in the result as dimensions with size one. With this option,
1158 the result will broadcast correctly against the array.
1160 .. versionadded:: 1.22.0
1162 Returns
1163 -------
1164 index_array : ndarray of ints
1165 Array of indices into the array. It has the same shape as `a.shape`
1166 with the dimension along `axis` removed. If `keepdims` is set to True,
1167 then the size of `axis` will be 1 with the resulting array having same
1168 shape as `a.shape`.
1170 See Also
1171 --------
1172 ndarray.argmax, argmin
1173 amax : The maximum value along a given axis.
1174 unravel_index : Convert a flat index into an index tuple.
1175 take_along_axis : Apply ``np.expand_dims(index_array, axis)``
1176 from argmax to an array as if by calling max.
1178 Notes
1179 -----
1180 In case of multiple occurrences of the maximum values, the indices
1181 corresponding to the first occurrence are returned.
1183 Examples
1184 --------
1185 >>> a = np.arange(6).reshape(2,3) + 10
1186 >>> a
1187 array([[10, 11, 12],
1188 [13, 14, 15]])
1189 >>> np.argmax(a)
1190 5
1191 >>> np.argmax(a, axis=0)
1192 array([1, 1, 1])
1193 >>> np.argmax(a, axis=1)
1194 array([2, 2])
1196 Indexes of the maximal elements of a N-dimensional array:
1198 >>> ind = np.unravel_index(np.argmax(a, axis=None), a.shape)
1199 >>> ind
1200 (1, 2)
1201 >>> a[ind]
1202 15
1204 >>> b = np.arange(6)
1205 >>> b[1] = 5
1206 >>> b
1207 array([0, 5, 2, 3, 4, 5])
1208 >>> np.argmax(b) # Only the first occurrence is returned.
1209 1
1211 >>> x = np.array([[4,2,3], [1,0,3]])
1212 >>> index_array = np.argmax(x, axis=-1)
1213 >>> # Same as np.amax(x, axis=-1, keepdims=True)
1214 >>> np.take_along_axis(x, np.expand_dims(index_array, axis=-1), axis=-1)
1215 array([[4],
1216 [3]])
1217 >>> # Same as np.amax(x, axis=-1)
1218 >>> np.take_along_axis(x, np.expand_dims(index_array, axis=-1), axis=-1).squeeze(axis=-1)
1219 array([4, 3])
1221 Setting `keepdims` to `True`,
1223 >>> x = np.arange(24).reshape((2, 3, 4))
1224 >>> res = np.argmax(x, axis=1, keepdims=True)
1225 >>> res.shape
1226 (2, 1, 4)
1227 """
1228 kwds = {'keepdims': keepdims} if keepdims is not np._NoValue else {}
1229 return _wrapfunc(a, 'argmax', axis=axis, out=out, **kwds)
1232def _argmin_dispatcher(a, axis=None, out=None, *, keepdims=np._NoValue):
1233 return (a, out)
1236@array_function_dispatch(_argmin_dispatcher)
1237def argmin(a, axis=None, out=None, *, keepdims=np._NoValue):
1238 """
1239 Returns the indices of the minimum values along an axis.
1241 Parameters
1242 ----------
1243 a : array_like
1244 Input array.
1245 axis : int, optional
1246 By default, the index is into the flattened array, otherwise
1247 along the specified axis.
1248 out : array, optional
1249 If provided, the result will be inserted into this array. It should
1250 be of the appropriate shape and dtype.
1251 keepdims : bool, optional
1252 If this is set to True, the axes which are reduced are left
1253 in the result as dimensions with size one. With this option,
1254 the result will broadcast correctly against the array.
1256 .. versionadded:: 1.22.0
1258 Returns
1259 -------
1260 index_array : ndarray of ints
1261 Array of indices into the array. It has the same shape as `a.shape`
1262 with the dimension along `axis` removed. If `keepdims` is set to True,
1263 then the size of `axis` will be 1 with the resulting array having same
1264 shape as `a.shape`.
1266 See Also
1267 --------
1268 ndarray.argmin, argmax
1269 amin : The minimum value along a given axis.
1270 unravel_index : Convert a flat index into an index tuple.
1271 take_along_axis : Apply ``np.expand_dims(index_array, axis)``
1272 from argmin to an array as if by calling min.
1274 Notes
1275 -----
1276 In case of multiple occurrences of the minimum values, the indices
1277 corresponding to the first occurrence are returned.
1279 Examples
1280 --------
1281 >>> a = np.arange(6).reshape(2,3) + 10
1282 >>> a
1283 array([[10, 11, 12],
1284 [13, 14, 15]])
1285 >>> np.argmin(a)
1286 0
1287 >>> np.argmin(a, axis=0)
1288 array([0, 0, 0])
1289 >>> np.argmin(a, axis=1)
1290 array([0, 0])
1292 Indices of the minimum elements of a N-dimensional array:
1294 >>> ind = np.unravel_index(np.argmin(a, axis=None), a.shape)
1295 >>> ind
1296 (0, 0)
1297 >>> a[ind]
1298 10
1300 >>> b = np.arange(6) + 10
1301 >>> b[4] = 10
1302 >>> b
1303 array([10, 11, 12, 13, 10, 15])
1304 >>> np.argmin(b) # Only the first occurrence is returned.
1305 0
1307 >>> x = np.array([[4,2,3], [1,0,3]])
1308 >>> index_array = np.argmin(x, axis=-1)
1309 >>> # Same as np.amin(x, axis=-1, keepdims=True)
1310 >>> np.take_along_axis(x, np.expand_dims(index_array, axis=-1), axis=-1)
1311 array([[2],
1312 [0]])
1313 >>> # Same as np.amax(x, axis=-1)
1314 >>> np.take_along_axis(x, np.expand_dims(index_array, axis=-1), axis=-1).squeeze(axis=-1)
1315 array([2, 0])
1317 Setting `keepdims` to `True`,
1319 >>> x = np.arange(24).reshape((2, 3, 4))
1320 >>> res = np.argmin(x, axis=1, keepdims=True)
1321 >>> res.shape
1322 (2, 1, 4)
1323 """
1324 kwds = {'keepdims': keepdims} if keepdims is not np._NoValue else {}
1325 return _wrapfunc(a, 'argmin', axis=axis, out=out, **kwds)
1328def _searchsorted_dispatcher(a, v, side=None, sorter=None):
1329 return (a, v, sorter)
1332@array_function_dispatch(_searchsorted_dispatcher)
1333def searchsorted(a, v, side='left', sorter=None):
1334 """
1335 Find indices where elements should be inserted to maintain order.
1337 Find the indices into a sorted array `a` such that, if the
1338 corresponding elements in `v` were inserted before the indices, the
1339 order of `a` would be preserved.
1341 Assuming that `a` is sorted:
1343 ====== ============================
1344 `side` returned index `i` satisfies
1345 ====== ============================
1346 left ``a[i-1] < v <= a[i]``
1347 right ``a[i-1] <= v < a[i]``
1348 ====== ============================
1350 Parameters
1351 ----------
1352 a : 1-D array_like
1353 Input array. If `sorter` is None, then it must be sorted in
1354 ascending order, otherwise `sorter` must be an array of indices
1355 that sort it.
1356 v : array_like
1357 Values to insert into `a`.
1358 side : {'left', 'right'}, optional
1359 If 'left', the index of the first suitable location found is given.
1360 If 'right', return the last such index. If there is no suitable
1361 index, return either 0 or N (where N is the length of `a`).
1362 sorter : 1-D array_like, optional
1363 Optional array of integer indices that sort array a into ascending
1364 order. They are typically the result of argsort.
1366 .. versionadded:: 1.7.0
1368 Returns
1369 -------
1370 indices : int or array of ints
1371 Array of insertion points with the same shape as `v`,
1372 or an integer if `v` is a scalar.
1374 See Also
1375 --------
1376 sort : Return a sorted copy of an array.
1377 histogram : Produce histogram from 1-D data.
1379 Notes
1380 -----
1381 Binary search is used to find the required insertion points.
1383 As of NumPy 1.4.0 `searchsorted` works with real/complex arrays containing
1384 `nan` values. The enhanced sort order is documented in `sort`.
1386 This function uses the same algorithm as the builtin python `bisect.bisect_left`
1387 (``side='left'``) and `bisect.bisect_right` (``side='right'``) functions,
1388 which is also vectorized in the `v` argument.
1390 Examples
1391 --------
1392 >>> np.searchsorted([1,2,3,4,5], 3)
1393 2
1394 >>> np.searchsorted([1,2,3,4,5], 3, side='right')
1395 3
1396 >>> np.searchsorted([1,2,3,4,5], [-10, 10, 2, 3])
1397 array([0, 5, 1, 2])
1399 """
1400 return _wrapfunc(a, 'searchsorted', v, side=side, sorter=sorter)
1403def _resize_dispatcher(a, new_shape):
1404 return (a,)
1407@array_function_dispatch(_resize_dispatcher)
1408def resize(a, new_shape):
1409 """
1410 Return a new array with the specified shape.
1412 If the new array is larger than the original array, then the new
1413 array is filled with repeated copies of `a`. Note that this behavior
1414 is different from a.resize(new_shape) which fills with zeros instead
1415 of repeated copies of `a`.
1417 Parameters
1418 ----------
1419 a : array_like
1420 Array to be resized.
1422 new_shape : int or tuple of int
1423 Shape of resized array.
1425 Returns
1426 -------
1427 reshaped_array : ndarray
1428 The new array is formed from the data in the old array, repeated
1429 if necessary to fill out the required number of elements. The
1430 data are repeated iterating over the array in C-order.
1432 See Also
1433 --------
1434 numpy.reshape : Reshape an array without changing the total size.
1435 numpy.pad : Enlarge and pad an array.
1436 numpy.repeat : Repeat elements of an array.
1437 ndarray.resize : resize an array in-place.
1439 Notes
1440 -----
1441 When the total size of the array does not change `~numpy.reshape` should
1442 be used. In most other cases either indexing (to reduce the size)
1443 or padding (to increase the size) may be a more appropriate solution.
1445 Warning: This functionality does **not** consider axes separately,
1446 i.e. it does not apply interpolation/extrapolation.
1447 It fills the return array with the required number of elements, iterating
1448 over `a` in C-order, disregarding axes (and cycling back from the start if
1449 the new shape is larger). This functionality is therefore not suitable to
1450 resize images, or data where each axis represents a separate and distinct
1451 entity.
1453 Examples
1454 --------
1455 >>> a=np.array([[0,1],[2,3]])
1456 >>> np.resize(a,(2,3))
1457 array([[0, 1, 2],
1458 [3, 0, 1]])
1459 >>> np.resize(a,(1,4))
1460 array([[0, 1, 2, 3]])
1461 >>> np.resize(a,(2,4))
1462 array([[0, 1, 2, 3],
1463 [0, 1, 2, 3]])
1465 """
1466 if isinstance(new_shape, (int, nt.integer)):
1467 new_shape = (new_shape,)
1469 a = ravel(a)
1471 new_size = 1
1472 for dim_length in new_shape:
1473 new_size *= dim_length
1474 if dim_length < 0:
1475 raise ValueError('all elements of `new_shape` must be non-negative')
1477 if a.size == 0 or new_size == 0:
1478 # First case must zero fill. The second would have repeats == 0.
1479 return np.zeros_like(a, shape=new_shape)
1481 repeats = -(-new_size // a.size) # ceil division
1482 a = concatenate((a,) * repeats)[:new_size]
1484 return reshape(a, new_shape)
1487def _squeeze_dispatcher(a, axis=None):
1488 return (a,)
1491@array_function_dispatch(_squeeze_dispatcher)
1492def squeeze(a, axis=None):
1493 """
1494 Remove axes of length one from `a`.
1496 Parameters
1497 ----------
1498 a : array_like
1499 Input data.
1500 axis : None or int or tuple of ints, optional
1501 .. versionadded:: 1.7.0
1503 Selects a subset of the entries of length one in the
1504 shape. If an axis is selected with shape entry greater than
1505 one, an error is raised.
1507 Returns
1508 -------
1509 squeezed : ndarray
1510 The input array, but with all or a subset of the
1511 dimensions of length 1 removed. This is always `a` itself
1512 or a view into `a`. Note that if all axes are squeezed,
1513 the result is a 0d array and not a scalar.
1515 Raises
1516 ------
1517 ValueError
1518 If `axis` is not None, and an axis being squeezed is not of length 1
1520 See Also
1521 --------
1522 expand_dims : The inverse operation, adding entries of length one
1523 reshape : Insert, remove, and combine dimensions, and resize existing ones
1525 Examples
1526 --------
1527 >>> x = np.array([[[0], [1], [2]]])
1528 >>> x.shape
1529 (1, 3, 1)
1530 >>> np.squeeze(x).shape
1531 (3,)
1532 >>> np.squeeze(x, axis=0).shape
1533 (3, 1)
1534 >>> np.squeeze(x, axis=1).shape
1535 Traceback (most recent call last):
1536 ...
1537 ValueError: cannot select an axis to squeeze out which has size not equal to one
1538 >>> np.squeeze(x, axis=2).shape
1539 (1, 3)
1540 >>> x = np.array([[1234]])
1541 >>> x.shape
1542 (1, 1)
1543 >>> np.squeeze(x)
1544 array(1234) # 0d array
1545 >>> np.squeeze(x).shape
1546 ()
1547 >>> np.squeeze(x)[()]
1548 1234
1550 """
1551 try:
1552 squeeze = a.squeeze
1553 except AttributeError:
1554 return _wrapit(a, 'squeeze', axis=axis)
1555 if axis is None:
1556 return squeeze()
1557 else:
1558 return squeeze(axis=axis)
1561def _diagonal_dispatcher(a, offset=None, axis1=None, axis2=None):
1562 return (a,)
1565@array_function_dispatch(_diagonal_dispatcher)
1566def diagonal(a, offset=0, axis1=0, axis2=1):
1567 """
1568 Return specified diagonals.
1570 If `a` is 2-D, returns the diagonal of `a` with the given offset,
1571 i.e., the collection of elements of the form ``a[i, i+offset]``. If
1572 `a` has more than two dimensions, then the axes specified by `axis1`
1573 and `axis2` are used to determine the 2-D sub-array whose diagonal is
1574 returned. The shape of the resulting array can be determined by
1575 removing `axis1` and `axis2` and appending an index to the right equal
1576 to the size of the resulting diagonals.
1578 In versions of NumPy prior to 1.7, this function always returned a new,
1579 independent array containing a copy of the values in the diagonal.
1581 In NumPy 1.7 and 1.8, it continues to return a copy of the diagonal,
1582 but depending on this fact is deprecated. Writing to the resulting
1583 array continues to work as it used to, but a FutureWarning is issued.
1585 Starting in NumPy 1.9 it returns a read-only view on the original array.
1586 Attempting to write to the resulting array will produce an error.
1588 In some future release, it will return a read/write view and writing to
1589 the returned array will alter your original array. The returned array
1590 will have the same type as the input array.
1592 If you don't write to the array returned by this function, then you can
1593 just ignore all of the above.
1595 If you depend on the current behavior, then we suggest copying the
1596 returned array explicitly, i.e., use ``np.diagonal(a).copy()`` instead
1597 of just ``np.diagonal(a)``. This will work with both past and future
1598 versions of NumPy.
1600 Parameters
1601 ----------
1602 a : array_like
1603 Array from which the diagonals are taken.
1604 offset : int, optional
1605 Offset of the diagonal from the main diagonal. Can be positive or
1606 negative. Defaults to main diagonal (0).
1607 axis1 : int, optional
1608 Axis to be used as the first axis of the 2-D sub-arrays from which
1609 the diagonals should be taken. Defaults to first axis (0).
1610 axis2 : int, optional
1611 Axis to be used as the second axis of the 2-D sub-arrays from
1612 which the diagonals should be taken. Defaults to second axis (1).
1614 Returns
1615 -------
1616 array_of_diagonals : ndarray
1617 If `a` is 2-D, then a 1-D array containing the diagonal and of the
1618 same type as `a` is returned unless `a` is a `matrix`, in which case
1619 a 1-D array rather than a (2-D) `matrix` is returned in order to
1620 maintain backward compatibility.
1622 If ``a.ndim > 2``, then the dimensions specified by `axis1` and `axis2`
1623 are removed, and a new axis inserted at the end corresponding to the
1624 diagonal.
1626 Raises
1627 ------
1628 ValueError
1629 If the dimension of `a` is less than 2.
1631 See Also
1632 --------
1633 diag : MATLAB work-a-like for 1-D and 2-D arrays.
1634 diagflat : Create diagonal arrays.
1635 trace : Sum along diagonals.
1637 Examples
1638 --------
1639 >>> a = np.arange(4).reshape(2,2)
1640 >>> a
1641 array([[0, 1],
1642 [2, 3]])
1643 >>> a.diagonal()
1644 array([0, 3])
1645 >>> a.diagonal(1)
1646 array([1])
1648 A 3-D example:
1650 >>> a = np.arange(8).reshape(2,2,2); a
1651 array([[[0, 1],
1652 [2, 3]],
1653 [[4, 5],
1654 [6, 7]]])
1655 >>> a.diagonal(0, # Main diagonals of two arrays created by skipping
1656 ... 0, # across the outer(left)-most axis last and
1657 ... 1) # the "middle" (row) axis first.
1658 array([[0, 6],
1659 [1, 7]])
1661 The sub-arrays whose main diagonals we just obtained; note that each
1662 corresponds to fixing the right-most (column) axis, and that the
1663 diagonals are "packed" in rows.
1665 >>> a[:,:,0] # main diagonal is [0 6]
1666 array([[0, 2],
1667 [4, 6]])
1668 >>> a[:,:,1] # main diagonal is [1 7]
1669 array([[1, 3],
1670 [5, 7]])
1672 The anti-diagonal can be obtained by reversing the order of elements
1673 using either `numpy.flipud` or `numpy.fliplr`.
1675 >>> a = np.arange(9).reshape(3, 3)
1676 >>> a
1677 array([[0, 1, 2],
1678 [3, 4, 5],
1679 [6, 7, 8]])
1680 >>> np.fliplr(a).diagonal() # Horizontal flip
1681 array([2, 4, 6])
1682 >>> np.flipud(a).diagonal() # Vertical flip
1683 array([6, 4, 2])
1685 Note that the order in which the diagonal is retrieved varies depending
1686 on the flip function.
1687 """
1688 if isinstance(a, np.matrix):
1689 # Make diagonal of matrix 1-D to preserve backward compatibility.
1690 return asarray(a).diagonal(offset=offset, axis1=axis1, axis2=axis2)
1691 else:
1692 return asanyarray(a).diagonal(offset=offset, axis1=axis1, axis2=axis2)
1695def _trace_dispatcher(
1696 a, offset=None, axis1=None, axis2=None, dtype=None, out=None):
1697 return (a, out)
1700@array_function_dispatch(_trace_dispatcher)
1701def trace(a, offset=0, axis1=0, axis2=1, dtype=None, out=None):
1702 """
1703 Return the sum along diagonals of the array.
1705 If `a` is 2-D, the sum along its diagonal with the given offset
1706 is returned, i.e., the sum of elements ``a[i,i+offset]`` for all i.
1708 If `a` has more than two dimensions, then the axes specified by axis1 and
1709 axis2 are used to determine the 2-D sub-arrays whose traces are returned.
1710 The shape of the resulting array is the same as that of `a` with `axis1`
1711 and `axis2` removed.
1713 Parameters
1714 ----------
1715 a : array_like
1716 Input array, from which the diagonals are taken.
1717 offset : int, optional
1718 Offset of the diagonal from the main diagonal. Can be both positive
1719 and negative. Defaults to 0.
1720 axis1, axis2 : int, optional
1721 Axes to be used as the first and second axis of the 2-D sub-arrays
1722 from which the diagonals should be taken. Defaults are the first two
1723 axes of `a`.
1724 dtype : dtype, optional
1725 Determines the data-type of the returned array and of the accumulator
1726 where the elements are summed. If dtype has the value None and `a` is
1727 of integer type of precision less than the default integer
1728 precision, then the default integer precision is used. Otherwise,
1729 the precision is the same as that of `a`.
1730 out : ndarray, optional
1731 Array into which the output is placed. Its type is preserved and
1732 it must be of the right shape to hold the output.
1734 Returns
1735 -------
1736 sum_along_diagonals : ndarray
1737 If `a` is 2-D, the sum along the diagonal is returned. If `a` has
1738 larger dimensions, then an array of sums along diagonals is returned.
1740 See Also
1741 --------
1742 diag, diagonal, diagflat
1744 Examples
1745 --------
1746 >>> np.trace(np.eye(3))
1747 3.0
1748 >>> a = np.arange(8).reshape((2,2,2))
1749 >>> np.trace(a)
1750 array([6, 8])
1752 >>> a = np.arange(24).reshape((2,2,2,3))
1753 >>> np.trace(a).shape
1754 (2, 3)
1756 """
1757 if isinstance(a, np.matrix):
1758 # Get trace of matrix via an array to preserve backward compatibility.
1759 return asarray(a).trace(offset=offset, axis1=axis1, axis2=axis2, dtype=dtype, out=out)
1760 else:
1761 return asanyarray(a).trace(offset=offset, axis1=axis1, axis2=axis2, dtype=dtype, out=out)
1764def _ravel_dispatcher(a, order=None):
1765 return (a,)
1768@array_function_dispatch(_ravel_dispatcher)
1769def ravel(a, order='C'):
1770 """Return a contiguous flattened array.
1772 A 1-D array, containing the elements of the input, is returned. A copy is
1773 made only if needed.
1775 As of NumPy 1.10, the returned array will have the same type as the input
1776 array. (for example, a masked array will be returned for a masked array
1777 input)
1779 Parameters
1780 ----------
1781 a : array_like
1782 Input array. The elements in `a` are read in the order specified by
1783 `order`, and packed as a 1-D array.
1784 order : {'C','F', 'A', 'K'}, optional
1786 The elements of `a` are read using this index order. 'C' means
1787 to index the elements in row-major, C-style order,
1788 with the last axis index changing fastest, back to the first
1789 axis index changing slowest. 'F' means to index the elements
1790 in column-major, Fortran-style order, with the
1791 first index changing fastest, and the last index changing
1792 slowest. Note that the 'C' and 'F' options take no account of
1793 the memory layout of the underlying array, and only refer to
1794 the order of axis indexing. 'A' means to read the elements in
1795 Fortran-like index order if `a` is Fortran *contiguous* in
1796 memory, C-like order otherwise. 'K' means to read the
1797 elements in the order they occur in memory, except for
1798 reversing the data when strides are negative. By default, 'C'
1799 index order is used.
1801 Returns
1802 -------
1803 y : array_like
1804 y is a contiguous 1-D array of the same subtype as `a`,
1805 with shape ``(a.size,)``.
1806 Note that matrices are special cased for backward compatibility,
1807 if `a` is a matrix, then y is a 1-D ndarray.
1809 See Also
1810 --------
1811 ndarray.flat : 1-D iterator over an array.
1812 ndarray.flatten : 1-D array copy of the elements of an array
1813 in row-major order.
1814 ndarray.reshape : Change the shape of an array without changing its data.
1816 Notes
1817 -----
1818 In row-major, C-style order, in two dimensions, the row index
1819 varies the slowest, and the column index the quickest. This can
1820 be generalized to multiple dimensions, where row-major order
1821 implies that the index along the first axis varies slowest, and
1822 the index along the last quickest. The opposite holds for
1823 column-major, Fortran-style index ordering.
1825 When a view is desired in as many cases as possible, ``arr.reshape(-1)``
1826 may be preferable. However, ``ravel`` supports ``K`` in the optional
1827 ``order`` argument while ``reshape`` does not.
1829 Examples
1830 --------
1831 It is equivalent to ``reshape(-1, order=order)``.
1833 >>> x = np.array([[1, 2, 3], [4, 5, 6]])
1834 >>> np.ravel(x)
1835 array([1, 2, 3, 4, 5, 6])
1837 >>> x.reshape(-1)
1838 array([1, 2, 3, 4, 5, 6])
1840 >>> np.ravel(x, order='F')
1841 array([1, 4, 2, 5, 3, 6])
1843 When ``order`` is 'A', it will preserve the array's 'C' or 'F' ordering:
1845 >>> np.ravel(x.T)
1846 array([1, 4, 2, 5, 3, 6])
1847 >>> np.ravel(x.T, order='A')
1848 array([1, 2, 3, 4, 5, 6])
1850 When ``order`` is 'K', it will preserve orderings that are neither 'C'
1851 nor 'F', but won't reverse axes:
1853 >>> a = np.arange(3)[::-1]; a
1854 array([2, 1, 0])
1855 >>> a.ravel(order='C')
1856 array([2, 1, 0])
1857 >>> a.ravel(order='K')
1858 array([2, 1, 0])
1860 >>> a = np.arange(12).reshape(2,3,2).swapaxes(1,2); a
1861 array([[[ 0, 2, 4],
1862 [ 1, 3, 5]],
1863 [[ 6, 8, 10],
1864 [ 7, 9, 11]]])
1865 >>> a.ravel(order='C')
1866 array([ 0, 2, 4, 1, 3, 5, 6, 8, 10, 7, 9, 11])
1867 >>> a.ravel(order='K')
1868 array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
1870 """
1871 if isinstance(a, np.matrix):
1872 return asarray(a).ravel(order=order)
1873 else:
1874 return asanyarray(a).ravel(order=order)
1877def _nonzero_dispatcher(a):
1878 return (a,)
1881@array_function_dispatch(_nonzero_dispatcher)
1882def nonzero(a):
1883 """
1884 Return the indices of the elements that are non-zero.
1886 Returns a tuple of arrays, one for each dimension of `a`,
1887 containing the indices of the non-zero elements in that
1888 dimension. The values in `a` are always tested and returned in
1889 row-major, C-style order.
1891 To group the indices by element, rather than dimension, use `argwhere`,
1892 which returns a row for each non-zero element.
1894 .. note::
1896 When called on a zero-d array or scalar, ``nonzero(a)`` is treated
1897 as ``nonzero(atleast_1d(a))``.
1899 .. deprecated:: 1.17.0
1901 Use `atleast_1d` explicitly if this behavior is deliberate.
1903 Parameters
1904 ----------
1905 a : array_like
1906 Input array.
1908 Returns
1909 -------
1910 tuple_of_arrays : tuple
1911 Indices of elements that are non-zero.
1913 See Also
1914 --------
1915 flatnonzero :
1916 Return indices that are non-zero in the flattened version of the input
1917 array.
1918 ndarray.nonzero :
1919 Equivalent ndarray method.
1920 count_nonzero :
1921 Counts the number of non-zero elements in the input array.
1923 Notes
1924 -----
1925 While the nonzero values can be obtained with ``a[nonzero(a)]``, it is
1926 recommended to use ``x[x.astype(bool)]`` or ``x[x != 0]`` instead, which
1927 will correctly handle 0-d arrays.
1929 Examples
1930 --------
1931 >>> x = np.array([[3, 0, 0], [0, 4, 0], [5, 6, 0]])
1932 >>> x
1933 array([[3, 0, 0],
1934 [0, 4, 0],
1935 [5, 6, 0]])
1936 >>> np.nonzero(x)
1937 (array([0, 1, 2, 2]), array([0, 1, 0, 1]))
1939 >>> x[np.nonzero(x)]
1940 array([3, 4, 5, 6])
1941 >>> np.transpose(np.nonzero(x))
1942 array([[0, 0],
1943 [1, 1],
1944 [2, 0],
1945 [2, 1]])
1947 A common use for ``nonzero`` is to find the indices of an array, where
1948 a condition is True. Given an array `a`, the condition `a` > 3 is a
1949 boolean array and since False is interpreted as 0, np.nonzero(a > 3)
1950 yields the indices of the `a` where the condition is true.
1952 >>> a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
1953 >>> a > 3
1954 array([[False, False, False],
1955 [ True, True, True],
1956 [ True, True, True]])
1957 >>> np.nonzero(a > 3)
1958 (array([1, 1, 1, 2, 2, 2]), array([0, 1, 2, 0, 1, 2]))
1960 Using this result to index `a` is equivalent to using the mask directly:
1962 >>> a[np.nonzero(a > 3)]
1963 array([4, 5, 6, 7, 8, 9])
1964 >>> a[a > 3] # prefer this spelling
1965 array([4, 5, 6, 7, 8, 9])
1967 ``nonzero`` can also be called as a method of the array.
1969 >>> (a > 3).nonzero()
1970 (array([1, 1, 1, 2, 2, 2]), array([0, 1, 2, 0, 1, 2]))
1972 """
1973 return _wrapfunc(a, 'nonzero')
1976def _shape_dispatcher(a):
1977 return (a,)
1980@array_function_dispatch(_shape_dispatcher)
1981def shape(a):
1982 """
1983 Return the shape of an array.
1985 Parameters
1986 ----------
1987 a : array_like
1988 Input array.
1990 Returns
1991 -------
1992 shape : tuple of ints
1993 The elements of the shape tuple give the lengths of the
1994 corresponding array dimensions.
1996 See Also
1997 --------
1998 len : ``len(a)`` is equivalent to ``np.shape(a)[0]`` for N-D arrays with
1999 ``N>=1``.
2000 ndarray.shape : Equivalent array method.
2002 Examples
2003 --------
2004 >>> np.shape(np.eye(3))
2005 (3, 3)
2006 >>> np.shape([[1, 3]])
2007 (1, 2)
2008 >>> np.shape([0])
2009 (1,)
2010 >>> np.shape(0)
2011 ()
2013 >>> a = np.array([(1, 2), (3, 4), (5, 6)],
2014 ... dtype=[('x', 'i4'), ('y', 'i4')])
2015 >>> np.shape(a)
2016 (3,)
2017 >>> a.shape
2018 (3,)
2020 """
2021 try:
2022 result = a.shape
2023 except AttributeError:
2024 result = asarray(a).shape
2025 return result
2028def _compress_dispatcher(condition, a, axis=None, out=None):
2029 return (condition, a, out)
2032@array_function_dispatch(_compress_dispatcher)
2033def compress(condition, a, axis=None, out=None):
2034 """
2035 Return selected slices of an array along given axis.
2037 When working along a given axis, a slice along that axis is returned in
2038 `output` for each index where `condition` evaluates to True. When
2039 working on a 1-D array, `compress` is equivalent to `extract`.
2041 Parameters
2042 ----------
2043 condition : 1-D array of bools
2044 Array that selects which entries to return. If len(condition)
2045 is less than the size of `a` along the given axis, then output is
2046 truncated to the length of the condition array.
2047 a : array_like
2048 Array from which to extract a part.
2049 axis : int, optional
2050 Axis along which to take slices. If None (default), work on the
2051 flattened array.
2052 out : ndarray, optional
2053 Output array. Its type is preserved and it must be of the right
2054 shape to hold the output.
2056 Returns
2057 -------
2058 compressed_array : ndarray
2059 A copy of `a` without the slices along axis for which `condition`
2060 is false.
2062 See Also
2063 --------
2064 take, choose, diag, diagonal, select
2065 ndarray.compress : Equivalent method in ndarray
2066 extract : Equivalent method when working on 1-D arrays
2067 :ref:`ufuncs-output-type`
2069 Examples
2070 --------
2071 >>> a = np.array([[1, 2], [3, 4], [5, 6]])
2072 >>> a
2073 array([[1, 2],
2074 [3, 4],
2075 [5, 6]])
2076 >>> np.compress([0, 1], a, axis=0)
2077 array([[3, 4]])
2078 >>> np.compress([False, True, True], a, axis=0)
2079 array([[3, 4],
2080 [5, 6]])
2081 >>> np.compress([False, True], a, axis=1)
2082 array([[2],
2083 [4],
2084 [6]])
2086 Working on the flattened array does not return slices along an axis but
2087 selects elements.
2089 >>> np.compress([False, True], a)
2090 array([2])
2092 """
2093 return _wrapfunc(a, 'compress', condition, axis=axis, out=out)
2096def _clip_dispatcher(a, a_min, a_max, out=None, **kwargs):
2097 return (a, a_min, a_max)
2100@array_function_dispatch(_clip_dispatcher)
2101def clip(a, a_min, a_max, out=None, **kwargs):
2102 """
2103 Clip (limit) the values in an array.
2105 Given an interval, values outside the interval are clipped to
2106 the interval edges. For example, if an interval of ``[0, 1]``
2107 is specified, values smaller than 0 become 0, and values larger
2108 than 1 become 1.
2110 Equivalent to but faster than ``np.minimum(a_max, np.maximum(a, a_min))``.
2112 No check is performed to ensure ``a_min < a_max``.
2114 Parameters
2115 ----------
2116 a : array_like
2117 Array containing elements to clip.
2118 a_min, a_max : array_like or None
2119 Minimum and maximum value. If ``None``, clipping is not performed on
2120 the corresponding edge. Only one of `a_min` and `a_max` may be
2121 ``None``. Both are broadcast against `a`.
2122 out : ndarray, optional
2123 The results will be placed in this array. It may be the input
2124 array for in-place clipping. `out` must be of the right shape
2125 to hold the output. Its type is preserved.
2126 **kwargs
2127 For other keyword-only arguments, see the
2128 :ref:`ufunc docs <ufuncs.kwargs>`.
2130 .. versionadded:: 1.17.0
2132 Returns
2133 -------
2134 clipped_array : ndarray
2135 An array with the elements of `a`, but where values
2136 < `a_min` are replaced with `a_min`, and those > `a_max`
2137 with `a_max`.
2139 See Also
2140 --------
2141 :ref:`ufuncs-output-type`
2143 Notes
2144 -----
2145 When `a_min` is greater than `a_max`, `clip` returns an
2146 array in which all values are equal to `a_max`,
2147 as shown in the second example.
2149 Examples
2150 --------
2151 >>> a = np.arange(10)
2152 >>> a
2153 array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
2154 >>> np.clip(a, 1, 8)
2155 array([1, 1, 2, 3, 4, 5, 6, 7, 8, 8])
2156 >>> np.clip(a, 8, 1)
2157 array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1])
2158 >>> np.clip(a, 3, 6, out=a)
2159 array([3, 3, 3, 3, 4, 5, 6, 6, 6, 6])
2160 >>> a
2161 array([3, 3, 3, 3, 4, 5, 6, 6, 6, 6])
2162 >>> a = np.arange(10)
2163 >>> a
2164 array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
2165 >>> np.clip(a, [3, 4, 1, 1, 1, 4, 4, 4, 4, 4], 8)
2166 array([3, 4, 2, 3, 4, 5, 6, 7, 8, 8])
2168 """
2169 return _wrapfunc(a, 'clip', a_min, a_max, out=out, **kwargs)
2172def _sum_dispatcher(a, axis=None, dtype=None, out=None, keepdims=None,
2173 initial=None, where=None):
2174 return (a, out)
2177@array_function_dispatch(_sum_dispatcher)
2178def sum(a, axis=None, dtype=None, out=None, keepdims=np._NoValue,
2179 initial=np._NoValue, where=np._NoValue):
2180 """
2181 Sum of array elements over a given axis.
2183 Parameters
2184 ----------
2185 a : array_like
2186 Elements to sum.
2187 axis : None or int or tuple of ints, optional
2188 Axis or axes along which a sum is performed. The default,
2189 axis=None, will sum all of the elements of the input array. If
2190 axis is negative it counts from the last to the first axis.
2192 .. versionadded:: 1.7.0
2194 If axis is a tuple of ints, a sum is performed on all of the axes
2195 specified in the tuple instead of a single axis or all the axes as
2196 before.
2197 dtype : dtype, optional
2198 The type of the returned array and of the accumulator in which the
2199 elements are summed. The dtype of `a` is used by default unless `a`
2200 has an integer dtype of less precision than the default platform
2201 integer. In that case, if `a` is signed then the platform integer
2202 is used while if `a` is unsigned then an unsigned integer of the
2203 same precision as the platform integer is used.
2204 out : ndarray, optional
2205 Alternative output array in which to place the result. It must have
2206 the same shape as the expected output, but the type of the output
2207 values will be cast if necessary.
2208 keepdims : bool, optional
2209 If this is set to True, the axes which are reduced are left
2210 in the result as dimensions with size one. With this option,
2211 the result will broadcast correctly against the input array.
2213 If the default value is passed, then `keepdims` will not be
2214 passed through to the `sum` method of sub-classes of
2215 `ndarray`, however any non-default value will be. If the
2216 sub-class' method does not implement `keepdims` any
2217 exceptions will be raised.
2218 initial : scalar, optional
2219 Starting value for the sum. See `~numpy.ufunc.reduce` for details.
2221 .. versionadded:: 1.15.0
2223 where : array_like of bool, optional
2224 Elements to include in the sum. See `~numpy.ufunc.reduce` for details.
2226 .. versionadded:: 1.17.0
2228 Returns
2229 -------
2230 sum_along_axis : ndarray
2231 An array with the same shape as `a`, with the specified
2232 axis removed. If `a` is a 0-d array, or if `axis` is None, a scalar
2233 is returned. If an output array is specified, a reference to
2234 `out` is returned.
2236 See Also
2237 --------
2238 ndarray.sum : Equivalent method.
2240 add.reduce : Equivalent functionality of `add`.
2242 cumsum : Cumulative sum of array elements.
2244 trapz : Integration of array values using the composite trapezoidal rule.
2246 mean, average
2248 Notes
2249 -----
2250 Arithmetic is modular when using integer types, and no error is
2251 raised on overflow.
2253 The sum of an empty array is the neutral element 0:
2255 >>> np.sum([])
2256 0.0
2258 For floating point numbers the numerical precision of sum (and
2259 ``np.add.reduce``) is in general limited by directly adding each number
2260 individually to the result causing rounding errors in every step.
2261 However, often numpy will use a numerically better approach (partial
2262 pairwise summation) leading to improved precision in many use-cases.
2263 This improved precision is always provided when no ``axis`` is given.
2264 When ``axis`` is given, it will depend on which axis is summed.
2265 Technically, to provide the best speed possible, the improved precision
2266 is only used when the summation is along the fast axis in memory.
2267 Note that the exact precision may vary depending on other parameters.
2268 In contrast to NumPy, Python's ``math.fsum`` function uses a slower but
2269 more precise approach to summation.
2270 Especially when summing a large number of lower precision floating point
2271 numbers, such as ``float32``, numerical errors can become significant.
2272 In such cases it can be advisable to use `dtype="float64"` to use a higher
2273 precision for the output.
2275 Examples
2276 --------
2277 >>> np.sum([0.5, 1.5])
2278 2.0
2279 >>> np.sum([0.5, 0.7, 0.2, 1.5], dtype=np.int32)
2280 1
2281 >>> np.sum([[0, 1], [0, 5]])
2282 6
2283 >>> np.sum([[0, 1], [0, 5]], axis=0)
2284 array([0, 6])
2285 >>> np.sum([[0, 1], [0, 5]], axis=1)
2286 array([1, 5])
2287 >>> np.sum([[0, 1], [np.nan, 5]], where=[False, True], axis=1)
2288 array([1., 5.])
2290 If the accumulator is too small, overflow occurs:
2292 >>> np.ones(128, dtype=np.int8).sum(dtype=np.int8)
2293 -128
2295 You can also start the sum with a value other than zero:
2297 >>> np.sum([10], initial=5)
2298 15
2299 """
2300 if isinstance(a, _gentype):
2301 # 2018-02-25, 1.15.0
2302 warnings.warn(
2303 "Calling np.sum(generator) is deprecated, and in the future will give a different result. "
2304 "Use np.sum(np.fromiter(generator)) or the python sum builtin instead.",
2305 DeprecationWarning, stacklevel=2)
2307 res = _sum_(a)
2308 if out is not None:
2309 out[...] = res
2310 return out
2311 return res
2313 return _wrapreduction(a, np.add, 'sum', axis, dtype, out, keepdims=keepdims,
2314 initial=initial, where=where)
2317def _any_dispatcher(a, axis=None, out=None, keepdims=None, *,
2318 where=np._NoValue):
2319 return (a, where, out)
2322@array_function_dispatch(_any_dispatcher)
2323def any(a, axis=None, out=None, keepdims=np._NoValue, *, where=np._NoValue):
2324 """
2325 Test whether any array element along a given axis evaluates to True.
2327 Returns single boolean if `axis` is ``None``
2329 Parameters
2330 ----------
2331 a : array_like
2332 Input array or object that can be converted to an array.
2333 axis : None or int or tuple of ints, optional
2334 Axis or axes along which a logical OR reduction is performed.
2335 The default (``axis=None``) is to perform a logical OR over all
2336 the dimensions of the input array. `axis` may be negative, in
2337 which case it counts from the last to the first axis.
2339 .. versionadded:: 1.7.0
2341 If this is a tuple of ints, a reduction is performed on multiple
2342 axes, instead of a single axis or all the axes as before.
2343 out : ndarray, optional
2344 Alternate output array in which to place the result. It must have
2345 the same shape as the expected output and its type is preserved
2346 (e.g., if it is of type float, then it will remain so, returning
2347 1.0 for True and 0.0 for False, regardless of the type of `a`).
2348 See :ref:`ufuncs-output-type` for more details.
2350 keepdims : bool, optional
2351 If this is set to True, the axes which are reduced are left
2352 in the result as dimensions with size one. With this option,
2353 the result will broadcast correctly against the input array.
2355 If the default value is passed, then `keepdims` will not be
2356 passed through to the `any` method of sub-classes of
2357 `ndarray`, however any non-default value will be. If the
2358 sub-class' method does not implement `keepdims` any
2359 exceptions will be raised.
2361 where : array_like of bool, optional
2362 Elements to include in checking for any `True` values.
2363 See `~numpy.ufunc.reduce` for details.
2365 .. versionadded:: 1.20.0
2367 Returns
2368 -------
2369 any : bool or ndarray
2370 A new boolean or `ndarray` is returned unless `out` is specified,
2371 in which case a reference to `out` is returned.
2373 See Also
2374 --------
2375 ndarray.any : equivalent method
2377 all : Test whether all elements along a given axis evaluate to True.
2379 Notes
2380 -----
2381 Not a Number (NaN), positive infinity and negative infinity evaluate
2382 to `True` because these are not equal to zero.
2384 Examples
2385 --------
2386 >>> np.any([[True, False], [True, True]])
2387 True
2389 >>> np.any([[True, False], [False, False]], axis=0)
2390 array([ True, False])
2392 >>> np.any([-1, 0, 5])
2393 True
2395 >>> np.any(np.nan)
2396 True
2398 >>> np.any([[True, False], [False, False]], where=[[False], [True]])
2399 False
2401 >>> o=np.array(False)
2402 >>> z=np.any([-1, 4, 5], out=o)
2403 >>> z, o
2404 (array(True), array(True))
2405 >>> # Check now that z is a reference to o
2406 >>> z is o
2407 True
2408 >>> id(z), id(o) # identity of z and o # doctest: +SKIP
2409 (191614240, 191614240)
2411 """
2412 return _wrapreduction(a, np.logical_or, 'any', axis, None, out,
2413 keepdims=keepdims, where=where)
2416def _all_dispatcher(a, axis=None, out=None, keepdims=None, *,
2417 where=None):
2418 return (a, where, out)
2421@array_function_dispatch(_all_dispatcher)
2422def all(a, axis=None, out=None, keepdims=np._NoValue, *, where=np._NoValue):
2423 """
2424 Test whether all array elements along a given axis evaluate to True.
2426 Parameters
2427 ----------
2428 a : array_like
2429 Input array or object that can be converted to an array.
2430 axis : None or int or tuple of ints, optional
2431 Axis or axes along which a logical AND reduction is performed.
2432 The default (``axis=None``) is to perform a logical AND over all
2433 the dimensions of the input array. `axis` may be negative, in
2434 which case it counts from the last to the first axis.
2436 .. versionadded:: 1.7.0
2438 If this is a tuple of ints, a reduction is performed on multiple
2439 axes, instead of a single axis or all the axes as before.
2440 out : ndarray, optional
2441 Alternate output array in which to place the result.
2442 It must have the same shape as the expected output and its
2443 type is preserved (e.g., if ``dtype(out)`` is float, the result
2444 will consist of 0.0's and 1.0's). See :ref:`ufuncs-output-type` for more
2445 details.
2447 keepdims : bool, optional
2448 If this is set to True, the axes which are reduced are left
2449 in the result as dimensions with size one. With this option,
2450 the result will broadcast correctly against the input array.
2452 If the default value is passed, then `keepdims` will not be
2453 passed through to the `all` method of sub-classes of
2454 `ndarray`, however any non-default value will be. If the
2455 sub-class' method does not implement `keepdims` any
2456 exceptions will be raised.
2458 where : array_like of bool, optional
2459 Elements to include in checking for all `True` values.
2460 See `~numpy.ufunc.reduce` for details.
2462 .. versionadded:: 1.20.0
2464 Returns
2465 -------
2466 all : ndarray, bool
2467 A new boolean or array is returned unless `out` is specified,
2468 in which case a reference to `out` is returned.
2470 See Also
2471 --------
2472 ndarray.all : equivalent method
2474 any : Test whether any element along a given axis evaluates to True.
2476 Notes
2477 -----
2478 Not a Number (NaN), positive infinity and negative infinity
2479 evaluate to `True` because these are not equal to zero.
2481 Examples
2482 --------
2483 >>> np.all([[True,False],[True,True]])
2484 False
2486 >>> np.all([[True,False],[True,True]], axis=0)
2487 array([ True, False])
2489 >>> np.all([-1, 4, 5])
2490 True
2492 >>> np.all([1.0, np.nan])
2493 True
2495 >>> np.all([[True, True], [False, True]], where=[[True], [False]])
2496 True
2498 >>> o=np.array(False)
2499 >>> z=np.all([-1, 4, 5], out=o)
2500 >>> id(z), id(o), z
2501 (28293632, 28293632, array(True)) # may vary
2503 """
2504 return _wrapreduction(a, np.logical_and, 'all', axis, None, out,
2505 keepdims=keepdims, where=where)
2508def _cumsum_dispatcher(a, axis=None, dtype=None, out=None):
2509 return (a, out)
2512@array_function_dispatch(_cumsum_dispatcher)
2513def cumsum(a, axis=None, dtype=None, out=None):
2514 """
2515 Return the cumulative sum of the elements along a given axis.
2517 Parameters
2518 ----------
2519 a : array_like
2520 Input array.
2521 axis : int, optional
2522 Axis along which the cumulative sum is computed. The default
2523 (None) is to compute the cumsum over the flattened array.
2524 dtype : dtype, optional
2525 Type of the returned array and of the accumulator in which the
2526 elements are summed. If `dtype` is not specified, it defaults
2527 to the dtype of `a`, unless `a` has an integer dtype with a
2528 precision less than that of the default platform integer. In
2529 that case, the default platform integer is used.
2530 out : ndarray, optional
2531 Alternative output array in which to place the result. It must
2532 have the same shape and buffer length as the expected output
2533 but the type will be cast if necessary. See :ref:`ufuncs-output-type` for
2534 more details.
2536 Returns
2537 -------
2538 cumsum_along_axis : ndarray.
2539 A new array holding the result is returned unless `out` is
2540 specified, in which case a reference to `out` is returned. The
2541 result has the same size as `a`, and the same shape as `a` if
2542 `axis` is not None or `a` is a 1-d array.
2544 See Also
2545 --------
2546 sum : Sum array elements.
2547 trapz : Integration of array values using the composite trapezoidal rule.
2548 diff : Calculate the n-th discrete difference along given axis.
2550 Notes
2551 -----
2552 Arithmetic is modular when using integer types, and no error is
2553 raised on overflow.
2555 ``cumsum(a)[-1]`` may not be equal to ``sum(a)`` for floating-point
2556 values since ``sum`` may use a pairwise summation routine, reducing
2557 the roundoff-error. See `sum` for more information.
2559 Examples
2560 --------
2561 >>> a = np.array([[1,2,3], [4,5,6]])
2562 >>> a
2563 array([[1, 2, 3],
2564 [4, 5, 6]])
2565 >>> np.cumsum(a)
2566 array([ 1, 3, 6, 10, 15, 21])
2567 >>> np.cumsum(a, dtype=float) # specifies type of output value(s)
2568 array([ 1., 3., 6., 10., 15., 21.])
2570 >>> np.cumsum(a,axis=0) # sum over rows for each of the 3 columns
2571 array([[1, 2, 3],
2572 [5, 7, 9]])
2573 >>> np.cumsum(a,axis=1) # sum over columns for each of the 2 rows
2574 array([[ 1, 3, 6],
2575 [ 4, 9, 15]])
2577 ``cumsum(b)[-1]`` may not be equal to ``sum(b)``
2579 >>> b = np.array([1, 2e-9, 3e-9] * 1000000)
2580 >>> b.cumsum()[-1]
2581 1000000.0050045159
2582 >>> b.sum()
2583 1000000.0050000029
2585 """
2586 return _wrapfunc(a, 'cumsum', axis=axis, dtype=dtype, out=out)
2589def _ptp_dispatcher(a, axis=None, out=None, keepdims=None):
2590 return (a, out)
2593@array_function_dispatch(_ptp_dispatcher)
2594def ptp(a, axis=None, out=None, keepdims=np._NoValue):
2595 """
2596 Range of values (maximum - minimum) along an axis.
2598 The name of the function comes from the acronym for 'peak to peak'.
2600 .. warning::
2601 `ptp` preserves the data type of the array. This means the
2602 return value for an input of signed integers with n bits
2603 (e.g. `np.int8`, `np.int16`, etc) is also a signed integer
2604 with n bits. In that case, peak-to-peak values greater than
2605 ``2**(n-1)-1`` will be returned as negative values. An example
2606 with a work-around is shown below.
2608 Parameters
2609 ----------
2610 a : array_like
2611 Input values.
2612 axis : None or int or tuple of ints, optional
2613 Axis along which to find the peaks. By default, flatten the
2614 array. `axis` may be negative, in
2615 which case it counts from the last to the first axis.
2617 .. versionadded:: 1.15.0
2619 If this is a tuple of ints, a reduction is performed on multiple
2620 axes, instead of a single axis or all the axes as before.
2621 out : array_like
2622 Alternative output array in which to place the result. It must
2623 have the same shape and buffer length as the expected output,
2624 but the type of the output values will be cast if necessary.
2626 keepdims : bool, optional
2627 If this is set to True, the axes which are reduced are left
2628 in the result as dimensions with size one. With this option,
2629 the result will broadcast correctly against the input array.
2631 If the default value is passed, then `keepdims` will not be
2632 passed through to the `ptp` method of sub-classes of
2633 `ndarray`, however any non-default value will be. If the
2634 sub-class' method does not implement `keepdims` any
2635 exceptions will be raised.
2637 Returns
2638 -------
2639 ptp : ndarray or scalar
2640 The range of a given array - `scalar` if array is one-dimensional
2641 or a new array holding the result along the given axis
2643 Examples
2644 --------
2645 >>> x = np.array([[4, 9, 2, 10],
2646 ... [6, 9, 7, 12]])
2648 >>> np.ptp(x, axis=1)
2649 array([8, 6])
2651 >>> np.ptp(x, axis=0)
2652 array([2, 0, 5, 2])
2654 >>> np.ptp(x)
2655 10
2657 This example shows that a negative value can be returned when
2658 the input is an array of signed integers.
2660 >>> y = np.array([[1, 127],
2661 ... [0, 127],
2662 ... [-1, 127],
2663 ... [-2, 127]], dtype=np.int8)
2664 >>> np.ptp(y, axis=1)
2665 array([ 126, 127, -128, -127], dtype=int8)
2667 A work-around is to use the `view()` method to view the result as
2668 unsigned integers with the same bit width:
2670 >>> np.ptp(y, axis=1).view(np.uint8)
2671 array([126, 127, 128, 129], dtype=uint8)
2673 """
2674 kwargs = {}
2675 if keepdims is not np._NoValue:
2676 kwargs['keepdims'] = keepdims
2677 if type(a) is not mu.ndarray:
2678 try:
2679 ptp = a.ptp
2680 except AttributeError:
2681 pass
2682 else:
2683 return ptp(axis=axis, out=out, **kwargs)
2684 return _methods._ptp(a, axis=axis, out=out, **kwargs)
2687def _max_dispatcher(a, axis=None, out=None, keepdims=None, initial=None,
2688 where=None):
2689 return (a, out)
2692@array_function_dispatch(_max_dispatcher)
2693@set_module('numpy')
2694def max(a, axis=None, out=None, keepdims=np._NoValue, initial=np._NoValue,
2695 where=np._NoValue):
2696 """
2697 Return the maximum of an array or maximum along an axis.
2699 Parameters
2700 ----------
2701 a : array_like
2702 Input data.
2703 axis : None or int or tuple of ints, optional
2704 Axis or axes along which to operate. By default, flattened input is
2705 used.
2707 .. versionadded:: 1.7.0
2709 If this is a tuple of ints, the maximum is selected over multiple axes,
2710 instead of a single axis or all the axes as before.
2711 out : ndarray, optional
2712 Alternative output array in which to place the result. Must
2713 be of the same shape and buffer length as the expected output.
2714 See :ref:`ufuncs-output-type` for more details.
2716 keepdims : bool, optional
2717 If this is set to True, the axes which are reduced are left
2718 in the result as dimensions with size one. With this option,
2719 the result will broadcast correctly against the input array.
2721 If the default value is passed, then `keepdims` will not be
2722 passed through to the ``max`` method of sub-classes of
2723 `ndarray`, however any non-default value will be. If the
2724 sub-class' method does not implement `keepdims` any
2725 exceptions will be raised.
2727 initial : scalar, optional
2728 The minimum value of an output element. Must be present to allow
2729 computation on empty slice. See `~numpy.ufunc.reduce` for details.
2731 .. versionadded:: 1.15.0
2733 where : array_like of bool, optional
2734 Elements to compare for the maximum. See `~numpy.ufunc.reduce`
2735 for details.
2737 .. versionadded:: 1.17.0
2739 Returns
2740 -------
2741 max : ndarray or scalar
2742 Maximum of `a`. If `axis` is None, the result is a scalar value.
2743 If `axis` is an int, the result is an array of dimension
2744 ``a.ndim - 1``. If `axis` is a tuple, the result is an array of
2745 dimension ``a.ndim - len(axis)``.
2747 See Also
2748 --------
2749 amin :
2750 The minimum value of an array along a given axis, propagating any NaNs.
2751 nanmax :
2752 The maximum value of an array along a given axis, ignoring any NaNs.
2753 maximum :
2754 Element-wise maximum of two arrays, propagating any NaNs.
2755 fmax :
2756 Element-wise maximum of two arrays, ignoring any NaNs.
2757 argmax :
2758 Return the indices of the maximum values.
2760 nanmin, minimum, fmin
2762 Notes
2763 -----
2764 NaN values are propagated, that is if at least one item is NaN, the
2765 corresponding max value will be NaN as well. To ignore NaN values
2766 (MATLAB behavior), please use nanmax.
2768 Don't use `~numpy.max` for element-wise comparison of 2 arrays; when
2769 ``a.shape[0]`` is 2, ``maximum(a[0], a[1])`` is faster than
2770 ``max(a, axis=0)``.
2772 Examples
2773 --------
2774 >>> a = np.arange(4).reshape((2,2))
2775 >>> a
2776 array([[0, 1],
2777 [2, 3]])
2778 >>> np.max(a) # Maximum of the flattened array
2779 3
2780 >>> np.max(a, axis=0) # Maxima along the first axis
2781 array([2, 3])
2782 >>> np.max(a, axis=1) # Maxima along the second axis
2783 array([1, 3])
2784 >>> np.max(a, where=[False, True], initial=-1, axis=0)
2785 array([-1, 3])
2786 >>> b = np.arange(5, dtype=float)
2787 >>> b[2] = np.NaN
2788 >>> np.max(b)
2789 nan
2790 >>> np.max(b, where=~np.isnan(b), initial=-1)
2791 4.0
2792 >>> np.nanmax(b)
2793 4.0
2795 You can use an initial value to compute the maximum of an empty slice, or
2796 to initialize it to a different value:
2798 >>> np.max([[-50], [10]], axis=-1, initial=0)
2799 array([ 0, 10])
2801 Notice that the initial value is used as one of the elements for which the
2802 maximum is determined, unlike for the default argument Python's max
2803 function, which is only used for empty iterables.
2805 >>> np.max([5], initial=6)
2806 6
2807 >>> max([5], default=6)
2808 5
2809 """
2810 return _wrapreduction(a, np.maximum, 'max', axis, None, out,
2811 keepdims=keepdims, initial=initial, where=where)
2814@array_function_dispatch(_max_dispatcher)
2815def amax(a, axis=None, out=None, keepdims=np._NoValue, initial=np._NoValue,
2816 where=np._NoValue):
2817 """
2818 Return the maximum of an array or maximum along an axis.
2820 `amax` is an alias of `~numpy.max`.
2822 See Also
2823 --------
2824 max : alias of this function
2825 ndarray.max : equivalent method
2826 """
2827 return _wrapreduction(a, np.maximum, 'max', axis, None, out,
2828 keepdims=keepdims, initial=initial, where=where)
2831def _min_dispatcher(a, axis=None, out=None, keepdims=None, initial=None,
2832 where=None):
2833 return (a, out)
2836@array_function_dispatch(_min_dispatcher)
2837def min(a, axis=None, out=None, keepdims=np._NoValue, initial=np._NoValue,
2838 where=np._NoValue):
2839 """
2840 Return the minimum of an array or minimum along an axis.
2842 Parameters
2843 ----------
2844 a : array_like
2845 Input data.
2846 axis : None or int or tuple of ints, optional
2847 Axis or axes along which to operate. By default, flattened input is
2848 used.
2850 .. versionadded:: 1.7.0
2852 If this is a tuple of ints, the minimum is selected over multiple axes,
2853 instead of a single axis or all the axes as before.
2854 out : ndarray, optional
2855 Alternative output array in which to place the result. Must
2856 be of the same shape and buffer length as the expected output.
2857 See :ref:`ufuncs-output-type` for more details.
2859 keepdims : bool, optional
2860 If this is set to True, the axes which are reduced are left
2861 in the result as dimensions with size one. With this option,
2862 the result will broadcast correctly against the input array.
2864 If the default value is passed, then `keepdims` will not be
2865 passed through to the ``min`` method of sub-classes of
2866 `ndarray`, however any non-default value will be. If the
2867 sub-class' method does not implement `keepdims` any
2868 exceptions will be raised.
2870 initial : scalar, optional
2871 The maximum value of an output element. Must be present to allow
2872 computation on empty slice. See `~numpy.ufunc.reduce` for details.
2874 .. versionadded:: 1.15.0
2876 where : array_like of bool, optional
2877 Elements to compare for the minimum. See `~numpy.ufunc.reduce`
2878 for details.
2880 .. versionadded:: 1.17.0
2882 Returns
2883 -------
2884 min : ndarray or scalar
2885 Minimum of `a`. If `axis` is None, the result is a scalar value.
2886 If `axis` is an int, the result is an array of dimension
2887 ``a.ndim - 1``. If `axis` is a tuple, the result is an array of
2888 dimension ``a.ndim - len(axis)``.
2890 See Also
2891 --------
2892 amax :
2893 The maximum value of an array along a given axis, propagating any NaNs.
2894 nanmin :
2895 The minimum value of an array along a given axis, ignoring any NaNs.
2896 minimum :
2897 Element-wise minimum of two arrays, propagating any NaNs.
2898 fmin :
2899 Element-wise minimum of two arrays, ignoring any NaNs.
2900 argmin :
2901 Return the indices of the minimum values.
2903 nanmax, maximum, fmax
2905 Notes
2906 -----
2907 NaN values are propagated, that is if at least one item is NaN, the
2908 corresponding min value will be NaN as well. To ignore NaN values
2909 (MATLAB behavior), please use nanmin.
2911 Don't use `~numpy.min` for element-wise comparison of 2 arrays; when
2912 ``a.shape[0]`` is 2, ``minimum(a[0], a[1])`` is faster than
2913 ``min(a, axis=0)``.
2915 Examples
2916 --------
2917 >>> a = np.arange(4).reshape((2,2))
2918 >>> a
2919 array([[0, 1],
2920 [2, 3]])
2921 >>> np.min(a) # Minimum of the flattened array
2922 0
2923 >>> np.min(a, axis=0) # Minima along the first axis
2924 array([0, 1])
2925 >>> np.min(a, axis=1) # Minima along the second axis
2926 array([0, 2])
2927 >>> np.min(a, where=[False, True], initial=10, axis=0)
2928 array([10, 1])
2930 >>> b = np.arange(5, dtype=float)
2931 >>> b[2] = np.NaN
2932 >>> np.min(b)
2933 nan
2934 >>> np.min(b, where=~np.isnan(b), initial=10)
2935 0.0
2936 >>> np.nanmin(b)
2937 0.0
2939 >>> np.min([[-50], [10]], axis=-1, initial=0)
2940 array([-50, 0])
2942 Notice that the initial value is used as one of the elements for which the
2943 minimum is determined, unlike for the default argument Python's max
2944 function, which is only used for empty iterables.
2946 Notice that this isn't the same as Python's ``default`` argument.
2948 >>> np.min([6], initial=5)
2949 5
2950 >>> min([6], default=5)
2951 6
2952 """
2953 return _wrapreduction(a, np.minimum, 'min', axis, None, out,
2954 keepdims=keepdims, initial=initial, where=where)
2957@array_function_dispatch(_min_dispatcher)
2958def amin(a, axis=None, out=None, keepdims=np._NoValue, initial=np._NoValue,
2959 where=np._NoValue):
2960 """
2961 Return the minimum of an array or minimum along an axis.
2963 `amin` is an alias of `~numpy.min`.
2965 See Also
2966 --------
2967 min : alias of this function
2968 ndarray.min : equivalent method
2969 """
2970 return _wrapreduction(a, np.minimum, 'min', axis, None, out,
2971 keepdims=keepdims, initial=initial, where=where)
2974def _prod_dispatcher(a, axis=None, dtype=None, out=None, keepdims=None,
2975 initial=None, where=None):
2976 return (a, out)
2979@array_function_dispatch(_prod_dispatcher)
2980def prod(a, axis=None, dtype=None, out=None, keepdims=np._NoValue,
2981 initial=np._NoValue, where=np._NoValue):
2982 """
2983 Return the product of array elements over a given axis.
2985 Parameters
2986 ----------
2987 a : array_like
2988 Input data.
2989 axis : None or int or tuple of ints, optional
2990 Axis or axes along which a product is performed. The default,
2991 axis=None, will calculate the product of all the elements in the
2992 input array. If axis is negative it counts from the last to the
2993 first axis.
2995 .. versionadded:: 1.7.0
2997 If axis is a tuple of ints, a product is performed on all of the
2998 axes specified in the tuple instead of a single axis or all the
2999 axes as before.
3000 dtype : dtype, optional
3001 The type of the returned array, as well as of the accumulator in
3002 which the elements are multiplied. The dtype of `a` is used by
3003 default unless `a` has an integer dtype of less precision than the
3004 default platform integer. In that case, if `a` is signed then the
3005 platform integer is used while if `a` is unsigned then an unsigned
3006 integer of the same precision as the platform integer is used.
3007 out : ndarray, optional
3008 Alternative output array in which to place the result. It must have
3009 the same shape as the expected output, but the type of the output
3010 values will be cast if necessary.
3011 keepdims : bool, optional
3012 If this is set to True, the axes which are reduced are left in the
3013 result as dimensions with size one. With this option, the result
3014 will broadcast correctly against the input array.
3016 If the default value is passed, then `keepdims` will not be
3017 passed through to the `prod` method of sub-classes of
3018 `ndarray`, however any non-default value will be. If the
3019 sub-class' method does not implement `keepdims` any
3020 exceptions will be raised.
3021 initial : scalar, optional
3022 The starting value for this product. See `~numpy.ufunc.reduce` for details.
3024 .. versionadded:: 1.15.0
3026 where : array_like of bool, optional
3027 Elements to include in the product. See `~numpy.ufunc.reduce` for details.
3029 .. versionadded:: 1.17.0
3031 Returns
3032 -------
3033 product_along_axis : ndarray, see `dtype` parameter above.
3034 An array shaped as `a` but with the specified axis removed.
3035 Returns a reference to `out` if specified.
3037 See Also
3038 --------
3039 ndarray.prod : equivalent method
3040 :ref:`ufuncs-output-type`
3042 Notes
3043 -----
3044 Arithmetic is modular when using integer types, and no error is
3045 raised on overflow. That means that, on a 32-bit platform:
3047 >>> x = np.array([536870910, 536870910, 536870910, 536870910])
3048 >>> np.prod(x)
3049 16 # may vary
3051 The product of an empty array is the neutral element 1:
3053 >>> np.prod([])
3054 1.0
3056 Examples
3057 --------
3058 By default, calculate the product of all elements:
3060 >>> np.prod([1.,2.])
3061 2.0
3063 Even when the input array is two-dimensional:
3065 >>> a = np.array([[1., 2.], [3., 4.]])
3066 >>> np.prod(a)
3067 24.0
3069 But we can also specify the axis over which to multiply:
3071 >>> np.prod(a, axis=1)
3072 array([ 2., 12.])
3073 >>> np.prod(a, axis=0)
3074 array([3., 8.])
3076 Or select specific elements to include:
3078 >>> np.prod([1., np.nan, 3.], where=[True, False, True])
3079 3.0
3081 If the type of `x` is unsigned, then the output type is
3082 the unsigned platform integer:
3084 >>> x = np.array([1, 2, 3], dtype=np.uint8)
3085 >>> np.prod(x).dtype == np.uint
3086 True
3088 If `x` is of a signed integer type, then the output type
3089 is the default platform integer:
3091 >>> x = np.array([1, 2, 3], dtype=np.int8)
3092 >>> np.prod(x).dtype == int
3093 True
3095 You can also start the product with a value other than one:
3097 >>> np.prod([1, 2], initial=5)
3098 10
3099 """
3100 return _wrapreduction(a, np.multiply, 'prod', axis, dtype, out,
3101 keepdims=keepdims, initial=initial, where=where)
3104def _cumprod_dispatcher(a, axis=None, dtype=None, out=None):
3105 return (a, out)
3108@array_function_dispatch(_cumprod_dispatcher)
3109def cumprod(a, axis=None, dtype=None, out=None):
3110 """
3111 Return the cumulative product of elements along a given axis.
3113 Parameters
3114 ----------
3115 a : array_like
3116 Input array.
3117 axis : int, optional
3118 Axis along which the cumulative product is computed. By default
3119 the input is flattened.
3120 dtype : dtype, optional
3121 Type of the returned array, as well as of the accumulator in which
3122 the elements are multiplied. If *dtype* is not specified, it
3123 defaults to the dtype of `a`, unless `a` has an integer dtype with
3124 a precision less than that of the default platform integer. In
3125 that case, the default platform integer is used instead.
3126 out : ndarray, optional
3127 Alternative output array in which to place the result. It must
3128 have the same shape and buffer length as the expected output
3129 but the type of the resulting values will be cast if necessary.
3131 Returns
3132 -------
3133 cumprod : ndarray
3134 A new array holding the result is returned unless `out` is
3135 specified, in which case a reference to out is returned.
3137 See Also
3138 --------
3139 :ref:`ufuncs-output-type`
3141 Notes
3142 -----
3143 Arithmetic is modular when using integer types, and no error is
3144 raised on overflow.
3146 Examples
3147 --------
3148 >>> a = np.array([1,2,3])
3149 >>> np.cumprod(a) # intermediate results 1, 1*2
3150 ... # total product 1*2*3 = 6
3151 array([1, 2, 6])
3152 >>> a = np.array([[1, 2, 3], [4, 5, 6]])
3153 >>> np.cumprod(a, dtype=float) # specify type of output
3154 array([ 1., 2., 6., 24., 120., 720.])
3156 The cumulative product for each column (i.e., over the rows) of `a`:
3158 >>> np.cumprod(a, axis=0)
3159 array([[ 1, 2, 3],
3160 [ 4, 10, 18]])
3162 The cumulative product for each row (i.e. over the columns) of `a`:
3164 >>> np.cumprod(a,axis=1)
3165 array([[ 1, 2, 6],
3166 [ 4, 20, 120]])
3168 """
3169 return _wrapfunc(a, 'cumprod', axis=axis, dtype=dtype, out=out)
3172def _ndim_dispatcher(a):
3173 return (a,)
3176@array_function_dispatch(_ndim_dispatcher)
3177def ndim(a):
3178 """
3179 Return the number of dimensions of an array.
3181 Parameters
3182 ----------
3183 a : array_like
3184 Input array. If it is not already an ndarray, a conversion is
3185 attempted.
3187 Returns
3188 -------
3189 number_of_dimensions : int
3190 The number of dimensions in `a`. Scalars are zero-dimensional.
3192 See Also
3193 --------
3194 ndarray.ndim : equivalent method
3195 shape : dimensions of array
3196 ndarray.shape : dimensions of array
3198 Examples
3199 --------
3200 >>> np.ndim([[1,2,3],[4,5,6]])
3201 2
3202 >>> np.ndim(np.array([[1,2,3],[4,5,6]]))
3203 2
3204 >>> np.ndim(1)
3205 0
3207 """
3208 try:
3209 return a.ndim
3210 except AttributeError:
3211 return asarray(a).ndim
3214def _size_dispatcher(a, axis=None):
3215 return (a,)
3218@array_function_dispatch(_size_dispatcher)
3219def size(a, axis=None):
3220 """
3221 Return the number of elements along a given axis.
3223 Parameters
3224 ----------
3225 a : array_like
3226 Input data.
3227 axis : int, optional
3228 Axis along which the elements are counted. By default, give
3229 the total number of elements.
3231 Returns
3232 -------
3233 element_count : int
3234 Number of elements along the specified axis.
3236 See Also
3237 --------
3238 shape : dimensions of array
3239 ndarray.shape : dimensions of array
3240 ndarray.size : number of elements in array
3242 Examples
3243 --------
3244 >>> a = np.array([[1,2,3],[4,5,6]])
3245 >>> np.size(a)
3246 6
3247 >>> np.size(a,1)
3248 3
3249 >>> np.size(a,0)
3250 2
3252 """
3253 if axis is None:
3254 try:
3255 return a.size
3256 except AttributeError:
3257 return asarray(a).size
3258 else:
3259 try:
3260 return a.shape[axis]
3261 except AttributeError:
3262 return asarray(a).shape[axis]
3265def _round_dispatcher(a, decimals=None, out=None):
3266 return (a, out)
3269@array_function_dispatch(_round_dispatcher)
3270def round(a, decimals=0, out=None):
3271 """
3272 Evenly round to the given number of decimals.
3274 Parameters
3275 ----------
3276 a : array_like
3277 Input data.
3278 decimals : int, optional
3279 Number of decimal places to round to (default: 0). If
3280 decimals is negative, it specifies the number of positions to
3281 the left of the decimal point.
3282 out : ndarray, optional
3283 Alternative output array in which to place the result. It must have
3284 the same shape as the expected output, but the type of the output
3285 values will be cast if necessary. See :ref:`ufuncs-output-type` for more
3286 details.
3288 Returns
3289 -------
3290 rounded_array : ndarray
3291 An array of the same type as `a`, containing the rounded values.
3292 Unless `out` was specified, a new array is created. A reference to
3293 the result is returned.
3295 The real and imaginary parts of complex numbers are rounded
3296 separately. The result of rounding a float is a float.
3298 See Also
3299 --------
3300 ndarray.round : equivalent method
3301 around : an alias for this function
3302 ceil, fix, floor, rint, trunc
3305 Notes
3306 -----
3307 For values exactly halfway between rounded decimal values, NumPy
3308 rounds to the nearest even value. Thus 1.5 and 2.5 round to 2.0,
3309 -0.5 and 0.5 round to 0.0, etc.
3311 ``np.round`` uses a fast but sometimes inexact algorithm to round
3312 floating-point datatypes. For positive `decimals` it is equivalent to
3313 ``np.true_divide(np.rint(a * 10**decimals), 10**decimals)``, which has
3314 error due to the inexact representation of decimal fractions in the IEEE
3315 floating point standard [1]_ and errors introduced when scaling by powers
3316 of ten. For instance, note the extra "1" in the following:
3318 >>> np.round(56294995342131.5, 3)
3319 56294995342131.51
3321 If your goal is to print such values with a fixed number of decimals, it is
3322 preferable to use numpy's float printing routines to limit the number of
3323 printed decimals:
3325 >>> np.format_float_positional(56294995342131.5, precision=3)
3326 '56294995342131.5'
3328 The float printing routines use an accurate but much more computationally
3329 demanding algorithm to compute the number of digits after the decimal
3330 point.
3332 Alternatively, Python's builtin `round` function uses a more accurate
3333 but slower algorithm for 64-bit floating point values:
3335 >>> round(56294995342131.5, 3)
3336 56294995342131.5
3337 >>> np.round(16.055, 2), round(16.055, 2) # equals 16.0549999999999997
3338 (16.06, 16.05)
3341 References
3342 ----------
3343 .. [1] "Lecture Notes on the Status of IEEE 754", William Kahan,
3344 https://people.eecs.berkeley.edu/~wkahan/ieee754status/IEEE754.PDF
3346 Examples
3347 --------
3348 >>> np.round([0.37, 1.64])
3349 array([0., 2.])
3350 >>> np.round([0.37, 1.64], decimals=1)
3351 array([0.4, 1.6])
3352 >>> np.round([.5, 1.5, 2.5, 3.5, 4.5]) # rounds to nearest even value
3353 array([0., 2., 2., 4., 4.])
3354 >>> np.round([1,2,3,11], decimals=1) # ndarray of ints is returned
3355 array([ 1, 2, 3, 11])
3356 >>> np.round([1,2,3,11], decimals=-1)
3357 array([ 0, 0, 0, 10])
3359 """
3360 return _wrapfunc(a, 'round', decimals=decimals, out=out)
3363@array_function_dispatch(_round_dispatcher)
3364def around(a, decimals=0, out=None):
3365 """
3366 Round an array to the given number of decimals.
3368 `around` is an alias of `~numpy.round`.
3370 See Also
3371 --------
3372 ndarray.round : equivalent method
3373 round : alias for this function
3374 ceil, fix, floor, rint, trunc
3376 """
3377 return _wrapfunc(a, 'round', decimals=decimals, out=out)
3380def _mean_dispatcher(a, axis=None, dtype=None, out=None, keepdims=None, *,
3381 where=None):
3382 return (a, where, out)
3385@array_function_dispatch(_mean_dispatcher)
3386def mean(a, axis=None, dtype=None, out=None, keepdims=np._NoValue, *,
3387 where=np._NoValue):
3388 """
3389 Compute the arithmetic mean along the specified axis.
3391 Returns the average of the array elements. The average is taken over
3392 the flattened array by default, otherwise over the specified axis.
3393 `float64` intermediate and return values are used for integer inputs.
3395 Parameters
3396 ----------
3397 a : array_like
3398 Array containing numbers whose mean is desired. If `a` is not an
3399 array, a conversion is attempted.
3400 axis : None or int or tuple of ints, optional
3401 Axis or axes along which the means are computed. The default is to
3402 compute the mean of the flattened array.
3404 .. versionadded:: 1.7.0
3406 If this is a tuple of ints, a mean is performed over multiple axes,
3407 instead of a single axis or all the axes as before.
3408 dtype : data-type, optional
3409 Type to use in computing the mean. For integer inputs, the default
3410 is `float64`; for floating point inputs, it is the same as the
3411 input dtype.
3412 out : ndarray, optional
3413 Alternate output array in which to place the result. The default
3414 is ``None``; if provided, it must have the same shape as the
3415 expected output, but the type will be cast if necessary.
3416 See :ref:`ufuncs-output-type` for more details.
3418 keepdims : bool, optional
3419 If this is set to True, the axes which are reduced are left
3420 in the result as dimensions with size one. With this option,
3421 the result will broadcast correctly against the input array.
3423 If the default value is passed, then `keepdims` will not be
3424 passed through to the `mean` method of sub-classes of
3425 `ndarray`, however any non-default value will be. If the
3426 sub-class' method does not implement `keepdims` any
3427 exceptions will be raised.
3429 where : array_like of bool, optional
3430 Elements to include in the mean. See `~numpy.ufunc.reduce` for details.
3432 .. versionadded:: 1.20.0
3434 Returns
3435 -------
3436 m : ndarray, see dtype parameter above
3437 If `out=None`, returns a new array containing the mean values,
3438 otherwise a reference to the output array is returned.
3440 See Also
3441 --------
3442 average : Weighted average
3443 std, var, nanmean, nanstd, nanvar
3445 Notes
3446 -----
3447 The arithmetic mean is the sum of the elements along the axis divided
3448 by the number of elements.
3450 Note that for floating-point input, the mean is computed using the
3451 same precision the input has. Depending on the input data, this can
3452 cause the results to be inaccurate, especially for `float32` (see
3453 example below). Specifying a higher-precision accumulator using the
3454 `dtype` keyword can alleviate this issue.
3456 By default, `float16` results are computed using `float32` intermediates
3457 for extra precision.
3459 Examples
3460 --------
3461 >>> a = np.array([[1, 2], [3, 4]])
3462 >>> np.mean(a)
3463 2.5
3464 >>> np.mean(a, axis=0)
3465 array([2., 3.])
3466 >>> np.mean(a, axis=1)
3467 array([1.5, 3.5])
3469 In single precision, `mean` can be inaccurate:
3471 >>> a = np.zeros((2, 512*512), dtype=np.float32)
3472 >>> a[0, :] = 1.0
3473 >>> a[1, :] = 0.1
3474 >>> np.mean(a)
3475 0.54999924
3477 Computing the mean in float64 is more accurate:
3479 >>> np.mean(a, dtype=np.float64)
3480 0.55000000074505806 # may vary
3482 Specifying a where argument:
3484 >>> a = np.array([[5, 9, 13], [14, 10, 12], [11, 15, 19]])
3485 >>> np.mean(a)
3486 12.0
3487 >>> np.mean(a, where=[[True], [False], [False]])
3488 9.0
3490 """
3491 kwargs = {}
3492 if keepdims is not np._NoValue:
3493 kwargs['keepdims'] = keepdims
3494 if where is not np._NoValue:
3495 kwargs['where'] = where
3496 if type(a) is not mu.ndarray:
3497 try:
3498 mean = a.mean
3499 except AttributeError:
3500 pass
3501 else:
3502 return mean(axis=axis, dtype=dtype, out=out, **kwargs)
3504 return _methods._mean(a, axis=axis, dtype=dtype,
3505 out=out, **kwargs)
3508def _std_dispatcher(a, axis=None, dtype=None, out=None, ddof=None,
3509 keepdims=None, *, where=None):
3510 return (a, where, out)
3513@array_function_dispatch(_std_dispatcher)
3514def std(a, axis=None, dtype=None, out=None, ddof=0, keepdims=np._NoValue, *,
3515 where=np._NoValue):
3516 """
3517 Compute the standard deviation along the specified axis.
3519 Returns the standard deviation, a measure of the spread of a distribution,
3520 of the array elements. The standard deviation is computed for the
3521 flattened array by default, otherwise over the specified axis.
3523 Parameters
3524 ----------
3525 a : array_like
3526 Calculate the standard deviation of these values.
3527 axis : None or int or tuple of ints, optional
3528 Axis or axes along which the standard deviation is computed. The
3529 default is to compute the standard deviation of the flattened array.
3531 .. versionadded:: 1.7.0
3533 If this is a tuple of ints, a standard deviation is performed over
3534 multiple axes, instead of a single axis or all the axes as before.
3535 dtype : dtype, optional
3536 Type to use in computing the standard deviation. For arrays of
3537 integer type the default is float64, for arrays of float types it is
3538 the same as the array type.
3539 out : ndarray, optional
3540 Alternative output array in which to place the result. It must have
3541 the same shape as the expected output but the type (of the calculated
3542 values) will be cast if necessary.
3543 ddof : int, optional
3544 Means Delta Degrees of Freedom. The divisor used in calculations
3545 is ``N - ddof``, where ``N`` represents the number of elements.
3546 By default `ddof` is zero.
3547 keepdims : bool, optional
3548 If this is set to True, the axes which are reduced are left
3549 in the result as dimensions with size one. With this option,
3550 the result will broadcast correctly against the input array.
3552 If the default value is passed, then `keepdims` will not be
3553 passed through to the `std` method of sub-classes of
3554 `ndarray`, however any non-default value will be. If the
3555 sub-class' method does not implement `keepdims` any
3556 exceptions will be raised.
3558 where : array_like of bool, optional
3559 Elements to include in the standard deviation.
3560 See `~numpy.ufunc.reduce` for details.
3562 .. versionadded:: 1.20.0
3564 Returns
3565 -------
3566 standard_deviation : ndarray, see dtype parameter above.
3567 If `out` is None, return a new array containing the standard deviation,
3568 otherwise return a reference to the output array.
3570 See Also
3571 --------
3572 var, mean, nanmean, nanstd, nanvar
3573 :ref:`ufuncs-output-type`
3575 Notes
3576 -----
3577 The standard deviation is the square root of the average of the squared
3578 deviations from the mean, i.e., ``std = sqrt(mean(x))``, where
3579 ``x = abs(a - a.mean())**2``.
3581 The average squared deviation is typically calculated as ``x.sum() / N``,
3582 where ``N = len(x)``. If, however, `ddof` is specified, the divisor
3583 ``N - ddof`` is used instead. In standard statistical practice, ``ddof=1``
3584 provides an unbiased estimator of the variance of the infinite population.
3585 ``ddof=0`` provides a maximum likelihood estimate of the variance for
3586 normally distributed variables. The standard deviation computed in this
3587 function is the square root of the estimated variance, so even with
3588 ``ddof=1``, it will not be an unbiased estimate of the standard deviation
3589 per se.
3591 Note that, for complex numbers, `std` takes the absolute
3592 value before squaring, so that the result is always real and nonnegative.
3594 For floating-point input, the *std* is computed using the same
3595 precision the input has. Depending on the input data, this can cause
3596 the results to be inaccurate, especially for float32 (see example below).
3597 Specifying a higher-accuracy accumulator using the `dtype` keyword can
3598 alleviate this issue.
3600 Examples
3601 --------
3602 >>> a = np.array([[1, 2], [3, 4]])
3603 >>> np.std(a)
3604 1.1180339887498949 # may vary
3605 >>> np.std(a, axis=0)
3606 array([1., 1.])
3607 >>> np.std(a, axis=1)
3608 array([0.5, 0.5])
3610 In single precision, std() can be inaccurate:
3612 >>> a = np.zeros((2, 512*512), dtype=np.float32)
3613 >>> a[0, :] = 1.0
3614 >>> a[1, :] = 0.1
3615 >>> np.std(a)
3616 0.45000005
3618 Computing the standard deviation in float64 is more accurate:
3620 >>> np.std(a, dtype=np.float64)
3621 0.44999999925494177 # may vary
3623 Specifying a where argument:
3625 >>> a = np.array([[14, 8, 11, 10], [7, 9, 10, 11], [10, 15, 5, 10]])
3626 >>> np.std(a)
3627 2.614064523559687 # may vary
3628 >>> np.std(a, where=[[True], [True], [False]])
3629 2.0
3631 """
3632 kwargs = {}
3633 if keepdims is not np._NoValue:
3634 kwargs['keepdims'] = keepdims
3635 if where is not np._NoValue:
3636 kwargs['where'] = where
3637 if type(a) is not mu.ndarray:
3638 try:
3639 std = a.std
3640 except AttributeError:
3641 pass
3642 else:
3643 return std(axis=axis, dtype=dtype, out=out, ddof=ddof, **kwargs)
3645 return _methods._std(a, axis=axis, dtype=dtype, out=out, ddof=ddof,
3646 **kwargs)
3649def _var_dispatcher(a, axis=None, dtype=None, out=None, ddof=None,
3650 keepdims=None, *, where=None):
3651 return (a, where, out)
3654@array_function_dispatch(_var_dispatcher)
3655def var(a, axis=None, dtype=None, out=None, ddof=0, keepdims=np._NoValue, *,
3656 where=np._NoValue):
3657 """
3658 Compute the variance along the specified axis.
3660 Returns the variance of the array elements, a measure of the spread of a
3661 distribution. The variance is computed for the flattened array by
3662 default, otherwise over the specified axis.
3664 Parameters
3665 ----------
3666 a : array_like
3667 Array containing numbers whose variance is desired. If `a` is not an
3668 array, a conversion is attempted.
3669 axis : None or int or tuple of ints, optional
3670 Axis or axes along which the variance is computed. The default is to
3671 compute the variance of the flattened array.
3673 .. versionadded:: 1.7.0
3675 If this is a tuple of ints, a variance is performed over multiple axes,
3676 instead of a single axis or all the axes as before.
3677 dtype : data-type, optional
3678 Type to use in computing the variance. For arrays of integer type
3679 the default is `float64`; for arrays of float types it is the same as
3680 the array type.
3681 out : ndarray, optional
3682 Alternate output array in which to place the result. It must have
3683 the same shape as the expected output, but the type is cast if
3684 necessary.
3685 ddof : int, optional
3686 "Delta Degrees of Freedom": the divisor used in the calculation is
3687 ``N - ddof``, where ``N`` represents the number of elements. By
3688 default `ddof` is zero.
3689 keepdims : bool, optional
3690 If this is set to True, the axes which are reduced are left
3691 in the result as dimensions with size one. With this option,
3692 the result will broadcast correctly against the input array.
3694 If the default value is passed, then `keepdims` will not be
3695 passed through to the `var` method of sub-classes of
3696 `ndarray`, however any non-default value will be. If the
3697 sub-class' method does not implement `keepdims` any
3698 exceptions will be raised.
3700 where : array_like of bool, optional
3701 Elements to include in the variance. See `~numpy.ufunc.reduce` for
3702 details.
3704 .. versionadded:: 1.20.0
3706 Returns
3707 -------
3708 variance : ndarray, see dtype parameter above
3709 If ``out=None``, returns a new array containing the variance;
3710 otherwise, a reference to the output array is returned.
3712 See Also
3713 --------
3714 std, mean, nanmean, nanstd, nanvar
3715 :ref:`ufuncs-output-type`
3717 Notes
3718 -----
3719 The variance is the average of the squared deviations from the mean,
3720 i.e., ``var = mean(x)``, where ``x = abs(a - a.mean())**2``.
3722 The mean is typically calculated as ``x.sum() / N``, where ``N = len(x)``.
3723 If, however, `ddof` is specified, the divisor ``N - ddof`` is used
3724 instead. In standard statistical practice, ``ddof=1`` provides an
3725 unbiased estimator of the variance of a hypothetical infinite population.
3726 ``ddof=0`` provides a maximum likelihood estimate of the variance for
3727 normally distributed variables.
3729 Note that for complex numbers, the absolute value is taken before
3730 squaring, so that the result is always real and nonnegative.
3732 For floating-point input, the variance is computed using the same
3733 precision the input has. Depending on the input data, this can cause
3734 the results to be inaccurate, especially for `float32` (see example
3735 below). Specifying a higher-accuracy accumulator using the ``dtype``
3736 keyword can alleviate this issue.
3738 Examples
3739 --------
3740 >>> a = np.array([[1, 2], [3, 4]])
3741 >>> np.var(a)
3742 1.25
3743 >>> np.var(a, axis=0)
3744 array([1., 1.])
3745 >>> np.var(a, axis=1)
3746 array([0.25, 0.25])
3748 In single precision, var() can be inaccurate:
3750 >>> a = np.zeros((2, 512*512), dtype=np.float32)
3751 >>> a[0, :] = 1.0
3752 >>> a[1, :] = 0.1
3753 >>> np.var(a)
3754 0.20250003
3756 Computing the variance in float64 is more accurate:
3758 >>> np.var(a, dtype=np.float64)
3759 0.20249999932944759 # may vary
3760 >>> ((1-0.55)**2 + (0.1-0.55)**2)/2
3761 0.2025
3763 Specifying a where argument:
3765 >>> a = np.array([[14, 8, 11, 10], [7, 9, 10, 11], [10, 15, 5, 10]])
3766 >>> np.var(a)
3767 6.833333333333333 # may vary
3768 >>> np.var(a, where=[[True], [True], [False]])
3769 4.0
3771 """
3772 kwargs = {}
3773 if keepdims is not np._NoValue:
3774 kwargs['keepdims'] = keepdims
3775 if where is not np._NoValue:
3776 kwargs['where'] = where
3778 if type(a) is not mu.ndarray:
3779 try:
3780 var = a.var
3782 except AttributeError:
3783 pass
3784 else:
3785 return var(axis=axis, dtype=dtype, out=out, ddof=ddof, **kwargs)
3787 return _methods._var(a, axis=axis, dtype=dtype, out=out, ddof=ddof,
3788 **kwargs)
3791# Aliases of other functions. Provided unique docstrings
3792# are for reference purposes only. Wherever possible,
3793# avoid using them.
3796def _round__dispatcher(a, decimals=None, out=None):
3797 # 2023-02-28, 1.25.0
3798 warnings.warn("`round_` is deprecated as of NumPy 1.25.0, and will be "
3799 "removed in NumPy 2.0. Please use `round` instead.",
3800 DeprecationWarning, stacklevel=3)
3801 return (a, out)
3804@array_function_dispatch(_round__dispatcher)
3805def round_(a, decimals=0, out=None):
3806 """
3807 Round an array to the given number of decimals.
3809 `~numpy.round_` is a disrecommended backwards-compatibility
3810 alias of `~numpy.around` and `~numpy.round`.
3812 .. deprecated:: 1.25.0
3813 ``round_`` is deprecated as of NumPy 1.25.0, and will be
3814 removed in NumPy 2.0. Please use `round` instead.
3816 See Also
3817 --------
3818 around : equivalent function; see for details.
3819 """
3820 return around(a, decimals=decimals, out=out)
3823def _product_dispatcher(a, axis=None, dtype=None, out=None, keepdims=None,
3824 initial=None, where=None):
3825 # 2023-03-02, 1.25.0
3826 warnings.warn("`product` is deprecated as of NumPy 1.25.0, and will be "
3827 "removed in NumPy 2.0. Please use `prod` instead.",
3828 DeprecationWarning, stacklevel=3)
3829 return (a, out)
3832@array_function_dispatch(_product_dispatcher, verify=False)
3833def product(*args, **kwargs):
3834 """
3835 Return the product of array elements over a given axis.
3837 .. deprecated:: 1.25.0
3838 ``product`` is deprecated as of NumPy 1.25.0, and will be
3839 removed in NumPy 2.0. Please use `prod` instead.
3841 See Also
3842 --------
3843 prod : equivalent function; see for details.
3844 """
3845 return prod(*args, **kwargs)
3848def _cumproduct_dispatcher(a, axis=None, dtype=None, out=None):
3849 # 2023-03-02, 1.25.0
3850 warnings.warn("`cumproduct` is deprecated as of NumPy 1.25.0, and will be "
3851 "removed in NumPy 2.0. Please use `cumprod` instead.",
3852 DeprecationWarning, stacklevel=3)
3853 return (a, out)
3856@array_function_dispatch(_cumproduct_dispatcher, verify=False)
3857def cumproduct(*args, **kwargs):
3858 """
3859 Return the cumulative product over the given axis.
3861 .. deprecated:: 1.25.0
3862 ``cumproduct`` is deprecated as of NumPy 1.25.0, and will be
3863 removed in NumPy 2.0. Please use `cumprod` instead.
3865 See Also
3866 --------
3867 cumprod : equivalent function; see for details.
3868 """
3869 return cumprod(*args, **kwargs)
3872def _sometrue_dispatcher(a, axis=None, out=None, keepdims=None, *,
3873 where=np._NoValue):
3874 # 2023-03-02, 1.25.0
3875 warnings.warn("`sometrue` is deprecated as of NumPy 1.25.0, and will be "
3876 "removed in NumPy 2.0. Please use `any` instead.",
3877 DeprecationWarning, stacklevel=3)
3878 return (a, where, out)
3881@array_function_dispatch(_sometrue_dispatcher, verify=False)
3882def sometrue(*args, **kwargs):
3883 """
3884 Check whether some values are true.
3886 Refer to `any` for full documentation.
3888 .. deprecated:: 1.25.0
3889 ``sometrue`` is deprecated as of NumPy 1.25.0, and will be
3890 removed in NumPy 2.0. Please use `any` instead.
3892 See Also
3893 --------
3894 any : equivalent function; see for details.
3895 """
3896 return any(*args, **kwargs)
3899def _alltrue_dispatcher(a, axis=None, out=None, keepdims=None, *, where=None):
3900 # 2023-03-02, 1.25.0
3901 warnings.warn("`alltrue` is deprecated as of NumPy 1.25.0, and will be "
3902 "removed in NumPy 2.0. Please use `all` instead.",
3903 DeprecationWarning, stacklevel=3)
3904 return (a, where, out)
3907@array_function_dispatch(_alltrue_dispatcher, verify=False)
3908def alltrue(*args, **kwargs):
3909 """
3910 Check if all elements of input array are true.
3912 .. deprecated:: 1.25.0
3913 ``alltrue`` is deprecated as of NumPy 1.25.0, and will be
3914 removed in NumPy 2.0. Please use `all` instead.
3916 See Also
3917 --------
3918 numpy.all : Equivalent function; see for details.
3919 """
3920 return all(*args, **kwargs)