Coverage for /var/srv/projects/api.amasfac.comuna18.com/tmp/venv/lib/python3.9/site-packages/numpy/core/fromnumeric.py: 34%
356 statements
« prev ^ index » next coverage.py v6.4.4, created at 2023-07-17 14:22 -0600
« prev ^ index » next coverage.py v6.4.4, created at 2023-07-17 14:22 -0600
1"""Module containing non-deprecated functions borrowed from Numeric.
3"""
4import functools
5import types
6import warnings
8import numpy as np
9from . import multiarray as mu
10from . import overrides
11from . import umath as um
12from . import numerictypes as nt
13from .multiarray import asarray, array, asanyarray, concatenate
14from . import _methods
16_dt_ = nt.sctype2char
18# functions that are methods
19__all__ = [
20 'all', 'alltrue', 'amax', 'amin', 'any', 'argmax',
21 'argmin', 'argpartition', 'argsort', 'around', 'choose', 'clip',
22 'compress', 'cumprod', 'cumproduct', 'cumsum', 'diagonal', 'mean',
23 'ndim', 'nonzero', 'partition', 'prod', 'product', 'ptp', 'put',
24 'ravel', 'repeat', 'reshape', 'resize', 'round_',
25 'searchsorted', 'shape', 'size', 'sometrue', 'sort', 'squeeze',
26 'std', 'sum', 'swapaxes', 'take', 'trace', 'transpose', 'var',
27]
29_gentype = types.GeneratorType
30# save away Python sum
31_sum_ = sum
33array_function_dispatch = functools.partial(
34 overrides.array_function_dispatch, module='numpy')
37# functions that are now methods
38def _wrapit(obj, method, *args, **kwds):
39 try:
40 wrap = obj.__array_wrap__
41 except AttributeError:
42 wrap = None
43 result = getattr(asarray(obj), method)(*args, **kwds)
44 if wrap:
45 if not isinstance(result, mu.ndarray):
46 result = asarray(result)
47 result = wrap(result)
48 return result
51def _wrapfunc(obj, method, *args, **kwds):
52 bound = getattr(obj, method, None)
53 if bound is None:
54 return _wrapit(obj, method, *args, **kwds)
56 try:
57 return bound(*args, **kwds)
58 except TypeError:
59 # A TypeError occurs if the object does have such a method in its
60 # class, but its signature is not identical to that of NumPy's. This
61 # situation has occurred in the case of a downstream library like
62 # 'pandas'.
63 #
64 # Call _wrapit from within the except clause to ensure a potential
65 # exception has a traceback chain.
66 return _wrapit(obj, method, *args, **kwds)
69def _wrapreduction(obj, ufunc, method, axis, dtype, out, **kwargs):
70 passkwargs = {k: v for k, v in kwargs.items()
71 if v is not np._NoValue}
73 if type(obj) is not mu.ndarray:
74 try:
75 reduction = getattr(obj, method)
76 except AttributeError:
77 pass
78 else:
79 # This branch is needed for reductions like any which don't
80 # support a dtype.
81 if dtype is not None:
82 return reduction(axis=axis, dtype=dtype, out=out, **passkwargs)
83 else:
84 return reduction(axis=axis, out=out, **passkwargs)
86 return ufunc.reduce(obj, axis, dtype, out, **passkwargs)
89def _take_dispatcher(a, indices, axis=None, out=None, mode=None):
90 return (a, out)
93@array_function_dispatch(_take_dispatcher)
94def take(a, indices, axis=None, out=None, mode='raise'):
95 """
96 Take elements from an array along an axis.
98 When axis is not None, this function does the same thing as "fancy"
99 indexing (indexing arrays using arrays); however, it can be easier to use
100 if you need elements along a given axis. A call such as
101 ``np.take(arr, indices, axis=3)`` is equivalent to
102 ``arr[:,:,:,indices,...]``.
104 Explained without fancy indexing, this is equivalent to the following use
105 of `ndindex`, which sets each of ``ii``, ``jj``, and ``kk`` to a tuple of
106 indices::
108 Ni, Nk = a.shape[:axis], a.shape[axis+1:]
109 Nj = indices.shape
110 for ii in ndindex(Ni):
111 for jj in ndindex(Nj):
112 for kk in ndindex(Nk):
113 out[ii + jj + kk] = a[ii + (indices[jj],) + kk]
115 Parameters
116 ----------
117 a : array_like (Ni..., M, Nk...)
118 The source array.
119 indices : array_like (Nj...)
120 The indices of the values to extract.
122 .. versionadded:: 1.8.0
124 Also allow scalars for indices.
125 axis : int, optional
126 The axis over which to select values. By default, the flattened
127 input array is used.
128 out : ndarray, optional (Ni..., Nj..., Nk...)
129 If provided, the result will be placed in this array. It should
130 be of the appropriate shape and dtype. Note that `out` is always
131 buffered if `mode='raise'`; use other modes for better performance.
132 mode : {'raise', 'wrap', 'clip'}, optional
133 Specifies how out-of-bounds indices will behave.
135 * 'raise' -- raise an error (default)
136 * 'wrap' -- wrap around
137 * 'clip' -- clip to the range
139 'clip' mode means that all indices that are too large are replaced
140 by the index that addresses the last element along that axis. Note
141 that this disables indexing with negative numbers.
143 Returns
144 -------
145 out : ndarray (Ni..., Nj..., Nk...)
146 The returned array has the same type as `a`.
148 See Also
149 --------
150 compress : Take elements using a boolean mask
151 ndarray.take : equivalent method
152 take_along_axis : Take elements by matching the array and the index arrays
154 Notes
155 -----
157 By eliminating the inner loop in the description above, and using `s_` to
158 build simple slice objects, `take` can be expressed in terms of applying
159 fancy indexing to each 1-d slice::
161 Ni, Nk = a.shape[:axis], a.shape[axis+1:]
162 for ii in ndindex(Ni):
163 for kk in ndindex(Nj):
164 out[ii + s_[...,] + kk] = a[ii + s_[:,] + kk][indices]
166 For this reason, it is equivalent to (but faster than) the following use
167 of `apply_along_axis`::
169 out = np.apply_along_axis(lambda a_1d: a_1d[indices], axis, a)
171 Examples
172 --------
173 >>> a = [4, 3, 5, 7, 6, 8]
174 >>> indices = [0, 1, 4]
175 >>> np.take(a, indices)
176 array([4, 3, 6])
178 In this example if `a` is an ndarray, "fancy" indexing can be used.
180 >>> a = np.array(a)
181 >>> a[indices]
182 array([4, 3, 6])
184 If `indices` is not one dimensional, the output also has these dimensions.
186 >>> np.take(a, [[0, 1], [2, 3]])
187 array([[4, 3],
188 [5, 7]])
189 """
190 return _wrapfunc(a, 'take', indices, axis=axis, out=out, mode=mode)
193def _reshape_dispatcher(a, newshape, order=None):
194 return (a,)
197# not deprecated --- copy if necessary, view otherwise
198@array_function_dispatch(_reshape_dispatcher)
199def reshape(a, newshape, order='C'):
200 """
201 Gives a new shape to an array without changing its data.
203 Parameters
204 ----------
205 a : array_like
206 Array to be reshaped.
207 newshape : int or tuple of ints
208 The new shape should be compatible with the original shape. If
209 an integer, then the result will be a 1-D array of that length.
210 One shape dimension can be -1. In this case, the value is
211 inferred from the length of the array and remaining dimensions.
212 order : {'C', 'F', 'A'}, optional
213 Read the elements of `a` using this index order, and place the
214 elements into the reshaped array using this index order. 'C'
215 means to read / write the elements using C-like index order,
216 with the last axis index changing fastest, back to the first
217 axis index changing slowest. 'F' means to read / write the
218 elements using Fortran-like index order, with the first index
219 changing fastest, and the last index changing slowest. Note that
220 the 'C' and 'F' options take no account of the memory layout of
221 the underlying array, and only refer to the order of indexing.
222 'A' means to read / write the elements in Fortran-like index
223 order if `a` is Fortran *contiguous* in memory, C-like order
224 otherwise.
226 Returns
227 -------
228 reshaped_array : ndarray
229 This will be a new view object if possible; otherwise, it will
230 be a copy. Note there is no guarantee of the *memory layout* (C- or
231 Fortran- contiguous) of the returned array.
233 See Also
234 --------
235 ndarray.reshape : Equivalent method.
237 Notes
238 -----
239 It is not always possible to change the shape of an array without
240 copying the data. If you want an error to be raised when the data is copied,
241 you should assign the new shape to the shape attribute of the array::
243 >>> a = np.zeros((10, 2))
245 # A transpose makes the array non-contiguous
246 >>> b = a.T
248 # Taking a view makes it possible to modify the shape without modifying
249 # the initial object.
250 >>> c = b.view()
251 >>> c.shape = (20)
252 Traceback (most recent call last):
253 ...
254 AttributeError: Incompatible shape for in-place modification. Use
255 `.reshape()` to make a copy with the desired shape.
257 The `order` keyword gives the index ordering both for *fetching* the values
258 from `a`, and then *placing* the values into the output array.
259 For example, let's say you have an array:
261 >>> a = np.arange(6).reshape((3, 2))
262 >>> a
263 array([[0, 1],
264 [2, 3],
265 [4, 5]])
267 You can think of reshaping as first raveling the array (using the given
268 index order), then inserting the elements from the raveled array into the
269 new array using the same kind of index ordering as was used for the
270 raveling.
272 >>> np.reshape(a, (2, 3)) # C-like index ordering
273 array([[0, 1, 2],
274 [3, 4, 5]])
275 >>> np.reshape(np.ravel(a), (2, 3)) # equivalent to C ravel then C reshape
276 array([[0, 1, 2],
277 [3, 4, 5]])
278 >>> np.reshape(a, (2, 3), order='F') # Fortran-like index ordering
279 array([[0, 4, 3],
280 [2, 1, 5]])
281 >>> np.reshape(np.ravel(a, order='F'), (2, 3), order='F')
282 array([[0, 4, 3],
283 [2, 1, 5]])
285 Examples
286 --------
287 >>> a = np.array([[1,2,3], [4,5,6]])
288 >>> np.reshape(a, 6)
289 array([1, 2, 3, 4, 5, 6])
290 >>> np.reshape(a, 6, order='F')
291 array([1, 4, 2, 5, 3, 6])
293 >>> np.reshape(a, (3,-1)) # the unspecified value is inferred to be 2
294 array([[1, 2],
295 [3, 4],
296 [5, 6]])
297 """
298 return _wrapfunc(a, 'reshape', newshape, order=order)
301def _choose_dispatcher(a, choices, out=None, mode=None):
302 yield a
303 yield from choices
304 yield out
307@array_function_dispatch(_choose_dispatcher)
308def choose(a, choices, out=None, mode='raise'):
309 """
310 Construct an array from an index array and a list of arrays to choose from.
312 First of all, if confused or uncertain, definitely look at the Examples -
313 in its full generality, this function is less simple than it might
314 seem from the following code description (below ndi =
315 `numpy.lib.index_tricks`):
317 ``np.choose(a,c) == np.array([c[a[I]][I] for I in ndi.ndindex(a.shape)])``.
319 But this omits some subtleties. Here is a fully general summary:
321 Given an "index" array (`a`) of integers and a sequence of ``n`` arrays
322 (`choices`), `a` and each choice array are first broadcast, as necessary,
323 to arrays of a common shape; calling these *Ba* and *Bchoices[i], i =
324 0,...,n-1* we have that, necessarily, ``Ba.shape == Bchoices[i].shape``
325 for each ``i``. Then, a new array with shape ``Ba.shape`` is created as
326 follows:
328 * if ``mode='raise'`` (the default), then, first of all, each element of
329 ``a`` (and thus ``Ba``) must be in the range ``[0, n-1]``; now, suppose
330 that ``i`` (in that range) is the value at the ``(j0, j1, ..., jm)``
331 position in ``Ba`` - then the value at the same position in the new array
332 is the value in ``Bchoices[i]`` at that same position;
334 * if ``mode='wrap'``, values in `a` (and thus `Ba`) may be any (signed)
335 integer; modular arithmetic is used to map integers outside the range
336 `[0, n-1]` back into that range; and then the new array is constructed
337 as above;
339 * if ``mode='clip'``, values in `a` (and thus ``Ba``) may be any (signed)
340 integer; negative integers are mapped to 0; values greater than ``n-1``
341 are mapped to ``n-1``; and then the new array is constructed as above.
343 Parameters
344 ----------
345 a : int array
346 This array must contain integers in ``[0, n-1]``, where ``n`` is the
347 number of choices, unless ``mode=wrap`` or ``mode=clip``, in which
348 cases any integers are permissible.
349 choices : sequence of arrays
350 Choice arrays. `a` and all of the choices must be broadcastable to the
351 same shape. If `choices` is itself an array (not recommended), then
352 its outermost dimension (i.e., the one corresponding to
353 ``choices.shape[0]``) is taken as defining the "sequence".
354 out : array, optional
355 If provided, the result will be inserted into this array. It should
356 be of the appropriate shape and dtype. Note that `out` is always
357 buffered if ``mode='raise'``; use other modes for better performance.
358 mode : {'raise' (default), 'wrap', 'clip'}, optional
359 Specifies how indices outside ``[0, n-1]`` will be treated:
361 * 'raise' : an exception is raised
362 * 'wrap' : value becomes value mod ``n``
363 * 'clip' : values < 0 are mapped to 0, values > n-1 are mapped to n-1
365 Returns
366 -------
367 merged_array : array
368 The merged result.
370 Raises
371 ------
372 ValueError: shape mismatch
373 If `a` and each choice array are not all broadcastable to the same
374 shape.
376 See Also
377 --------
378 ndarray.choose : equivalent method
379 numpy.take_along_axis : Preferable if `choices` is an array
381 Notes
382 -----
383 To reduce the chance of misinterpretation, even though the following
384 "abuse" is nominally supported, `choices` should neither be, nor be
385 thought of as, a single array, i.e., the outermost sequence-like container
386 should be either a list or a tuple.
388 Examples
389 --------
391 >>> choices = [[0, 1, 2, 3], [10, 11, 12, 13],
392 ... [20, 21, 22, 23], [30, 31, 32, 33]]
393 >>> np.choose([2, 3, 1, 0], choices
394 ... # the first element of the result will be the first element of the
395 ... # third (2+1) "array" in choices, namely, 20; the second element
396 ... # will be the second element of the fourth (3+1) choice array, i.e.,
397 ... # 31, etc.
398 ... )
399 array([20, 31, 12, 3])
400 >>> np.choose([2, 4, 1, 0], choices, mode='clip') # 4 goes to 3 (4-1)
401 array([20, 31, 12, 3])
402 >>> # because there are 4 choice arrays
403 >>> np.choose([2, 4, 1, 0], choices, mode='wrap') # 4 goes to (4 mod 4)
404 array([20, 1, 12, 3])
405 >>> # i.e., 0
407 A couple examples illustrating how choose broadcasts:
409 >>> a = [[1, 0, 1], [0, 1, 0], [1, 0, 1]]
410 >>> choices = [-10, 10]
411 >>> np.choose(a, choices)
412 array([[ 10, -10, 10],
413 [-10, 10, -10],
414 [ 10, -10, 10]])
416 >>> # With thanks to Anne Archibald
417 >>> a = np.array([0, 1]).reshape((2,1,1))
418 >>> c1 = np.array([1, 2, 3]).reshape((1,3,1))
419 >>> c2 = np.array([-1, -2, -3, -4, -5]).reshape((1,1,5))
420 >>> np.choose(a, (c1, c2)) # result is 2x3x5, res[0,:,:]=c1, res[1,:,:]=c2
421 array([[[ 1, 1, 1, 1, 1],
422 [ 2, 2, 2, 2, 2],
423 [ 3, 3, 3, 3, 3]],
424 [[-1, -2, -3, -4, -5],
425 [-1, -2, -3, -4, -5],
426 [-1, -2, -3, -4, -5]]])
428 """
429 return _wrapfunc(a, 'choose', choices, out=out, mode=mode)
432def _repeat_dispatcher(a, repeats, axis=None):
433 return (a,)
436@array_function_dispatch(_repeat_dispatcher)
437def repeat(a, repeats, axis=None):
438 """
439 Repeat elements of an array.
441 Parameters
442 ----------
443 a : array_like
444 Input array.
445 repeats : int or array of ints
446 The number of repetitions for each element. `repeats` is broadcasted
447 to fit the shape of the given axis.
448 axis : int, optional
449 The axis along which to repeat values. By default, use the
450 flattened input array, and return a flat output array.
452 Returns
453 -------
454 repeated_array : ndarray
455 Output array which has the same shape as `a`, except along
456 the given axis.
458 See Also
459 --------
460 tile : Tile an array.
461 unique : Find the unique elements of an array.
463 Examples
464 --------
465 >>> np.repeat(3, 4)
466 array([3, 3, 3, 3])
467 >>> x = np.array([[1,2],[3,4]])
468 >>> np.repeat(x, 2)
469 array([1, 1, 2, 2, 3, 3, 4, 4])
470 >>> np.repeat(x, 3, axis=1)
471 array([[1, 1, 1, 2, 2, 2],
472 [3, 3, 3, 4, 4, 4]])
473 >>> np.repeat(x, [1, 2], axis=0)
474 array([[1, 2],
475 [3, 4],
476 [3, 4]])
478 """
479 return _wrapfunc(a, 'repeat', repeats, axis=axis)
482def _put_dispatcher(a, ind, v, mode=None):
483 return (a, ind, v)
486@array_function_dispatch(_put_dispatcher)
487def put(a, ind, v, mode='raise'):
488 """
489 Replaces specified elements of an array with given values.
491 The indexing works on the flattened target array. `put` is roughly
492 equivalent to:
494 ::
496 a.flat[ind] = v
498 Parameters
499 ----------
500 a : ndarray
501 Target array.
502 ind : array_like
503 Target indices, interpreted as integers.
504 v : array_like
505 Values to place in `a` at target indices. If `v` is shorter than
506 `ind` it will be repeated as necessary.
507 mode : {'raise', 'wrap', 'clip'}, optional
508 Specifies how out-of-bounds indices will behave.
510 * 'raise' -- raise an error (default)
511 * 'wrap' -- wrap around
512 * 'clip' -- clip to the range
514 'clip' mode means that all indices that are too large are replaced
515 by the index that addresses the last element along that axis. Note
516 that this disables indexing with negative numbers. In 'raise' mode,
517 if an exception occurs the target array may still be modified.
519 See Also
520 --------
521 putmask, place
522 put_along_axis : Put elements by matching the array and the index arrays
524 Examples
525 --------
526 >>> a = np.arange(5)
527 >>> np.put(a, [0, 2], [-44, -55])
528 >>> a
529 array([-44, 1, -55, 3, 4])
531 >>> a = np.arange(5)
532 >>> np.put(a, 22, -5, mode='clip')
533 >>> a
534 array([ 0, 1, 2, 3, -5])
536 """
537 try:
538 put = a.put
539 except AttributeError as e:
540 raise TypeError("argument 1 must be numpy.ndarray, "
541 "not {name}".format(name=type(a).__name__)) from e
543 return put(ind, v, mode=mode)
546def _swapaxes_dispatcher(a, axis1, axis2):
547 return (a,)
550@array_function_dispatch(_swapaxes_dispatcher)
551def swapaxes(a, axis1, axis2):
552 """
553 Interchange two axes of an array.
555 Parameters
556 ----------
557 a : array_like
558 Input array.
559 axis1 : int
560 First axis.
561 axis2 : int
562 Second axis.
564 Returns
565 -------
566 a_swapped : ndarray
567 For NumPy >= 1.10.0, if `a` is an ndarray, then a view of `a` is
568 returned; otherwise a new array is created. For earlier NumPy
569 versions a view of `a` is returned only if the order of the
570 axes is changed, otherwise the input array is returned.
572 Examples
573 --------
574 >>> x = np.array([[1,2,3]])
575 >>> np.swapaxes(x,0,1)
576 array([[1],
577 [2],
578 [3]])
580 >>> x = np.array([[[0,1],[2,3]],[[4,5],[6,7]]])
581 >>> x
582 array([[[0, 1],
583 [2, 3]],
584 [[4, 5],
585 [6, 7]]])
587 >>> np.swapaxes(x,0,2)
588 array([[[0, 4],
589 [2, 6]],
590 [[1, 5],
591 [3, 7]]])
593 """
594 return _wrapfunc(a, 'swapaxes', axis1, axis2)
597def _transpose_dispatcher(a, axes=None):
598 return (a,)
601@array_function_dispatch(_transpose_dispatcher)
602def transpose(a, axes=None):
603 """
604 Reverse or permute the axes of an array; returns the modified array.
606 For an array a with two axes, transpose(a) gives the matrix transpose.
608 Refer to `numpy.ndarray.transpose` for full documentation.
610 Parameters
611 ----------
612 a : array_like
613 Input array.
614 axes : tuple or list of ints, optional
615 If specified, it must be a tuple or list which contains a permutation of
616 [0,1,..,N-1] where N is the number of axes of a. The i'th axis of the
617 returned array will correspond to the axis numbered ``axes[i]`` of the
618 input. If not specified, defaults to ``range(a.ndim)[::-1]``, which
619 reverses the order of the axes.
621 Returns
622 -------
623 p : ndarray
624 `a` with its axes permuted. A view is returned whenever
625 possible.
627 See Also
628 --------
629 ndarray.transpose : Equivalent method
630 moveaxis
631 argsort
633 Notes
634 -----
635 Use `transpose(a, argsort(axes))` to invert the transposition of tensors
636 when using the `axes` keyword argument.
638 Transposing a 1-D array returns an unchanged view of the original array.
640 Examples
641 --------
642 >>> x = np.arange(4).reshape((2,2))
643 >>> x
644 array([[0, 1],
645 [2, 3]])
647 >>> np.transpose(x)
648 array([[0, 2],
649 [1, 3]])
651 >>> x = np.ones((1, 2, 3))
652 >>> np.transpose(x, (1, 0, 2)).shape
653 (2, 1, 3)
655 >>> x = np.ones((2, 3, 4, 5))
656 >>> np.transpose(x).shape
657 (5, 4, 3, 2)
659 """
660 return _wrapfunc(a, 'transpose', axes)
663def _partition_dispatcher(a, kth, axis=None, kind=None, order=None):
664 return (a,)
667@array_function_dispatch(_partition_dispatcher)
668def partition(a, kth, axis=-1, kind='introselect', order=None):
669 """
670 Return a partitioned copy of an array.
672 Creates a copy of the array with its elements rearranged in such a
673 way that the value of the element in k-th position is in the
674 position it would be in a sorted array. All elements smaller than
675 the k-th element are moved before this element and all equal or
676 greater are moved behind it. The ordering of the elements in the two
677 partitions is undefined.
679 .. versionadded:: 1.8.0
681 Parameters
682 ----------
683 a : array_like
684 Array to be sorted.
685 kth : int or sequence of ints
686 Element index to partition by. The k-th value of the element
687 will be in its final sorted position and all smaller elements
688 will be moved before it and all equal or greater elements behind
689 it. The order of all elements in the partitions is undefined. If
690 provided with a sequence of k-th it will partition all elements
691 indexed by k-th of them into their sorted position at once.
693 .. deprecated:: 1.22.0
694 Passing booleans as index is deprecated.
695 axis : int or None, optional
696 Axis along which to sort. If None, the array is flattened before
697 sorting. The default is -1, which sorts along the last axis.
698 kind : {'introselect'}, optional
699 Selection algorithm. Default is 'introselect'.
700 order : str or list of str, optional
701 When `a` is an array with fields defined, this argument
702 specifies which fields to compare first, second, etc. A single
703 field can be specified as a string. Not all fields need be
704 specified, but unspecified fields will still be used, in the
705 order in which they come up in the dtype, to break ties.
707 Returns
708 -------
709 partitioned_array : ndarray
710 Array of the same type and shape as `a`.
712 See Also
713 --------
714 ndarray.partition : Method to sort an array in-place.
715 argpartition : Indirect partition.
716 sort : Full sorting
718 Notes
719 -----
720 The various selection algorithms are characterized by their average
721 speed, worst case performance, work space size, and whether they are
722 stable. A stable sort keeps items with the same key in the same
723 relative order. The available algorithms have the following
724 properties:
726 ================= ======= ============= ============ =======
727 kind speed worst case work space stable
728 ================= ======= ============= ============ =======
729 'introselect' 1 O(n) 0 no
730 ================= ======= ============= ============ =======
732 All the partition algorithms make temporary copies of the data when
733 partitioning along any but the last axis. Consequently,
734 partitioning along the last axis is faster and uses less space than
735 partitioning along any other axis.
737 The sort order for complex numbers is lexicographic. If both the
738 real and imaginary parts are non-nan then the order is determined by
739 the real parts except when they are equal, in which case the order
740 is determined by the imaginary parts.
742 Examples
743 --------
744 >>> a = np.array([3, 4, 2, 1])
745 >>> np.partition(a, 3)
746 array([2, 1, 3, 4])
748 >>> np.partition(a, (1, 3))
749 array([1, 2, 3, 4])
751 """
752 if axis is None:
753 # flatten returns (1, N) for np.matrix, so always use the last axis
754 a = asanyarray(a).flatten()
755 axis = -1
756 else:
757 a = asanyarray(a).copy(order="K")
758 a.partition(kth, axis=axis, kind=kind, order=order)
759 return a
762def _argpartition_dispatcher(a, kth, axis=None, kind=None, order=None):
763 return (a,)
766@array_function_dispatch(_argpartition_dispatcher)
767def argpartition(a, kth, axis=-1, kind='introselect', order=None):
768 """
769 Perform an indirect partition along the given axis using the
770 algorithm specified by the `kind` keyword. It returns an array of
771 indices of the same shape as `a` that index data along the given
772 axis in partitioned order.
774 .. versionadded:: 1.8.0
776 Parameters
777 ----------
778 a : array_like
779 Array to sort.
780 kth : int or sequence of ints
781 Element index to partition by. The k-th element will be in its
782 final sorted position and all smaller elements will be moved
783 before it and all larger elements behind it. The order all
784 elements in the partitions is undefined. If provided with a
785 sequence of k-th it will partition all of them into their sorted
786 position at once.
788 .. deprecated:: 1.22.0
789 Passing booleans as index is deprecated.
790 axis : int or None, optional
791 Axis along which to sort. The default is -1 (the last axis). If
792 None, the flattened array is used.
793 kind : {'introselect'}, optional
794 Selection algorithm. Default is 'introselect'
795 order : str or list of str, optional
796 When `a` is an array with fields defined, this argument
797 specifies which fields to compare first, second, etc. A single
798 field can be specified as a string, and not all fields need be
799 specified, but unspecified fields will still be used, in the
800 order in which they come up in the dtype, to break ties.
802 Returns
803 -------
804 index_array : ndarray, int
805 Array of indices that partition `a` along the specified axis.
806 If `a` is one-dimensional, ``a[index_array]`` yields a partitioned `a`.
807 More generally, ``np.take_along_axis(a, index_array, axis)``
808 always yields the partitioned `a`, irrespective of dimensionality.
810 See Also
811 --------
812 partition : Describes partition algorithms used.
813 ndarray.partition : Inplace partition.
814 argsort : Full indirect sort.
815 take_along_axis : Apply ``index_array`` from argpartition
816 to an array as if by calling partition.
818 Notes
819 -----
820 See `partition` for notes on the different selection algorithms.
822 Examples
823 --------
824 One dimensional array:
826 >>> x = np.array([3, 4, 2, 1])
827 >>> x[np.argpartition(x, 3)]
828 array([2, 1, 3, 4])
829 >>> x[np.argpartition(x, (1, 3))]
830 array([1, 2, 3, 4])
832 >>> x = [3, 4, 2, 1]
833 >>> np.array(x)[np.argpartition(x, 3)]
834 array([2, 1, 3, 4])
836 Multi-dimensional array:
838 >>> x = np.array([[3, 4, 2], [1, 3, 1]])
839 >>> index_array = np.argpartition(x, kth=1, axis=-1)
840 >>> np.take_along_axis(x, index_array, axis=-1) # same as np.partition(x, kth=1)
841 array([[2, 3, 4],
842 [1, 1, 3]])
844 """
845 return _wrapfunc(a, 'argpartition', kth, axis=axis, kind=kind, order=order)
848def _sort_dispatcher(a, axis=None, kind=None, order=None):
849 return (a,)
852@array_function_dispatch(_sort_dispatcher)
853def sort(a, axis=-1, kind=None, order=None):
854 """
855 Return a sorted copy of an array.
857 Parameters
858 ----------
859 a : array_like
860 Array to be sorted.
861 axis : int or None, optional
862 Axis along which to sort. If None, the array is flattened before
863 sorting. The default is -1, which sorts along the last axis.
864 kind : {'quicksort', 'mergesort', 'heapsort', 'stable'}, optional
865 Sorting algorithm. The default is 'quicksort'. Note that both 'stable'
866 and 'mergesort' use timsort or radix sort under the covers and, in general,
867 the actual implementation will vary with data type. The 'mergesort' option
868 is retained for backwards compatibility.
870 .. versionchanged:: 1.15.0.
871 The 'stable' option was added.
873 order : str or list of str, optional
874 When `a` is an array with fields defined, this argument specifies
875 which fields to compare first, second, etc. A single field can
876 be specified as a string, and not all fields need be specified,
877 but unspecified fields will still be used, in the order in which
878 they come up in the dtype, to break ties.
880 Returns
881 -------
882 sorted_array : ndarray
883 Array of the same type and shape as `a`.
885 See Also
886 --------
887 ndarray.sort : Method to sort an array in-place.
888 argsort : Indirect sort.
889 lexsort : Indirect stable sort on multiple keys.
890 searchsorted : Find elements in a sorted array.
891 partition : Partial sort.
893 Notes
894 -----
895 The various sorting algorithms are characterized by their average speed,
896 worst case performance, work space size, and whether they are stable. A
897 stable sort keeps items with the same key in the same relative
898 order. The four algorithms implemented in NumPy have the following
899 properties:
901 =========== ======= ============= ============ ========
902 kind speed worst case work space stable
903 =========== ======= ============= ============ ========
904 'quicksort' 1 O(n^2) 0 no
905 'heapsort' 3 O(n*log(n)) 0 no
906 'mergesort' 2 O(n*log(n)) ~n/2 yes
907 'timsort' 2 O(n*log(n)) ~n/2 yes
908 =========== ======= ============= ============ ========
910 .. note:: The datatype determines which of 'mergesort' or 'timsort'
911 is actually used, even if 'mergesort' is specified. User selection
912 at a finer scale is not currently available.
914 All the sort algorithms make temporary copies of the data when
915 sorting along any but the last axis. Consequently, sorting along
916 the last axis is faster and uses less space than sorting along
917 any other axis.
919 The sort order for complex numbers is lexicographic. If both the real
920 and imaginary parts are non-nan then the order is determined by the
921 real parts except when they are equal, in which case the order is
922 determined by the imaginary parts.
924 Previous to numpy 1.4.0 sorting real and complex arrays containing nan
925 values led to undefined behaviour. In numpy versions >= 1.4.0 nan
926 values are sorted to the end. The extended sort order is:
928 * Real: [R, nan]
929 * Complex: [R + Rj, R + nanj, nan + Rj, nan + nanj]
931 where R is a non-nan real value. Complex values with the same nan
932 placements are sorted according to the non-nan part if it exists.
933 Non-nan values are sorted as before.
935 .. versionadded:: 1.12.0
937 quicksort has been changed to `introsort <https://en.wikipedia.org/wiki/Introsort>`_.
938 When sorting does not make enough progress it switches to
939 `heapsort <https://en.wikipedia.org/wiki/Heapsort>`_.
940 This implementation makes quicksort O(n*log(n)) in the worst case.
942 'stable' automatically chooses the best stable sorting algorithm
943 for the data type being sorted.
944 It, along with 'mergesort' is currently mapped to
945 `timsort <https://en.wikipedia.org/wiki/Timsort>`_
946 or `radix sort <https://en.wikipedia.org/wiki/Radix_sort>`_
947 depending on the data type.
948 API forward compatibility currently limits the
949 ability to select the implementation and it is hardwired for the different
950 data types.
952 .. versionadded:: 1.17.0
954 Timsort is added for better performance on already or nearly
955 sorted data. On random data timsort is almost identical to
956 mergesort. It is now used for stable sort while quicksort is still the
957 default sort if none is chosen. For timsort details, refer to
958 `CPython listsort.txt <https://github.com/python/cpython/blob/3.7/Objects/listsort.txt>`_.
959 'mergesort' and 'stable' are mapped to radix sort for integer data types. Radix sort is an
960 O(n) sort instead of O(n log n).
962 .. versionchanged:: 1.18.0
964 NaT now sorts to the end of arrays for consistency with NaN.
966 Examples
967 --------
968 >>> a = np.array([[1,4],[3,1]])
969 >>> np.sort(a) # sort along the last axis
970 array([[1, 4],
971 [1, 3]])
972 >>> np.sort(a, axis=None) # sort the flattened array
973 array([1, 1, 3, 4])
974 >>> np.sort(a, axis=0) # sort along the first axis
975 array([[1, 1],
976 [3, 4]])
978 Use the `order` keyword to specify a field to use when sorting a
979 structured array:
981 >>> dtype = [('name', 'S10'), ('height', float), ('age', int)]
982 >>> values = [('Arthur', 1.8, 41), ('Lancelot', 1.9, 38),
983 ... ('Galahad', 1.7, 38)]
984 >>> a = np.array(values, dtype=dtype) # create a structured array
985 >>> np.sort(a, order='height') # doctest: +SKIP
986 array([('Galahad', 1.7, 38), ('Arthur', 1.8, 41),
987 ('Lancelot', 1.8999999999999999, 38)],
988 dtype=[('name', '|S10'), ('height', '<f8'), ('age', '<i4')])
990 Sort by age, then height if ages are equal:
992 >>> np.sort(a, order=['age', 'height']) # doctest: +SKIP
993 array([('Galahad', 1.7, 38), ('Lancelot', 1.8999999999999999, 38),
994 ('Arthur', 1.8, 41)],
995 dtype=[('name', '|S10'), ('height', '<f8'), ('age', '<i4')])
997 """
998 if axis is None:
999 # flatten returns (1, N) for np.matrix, so always use the last axis
1000 a = asanyarray(a).flatten()
1001 axis = -1
1002 else:
1003 a = asanyarray(a).copy(order="K")
1004 a.sort(axis=axis, kind=kind, order=order)
1005 return a
1008def _argsort_dispatcher(a, axis=None, kind=None, order=None):
1009 return (a,)
1012@array_function_dispatch(_argsort_dispatcher)
1013def argsort(a, axis=-1, kind=None, order=None):
1014 """
1015 Returns the indices that would sort an array.
1017 Perform an indirect sort along the given axis using the algorithm specified
1018 by the `kind` keyword. It returns an array of indices of the same shape as
1019 `a` that index data along the given axis in sorted order.
1021 Parameters
1022 ----------
1023 a : array_like
1024 Array to sort.
1025 axis : int or None, optional
1026 Axis along which to sort. The default is -1 (the last axis). If None,
1027 the flattened array is used.
1028 kind : {'quicksort', 'mergesort', 'heapsort', 'stable'}, optional
1029 Sorting algorithm. The default is 'quicksort'. Note that both 'stable'
1030 and 'mergesort' use timsort under the covers and, in general, the
1031 actual implementation will vary with data type. The 'mergesort' option
1032 is retained for backwards compatibility.
1034 .. versionchanged:: 1.15.0.
1035 The 'stable' option was added.
1036 order : str or list of str, optional
1037 When `a` is an array with fields defined, this argument specifies
1038 which fields to compare first, second, etc. A single field can
1039 be specified as a string, and not all fields need be specified,
1040 but unspecified fields will still be used, in the order in which
1041 they come up in the dtype, to break ties.
1043 Returns
1044 -------
1045 index_array : ndarray, int
1046 Array of indices that sort `a` along the specified `axis`.
1047 If `a` is one-dimensional, ``a[index_array]`` yields a sorted `a`.
1048 More generally, ``np.take_along_axis(a, index_array, axis=axis)``
1049 always yields the sorted `a`, irrespective of dimensionality.
1051 See Also
1052 --------
1053 sort : Describes sorting algorithms used.
1054 lexsort : Indirect stable sort with multiple keys.
1055 ndarray.sort : Inplace sort.
1056 argpartition : Indirect partial sort.
1057 take_along_axis : Apply ``index_array`` from argsort
1058 to an array as if by calling sort.
1060 Notes
1061 -----
1062 See `sort` for notes on the different sorting algorithms.
1064 As of NumPy 1.4.0 `argsort` works with real/complex arrays containing
1065 nan values. The enhanced sort order is documented in `sort`.
1067 Examples
1068 --------
1069 One dimensional array:
1071 >>> x = np.array([3, 1, 2])
1072 >>> np.argsort(x)
1073 array([1, 2, 0])
1075 Two-dimensional array:
1077 >>> x = np.array([[0, 3], [2, 2]])
1078 >>> x
1079 array([[0, 3],
1080 [2, 2]])
1082 >>> ind = np.argsort(x, axis=0) # sorts along first axis (down)
1083 >>> ind
1084 array([[0, 1],
1085 [1, 0]])
1086 >>> np.take_along_axis(x, ind, axis=0) # same as np.sort(x, axis=0)
1087 array([[0, 2],
1088 [2, 3]])
1090 >>> ind = np.argsort(x, axis=1) # sorts along last axis (across)
1091 >>> ind
1092 array([[0, 1],
1093 [0, 1]])
1094 >>> np.take_along_axis(x, ind, axis=1) # same as np.sort(x, axis=1)
1095 array([[0, 3],
1096 [2, 2]])
1098 Indices of the sorted elements of a N-dimensional array:
1100 >>> ind = np.unravel_index(np.argsort(x, axis=None), x.shape)
1101 >>> ind
1102 (array([0, 1, 1, 0]), array([0, 0, 1, 1]))
1103 >>> x[ind] # same as np.sort(x, axis=None)
1104 array([0, 2, 2, 3])
1106 Sorting with keys:
1108 >>> x = np.array([(1, 0), (0, 1)], dtype=[('x', '<i4'), ('y', '<i4')])
1109 >>> x
1110 array([(1, 0), (0, 1)],
1111 dtype=[('x', '<i4'), ('y', '<i4')])
1113 >>> np.argsort(x, order=('x','y'))
1114 array([1, 0])
1116 >>> np.argsort(x, order=('y','x'))
1117 array([0, 1])
1119 """
1120 return _wrapfunc(a, 'argsort', axis=axis, kind=kind, order=order)
1123def _argmax_dispatcher(a, axis=None, out=None, *, keepdims=np._NoValue):
1124 return (a, out)
1127@array_function_dispatch(_argmax_dispatcher)
1128def argmax(a, axis=None, out=None, *, keepdims=np._NoValue):
1129 """
1130 Returns the indices of the maximum values along an axis.
1132 Parameters
1133 ----------
1134 a : array_like
1135 Input array.
1136 axis : int, optional
1137 By default, the index is into the flattened array, otherwise
1138 along the specified axis.
1139 out : array, optional
1140 If provided, the result will be inserted into this array. It should
1141 be of the appropriate shape and dtype.
1142 keepdims : bool, optional
1143 If this is set to True, the axes which are reduced are left
1144 in the result as dimensions with size one. With this option,
1145 the result will broadcast correctly against the array.
1147 .. versionadded:: 1.22.0
1149 Returns
1150 -------
1151 index_array : ndarray of ints
1152 Array of indices into the array. It has the same shape as `a.shape`
1153 with the dimension along `axis` removed. If `keepdims` is set to True,
1154 then the size of `axis` will be 1 with the resulting array having same
1155 shape as `a.shape`.
1157 See Also
1158 --------
1159 ndarray.argmax, argmin
1160 amax : The maximum value along a given axis.
1161 unravel_index : Convert a flat index into an index tuple.
1162 take_along_axis : Apply ``np.expand_dims(index_array, axis)``
1163 from argmax to an array as if by calling max.
1165 Notes
1166 -----
1167 In case of multiple occurrences of the maximum values, the indices
1168 corresponding to the first occurrence are returned.
1170 Examples
1171 --------
1172 >>> a = np.arange(6).reshape(2,3) + 10
1173 >>> a
1174 array([[10, 11, 12],
1175 [13, 14, 15]])
1176 >>> np.argmax(a)
1177 5
1178 >>> np.argmax(a, axis=0)
1179 array([1, 1, 1])
1180 >>> np.argmax(a, axis=1)
1181 array([2, 2])
1183 Indexes of the maximal elements of a N-dimensional array:
1185 >>> ind = np.unravel_index(np.argmax(a, axis=None), a.shape)
1186 >>> ind
1187 (1, 2)
1188 >>> a[ind]
1189 15
1191 >>> b = np.arange(6)
1192 >>> b[1] = 5
1193 >>> b
1194 array([0, 5, 2, 3, 4, 5])
1195 >>> np.argmax(b) # Only the first occurrence is returned.
1196 1
1198 >>> x = np.array([[4,2,3], [1,0,3]])
1199 >>> index_array = np.argmax(x, axis=-1)
1200 >>> # Same as np.amax(x, axis=-1, keepdims=True)
1201 >>> np.take_along_axis(x, np.expand_dims(index_array, axis=-1), axis=-1)
1202 array([[4],
1203 [3]])
1204 >>> # Same as np.amax(x, axis=-1)
1205 >>> np.take_along_axis(x, np.expand_dims(index_array, axis=-1), axis=-1).squeeze(axis=-1)
1206 array([4, 3])
1208 Setting `keepdims` to `True`,
1210 >>> x = np.arange(24).reshape((2, 3, 4))
1211 >>> res = np.argmax(x, axis=1, keepdims=True)
1212 >>> res.shape
1213 (2, 1, 4)
1214 """
1215 kwds = {'keepdims': keepdims} if keepdims is not np._NoValue else {}
1216 return _wrapfunc(a, 'argmax', axis=axis, out=out, **kwds)
1219def _argmin_dispatcher(a, axis=None, out=None, *, keepdims=np._NoValue):
1220 return (a, out)
1223@array_function_dispatch(_argmin_dispatcher)
1224def argmin(a, axis=None, out=None, *, keepdims=np._NoValue):
1225 """
1226 Returns the indices of the minimum values along an axis.
1228 Parameters
1229 ----------
1230 a : array_like
1231 Input array.
1232 axis : int, optional
1233 By default, the index is into the flattened array, otherwise
1234 along the specified axis.
1235 out : array, optional
1236 If provided, the result will be inserted into this array. It should
1237 be of the appropriate shape and dtype.
1238 keepdims : bool, optional
1239 If this is set to True, the axes which are reduced are left
1240 in the result as dimensions with size one. With this option,
1241 the result will broadcast correctly against the array.
1243 .. versionadded:: 1.22.0
1245 Returns
1246 -------
1247 index_array : ndarray of ints
1248 Array of indices into the array. It has the same shape as `a.shape`
1249 with the dimension along `axis` removed. If `keepdims` is set to True,
1250 then the size of `axis` will be 1 with the resulting array having same
1251 shape as `a.shape`.
1253 See Also
1254 --------
1255 ndarray.argmin, argmax
1256 amin : The minimum value along a given axis.
1257 unravel_index : Convert a flat index into an index tuple.
1258 take_along_axis : Apply ``np.expand_dims(index_array, axis)``
1259 from argmin to an array as if by calling min.
1261 Notes
1262 -----
1263 In case of multiple occurrences of the minimum values, the indices
1264 corresponding to the first occurrence are returned.
1266 Examples
1267 --------
1268 >>> a = np.arange(6).reshape(2,3) + 10
1269 >>> a
1270 array([[10, 11, 12],
1271 [13, 14, 15]])
1272 >>> np.argmin(a)
1273 0
1274 >>> np.argmin(a, axis=0)
1275 array([0, 0, 0])
1276 >>> np.argmin(a, axis=1)
1277 array([0, 0])
1279 Indices of the minimum elements of a N-dimensional array:
1281 >>> ind = np.unravel_index(np.argmin(a, axis=None), a.shape)
1282 >>> ind
1283 (0, 0)
1284 >>> a[ind]
1285 10
1287 >>> b = np.arange(6) + 10
1288 >>> b[4] = 10
1289 >>> b
1290 array([10, 11, 12, 13, 10, 15])
1291 >>> np.argmin(b) # Only the first occurrence is returned.
1292 0
1294 >>> x = np.array([[4,2,3], [1,0,3]])
1295 >>> index_array = np.argmin(x, axis=-1)
1296 >>> # Same as np.amin(x, axis=-1, keepdims=True)
1297 >>> np.take_along_axis(x, np.expand_dims(index_array, axis=-1), axis=-1)
1298 array([[2],
1299 [0]])
1300 >>> # Same as np.amax(x, axis=-1)
1301 >>> np.take_along_axis(x, np.expand_dims(index_array, axis=-1), axis=-1).squeeze(axis=-1)
1302 array([2, 0])
1304 Setting `keepdims` to `True`,
1306 >>> x = np.arange(24).reshape((2, 3, 4))
1307 >>> res = np.argmin(x, axis=1, keepdims=True)
1308 >>> res.shape
1309 (2, 1, 4)
1310 """
1311 kwds = {'keepdims': keepdims} if keepdims is not np._NoValue else {}
1312 return _wrapfunc(a, 'argmin', axis=axis, out=out, **kwds)
1315def _searchsorted_dispatcher(a, v, side=None, sorter=None):
1316 return (a, v, sorter)
1319@array_function_dispatch(_searchsorted_dispatcher)
1320def searchsorted(a, v, side='left', sorter=None):
1321 """
1322 Find indices where elements should be inserted to maintain order.
1324 Find the indices into a sorted array `a` such that, if the
1325 corresponding elements in `v` were inserted before the indices, the
1326 order of `a` would be preserved.
1328 Assuming that `a` is sorted:
1330 ====== ============================
1331 `side` returned index `i` satisfies
1332 ====== ============================
1333 left ``a[i-1] < v <= a[i]``
1334 right ``a[i-1] <= v < a[i]``
1335 ====== ============================
1337 Parameters
1338 ----------
1339 a : 1-D array_like
1340 Input array. If `sorter` is None, then it must be sorted in
1341 ascending order, otherwise `sorter` must be an array of indices
1342 that sort it.
1343 v : array_like
1344 Values to insert into `a`.
1345 side : {'left', 'right'}, optional
1346 If 'left', the index of the first suitable location found is given.
1347 If 'right', return the last such index. If there is no suitable
1348 index, return either 0 or N (where N is the length of `a`).
1349 sorter : 1-D array_like, optional
1350 Optional array of integer indices that sort array a into ascending
1351 order. They are typically the result of argsort.
1353 .. versionadded:: 1.7.0
1355 Returns
1356 -------
1357 indices : int or array of ints
1358 Array of insertion points with the same shape as `v`,
1359 or an integer if `v` is a scalar.
1361 See Also
1362 --------
1363 sort : Return a sorted copy of an array.
1364 histogram : Produce histogram from 1-D data.
1366 Notes
1367 -----
1368 Binary search is used to find the required insertion points.
1370 As of NumPy 1.4.0 `searchsorted` works with real/complex arrays containing
1371 `nan` values. The enhanced sort order is documented in `sort`.
1373 This function uses the same algorithm as the builtin python `bisect.bisect_left`
1374 (``side='left'``) and `bisect.bisect_right` (``side='right'``) functions,
1375 which is also vectorized in the `v` argument.
1377 Examples
1378 --------
1379 >>> np.searchsorted([1,2,3,4,5], 3)
1380 2
1381 >>> np.searchsorted([1,2,3,4,5], 3, side='right')
1382 3
1383 >>> np.searchsorted([1,2,3,4,5], [-10, 10, 2, 3])
1384 array([0, 5, 1, 2])
1386 """
1387 return _wrapfunc(a, 'searchsorted', v, side=side, sorter=sorter)
1390def _resize_dispatcher(a, new_shape):
1391 return (a,)
1394@array_function_dispatch(_resize_dispatcher)
1395def resize(a, new_shape):
1396 """
1397 Return a new array with the specified shape.
1399 If the new array is larger than the original array, then the new
1400 array is filled with repeated copies of `a`. Note that this behavior
1401 is different from a.resize(new_shape) which fills with zeros instead
1402 of repeated copies of `a`.
1404 Parameters
1405 ----------
1406 a : array_like
1407 Array to be resized.
1409 new_shape : int or tuple of int
1410 Shape of resized array.
1412 Returns
1413 -------
1414 reshaped_array : ndarray
1415 The new array is formed from the data in the old array, repeated
1416 if necessary to fill out the required number of elements. The
1417 data are repeated iterating over the array in C-order.
1419 See Also
1420 --------
1421 numpy.reshape : Reshape an array without changing the total size.
1422 numpy.pad : Enlarge and pad an array.
1423 numpy.repeat : Repeat elements of an array.
1424 ndarray.resize : resize an array in-place.
1426 Notes
1427 -----
1428 When the total size of the array does not change `~numpy.reshape` should
1429 be used. In most other cases either indexing (to reduce the size)
1430 or padding (to increase the size) may be a more appropriate solution.
1432 Warning: This functionality does **not** consider axes separately,
1433 i.e. it does not apply interpolation/extrapolation.
1434 It fills the return array with the required number of elements, iterating
1435 over `a` in C-order, disregarding axes (and cycling back from the start if
1436 the new shape is larger). This functionality is therefore not suitable to
1437 resize images, or data where each axis represents a separate and distinct
1438 entity.
1440 Examples
1441 --------
1442 >>> a=np.array([[0,1],[2,3]])
1443 >>> np.resize(a,(2,3))
1444 array([[0, 1, 2],
1445 [3, 0, 1]])
1446 >>> np.resize(a,(1,4))
1447 array([[0, 1, 2, 3]])
1448 >>> np.resize(a,(2,4))
1449 array([[0, 1, 2, 3],
1450 [0, 1, 2, 3]])
1452 """
1453 if isinstance(new_shape, (int, nt.integer)):
1454 new_shape = (new_shape,)
1456 a = ravel(a)
1458 new_size = 1
1459 for dim_length in new_shape:
1460 new_size *= dim_length
1461 if dim_length < 0:
1462 raise ValueError('all elements of `new_shape` must be non-negative')
1464 if a.size == 0 or new_size == 0:
1465 # First case must zero fill. The second would have repeats == 0.
1466 return np.zeros_like(a, shape=new_shape)
1468 repeats = -(-new_size // a.size) # ceil division
1469 a = concatenate((a,) * repeats)[:new_size]
1471 return reshape(a, new_shape)
1474def _squeeze_dispatcher(a, axis=None):
1475 return (a,)
1478@array_function_dispatch(_squeeze_dispatcher)
1479def squeeze(a, axis=None):
1480 """
1481 Remove axes of length one from `a`.
1483 Parameters
1484 ----------
1485 a : array_like
1486 Input data.
1487 axis : None or int or tuple of ints, optional
1488 .. versionadded:: 1.7.0
1490 Selects a subset of the entries of length one in the
1491 shape. If an axis is selected with shape entry greater than
1492 one, an error is raised.
1494 Returns
1495 -------
1496 squeezed : ndarray
1497 The input array, but with all or a subset of the
1498 dimensions of length 1 removed. This is always `a` itself
1499 or a view into `a`. Note that if all axes are squeezed,
1500 the result is a 0d array and not a scalar.
1502 Raises
1503 ------
1504 ValueError
1505 If `axis` is not None, and an axis being squeezed is not of length 1
1507 See Also
1508 --------
1509 expand_dims : The inverse operation, adding entries of length one
1510 reshape : Insert, remove, and combine dimensions, and resize existing ones
1512 Examples
1513 --------
1514 >>> x = np.array([[[0], [1], [2]]])
1515 >>> x.shape
1516 (1, 3, 1)
1517 >>> np.squeeze(x).shape
1518 (3,)
1519 >>> np.squeeze(x, axis=0).shape
1520 (3, 1)
1521 >>> np.squeeze(x, axis=1).shape
1522 Traceback (most recent call last):
1523 ...
1524 ValueError: cannot select an axis to squeeze out which has size not equal to one
1525 >>> np.squeeze(x, axis=2).shape
1526 (1, 3)
1527 >>> x = np.array([[1234]])
1528 >>> x.shape
1529 (1, 1)
1530 >>> np.squeeze(x)
1531 array(1234) # 0d array
1532 >>> np.squeeze(x).shape
1533 ()
1534 >>> np.squeeze(x)[()]
1535 1234
1537 """
1538 try:
1539 squeeze = a.squeeze
1540 except AttributeError:
1541 return _wrapit(a, 'squeeze', axis=axis)
1542 if axis is None:
1543 return squeeze()
1544 else:
1545 return squeeze(axis=axis)
1548def _diagonal_dispatcher(a, offset=None, axis1=None, axis2=None):
1549 return (a,)
1552@array_function_dispatch(_diagonal_dispatcher)
1553def diagonal(a, offset=0, axis1=0, axis2=1):
1554 """
1555 Return specified diagonals.
1557 If `a` is 2-D, returns the diagonal of `a` with the given offset,
1558 i.e., the collection of elements of the form ``a[i, i+offset]``. If
1559 `a` has more than two dimensions, then the axes specified by `axis1`
1560 and `axis2` are used to determine the 2-D sub-array whose diagonal is
1561 returned. The shape of the resulting array can be determined by
1562 removing `axis1` and `axis2` and appending an index to the right equal
1563 to the size of the resulting diagonals.
1565 In versions of NumPy prior to 1.7, this function always returned a new,
1566 independent array containing a copy of the values in the diagonal.
1568 In NumPy 1.7 and 1.8, it continues to return a copy of the diagonal,
1569 but depending on this fact is deprecated. Writing to the resulting
1570 array continues to work as it used to, but a FutureWarning is issued.
1572 Starting in NumPy 1.9 it returns a read-only view on the original array.
1573 Attempting to write to the resulting array will produce an error.
1575 In some future release, it will return a read/write view and writing to
1576 the returned array will alter your original array. The returned array
1577 will have the same type as the input array.
1579 If you don't write to the array returned by this function, then you can
1580 just ignore all of the above.
1582 If you depend on the current behavior, then we suggest copying the
1583 returned array explicitly, i.e., use ``np.diagonal(a).copy()`` instead
1584 of just ``np.diagonal(a)``. This will work with both past and future
1585 versions of NumPy.
1587 Parameters
1588 ----------
1589 a : array_like
1590 Array from which the diagonals are taken.
1591 offset : int, optional
1592 Offset of the diagonal from the main diagonal. Can be positive or
1593 negative. Defaults to main diagonal (0).
1594 axis1 : int, optional
1595 Axis to be used as the first axis of the 2-D sub-arrays from which
1596 the diagonals should be taken. Defaults to first axis (0).
1597 axis2 : int, optional
1598 Axis to be used as the second axis of the 2-D sub-arrays from
1599 which the diagonals should be taken. Defaults to second axis (1).
1601 Returns
1602 -------
1603 array_of_diagonals : ndarray
1604 If `a` is 2-D, then a 1-D array containing the diagonal and of the
1605 same type as `a` is returned unless `a` is a `matrix`, in which case
1606 a 1-D array rather than a (2-D) `matrix` is returned in order to
1607 maintain backward compatibility.
1609 If ``a.ndim > 2``, then the dimensions specified by `axis1` and `axis2`
1610 are removed, and a new axis inserted at the end corresponding to the
1611 diagonal.
1613 Raises
1614 ------
1615 ValueError
1616 If the dimension of `a` is less than 2.
1618 See Also
1619 --------
1620 diag : MATLAB work-a-like for 1-D and 2-D arrays.
1621 diagflat : Create diagonal arrays.
1622 trace : Sum along diagonals.
1624 Examples
1625 --------
1626 >>> a = np.arange(4).reshape(2,2)
1627 >>> a
1628 array([[0, 1],
1629 [2, 3]])
1630 >>> a.diagonal()
1631 array([0, 3])
1632 >>> a.diagonal(1)
1633 array([1])
1635 A 3-D example:
1637 >>> a = np.arange(8).reshape(2,2,2); a
1638 array([[[0, 1],
1639 [2, 3]],
1640 [[4, 5],
1641 [6, 7]]])
1642 >>> a.diagonal(0, # Main diagonals of two arrays created by skipping
1643 ... 0, # across the outer(left)-most axis last and
1644 ... 1) # the "middle" (row) axis first.
1645 array([[0, 6],
1646 [1, 7]])
1648 The sub-arrays whose main diagonals we just obtained; note that each
1649 corresponds to fixing the right-most (column) axis, and that the
1650 diagonals are "packed" in rows.
1652 >>> a[:,:,0] # main diagonal is [0 6]
1653 array([[0, 2],
1654 [4, 6]])
1655 >>> a[:,:,1] # main diagonal is [1 7]
1656 array([[1, 3],
1657 [5, 7]])
1659 The anti-diagonal can be obtained by reversing the order of elements
1660 using either `numpy.flipud` or `numpy.fliplr`.
1662 >>> a = np.arange(9).reshape(3, 3)
1663 >>> a
1664 array([[0, 1, 2],
1665 [3, 4, 5],
1666 [6, 7, 8]])
1667 >>> np.fliplr(a).diagonal() # Horizontal flip
1668 array([2, 4, 6])
1669 >>> np.flipud(a).diagonal() # Vertical flip
1670 array([6, 4, 2])
1672 Note that the order in which the diagonal is retrieved varies depending
1673 on the flip function.
1674 """
1675 if isinstance(a, np.matrix):
1676 # Make diagonal of matrix 1-D to preserve backward compatibility.
1677 return asarray(a).diagonal(offset=offset, axis1=axis1, axis2=axis2)
1678 else:
1679 return asanyarray(a).diagonal(offset=offset, axis1=axis1, axis2=axis2)
1682def _trace_dispatcher(
1683 a, offset=None, axis1=None, axis2=None, dtype=None, out=None):
1684 return (a, out)
1687@array_function_dispatch(_trace_dispatcher)
1688def trace(a, offset=0, axis1=0, axis2=1, dtype=None, out=None):
1689 """
1690 Return the sum along diagonals of the array.
1692 If `a` is 2-D, the sum along its diagonal with the given offset
1693 is returned, i.e., the sum of elements ``a[i,i+offset]`` for all i.
1695 If `a` has more than two dimensions, then the axes specified by axis1 and
1696 axis2 are used to determine the 2-D sub-arrays whose traces are returned.
1697 The shape of the resulting array is the same as that of `a` with `axis1`
1698 and `axis2` removed.
1700 Parameters
1701 ----------
1702 a : array_like
1703 Input array, from which the diagonals are taken.
1704 offset : int, optional
1705 Offset of the diagonal from the main diagonal. Can be both positive
1706 and negative. Defaults to 0.
1707 axis1, axis2 : int, optional
1708 Axes to be used as the first and second axis of the 2-D sub-arrays
1709 from which the diagonals should be taken. Defaults are the first two
1710 axes of `a`.
1711 dtype : dtype, optional
1712 Determines the data-type of the returned array and of the accumulator
1713 where the elements are summed. If dtype has the value None and `a` is
1714 of integer type of precision less than the default integer
1715 precision, then the default integer precision is used. Otherwise,
1716 the precision is the same as that of `a`.
1717 out : ndarray, optional
1718 Array into which the output is placed. Its type is preserved and
1719 it must be of the right shape to hold the output.
1721 Returns
1722 -------
1723 sum_along_diagonals : ndarray
1724 If `a` is 2-D, the sum along the diagonal is returned. If `a` has
1725 larger dimensions, then an array of sums along diagonals is returned.
1727 See Also
1728 --------
1729 diag, diagonal, diagflat
1731 Examples
1732 --------
1733 >>> np.trace(np.eye(3))
1734 3.0
1735 >>> a = np.arange(8).reshape((2,2,2))
1736 >>> np.trace(a)
1737 array([6, 8])
1739 >>> a = np.arange(24).reshape((2,2,2,3))
1740 >>> np.trace(a).shape
1741 (2, 3)
1743 """
1744 if isinstance(a, np.matrix):
1745 # Get trace of matrix via an array to preserve backward compatibility.
1746 return asarray(a).trace(offset=offset, axis1=axis1, axis2=axis2, dtype=dtype, out=out)
1747 else:
1748 return asanyarray(a).trace(offset=offset, axis1=axis1, axis2=axis2, dtype=dtype, out=out)
1751def _ravel_dispatcher(a, order=None):
1752 return (a,)
1755@array_function_dispatch(_ravel_dispatcher)
1756def ravel(a, order='C'):
1757 """Return a contiguous flattened array.
1759 A 1-D array, containing the elements of the input, is returned. A copy is
1760 made only if needed.
1762 As of NumPy 1.10, the returned array will have the same type as the input
1763 array. (for example, a masked array will be returned for a masked array
1764 input)
1766 Parameters
1767 ----------
1768 a : array_like
1769 Input array. The elements in `a` are read in the order specified by
1770 `order`, and packed as a 1-D array.
1771 order : {'C','F', 'A', 'K'}, optional
1773 The elements of `a` are read using this index order. 'C' means
1774 to index the elements in row-major, C-style order,
1775 with the last axis index changing fastest, back to the first
1776 axis index changing slowest. 'F' means to index the elements
1777 in column-major, Fortran-style order, with the
1778 first index changing fastest, and the last index changing
1779 slowest. Note that the 'C' and 'F' options take no account of
1780 the memory layout of the underlying array, and only refer to
1781 the order of axis indexing. 'A' means to read the elements in
1782 Fortran-like index order if `a` is Fortran *contiguous* in
1783 memory, C-like order otherwise. 'K' means to read the
1784 elements in the order they occur in memory, except for
1785 reversing the data when strides are negative. By default, 'C'
1786 index order is used.
1788 Returns
1789 -------
1790 y : array_like
1791 y is an array of the same subtype as `a`, with shape ``(a.size,)``.
1792 Note that matrices are special cased for backward compatibility, if `a`
1793 is a matrix, then y is a 1-D ndarray.
1795 See Also
1796 --------
1797 ndarray.flat : 1-D iterator over an array.
1798 ndarray.flatten : 1-D array copy of the elements of an array
1799 in row-major order.
1800 ndarray.reshape : Change the shape of an array without changing its data.
1802 Notes
1803 -----
1804 In row-major, C-style order, in two dimensions, the row index
1805 varies the slowest, and the column index the quickest. This can
1806 be generalized to multiple dimensions, where row-major order
1807 implies that the index along the first axis varies slowest, and
1808 the index along the last quickest. The opposite holds for
1809 column-major, Fortran-style index ordering.
1811 When a view is desired in as many cases as possible, ``arr.reshape(-1)``
1812 may be preferable.
1814 Examples
1815 --------
1816 It is equivalent to ``reshape(-1, order=order)``.
1818 >>> x = np.array([[1, 2, 3], [4, 5, 6]])
1819 >>> np.ravel(x)
1820 array([1, 2, 3, 4, 5, 6])
1822 >>> x.reshape(-1)
1823 array([1, 2, 3, 4, 5, 6])
1825 >>> np.ravel(x, order='F')
1826 array([1, 4, 2, 5, 3, 6])
1828 When ``order`` is 'A', it will preserve the array's 'C' or 'F' ordering:
1830 >>> np.ravel(x.T)
1831 array([1, 4, 2, 5, 3, 6])
1832 >>> np.ravel(x.T, order='A')
1833 array([1, 2, 3, 4, 5, 6])
1835 When ``order`` is 'K', it will preserve orderings that are neither 'C'
1836 nor 'F', but won't reverse axes:
1838 >>> a = np.arange(3)[::-1]; a
1839 array([2, 1, 0])
1840 >>> a.ravel(order='C')
1841 array([2, 1, 0])
1842 >>> a.ravel(order='K')
1843 array([2, 1, 0])
1845 >>> a = np.arange(12).reshape(2,3,2).swapaxes(1,2); a
1846 array([[[ 0, 2, 4],
1847 [ 1, 3, 5]],
1848 [[ 6, 8, 10],
1849 [ 7, 9, 11]]])
1850 >>> a.ravel(order='C')
1851 array([ 0, 2, 4, 1, 3, 5, 6, 8, 10, 7, 9, 11])
1852 >>> a.ravel(order='K')
1853 array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
1855 """
1856 if isinstance(a, np.matrix):
1857 return asarray(a).ravel(order=order)
1858 else:
1859 return asanyarray(a).ravel(order=order)
1862def _nonzero_dispatcher(a):
1863 return (a,)
1866@array_function_dispatch(_nonzero_dispatcher)
1867def nonzero(a):
1868 """
1869 Return the indices of the elements that are non-zero.
1871 Returns a tuple of arrays, one for each dimension of `a`,
1872 containing the indices of the non-zero elements in that
1873 dimension. The values in `a` are always tested and returned in
1874 row-major, C-style order.
1876 To group the indices by element, rather than dimension, use `argwhere`,
1877 which returns a row for each non-zero element.
1879 .. note::
1881 When called on a zero-d array or scalar, ``nonzero(a)`` is treated
1882 as ``nonzero(atleast_1d(a))``.
1884 .. deprecated:: 1.17.0
1886 Use `atleast_1d` explicitly if this behavior is deliberate.
1888 Parameters
1889 ----------
1890 a : array_like
1891 Input array.
1893 Returns
1894 -------
1895 tuple_of_arrays : tuple
1896 Indices of elements that are non-zero.
1898 See Also
1899 --------
1900 flatnonzero :
1901 Return indices that are non-zero in the flattened version of the input
1902 array.
1903 ndarray.nonzero :
1904 Equivalent ndarray method.
1905 count_nonzero :
1906 Counts the number of non-zero elements in the input array.
1908 Notes
1909 -----
1910 While the nonzero values can be obtained with ``a[nonzero(a)]``, it is
1911 recommended to use ``x[x.astype(bool)]`` or ``x[x != 0]`` instead, which
1912 will correctly handle 0-d arrays.
1914 Examples
1915 --------
1916 >>> x = np.array([[3, 0, 0], [0, 4, 0], [5, 6, 0]])
1917 >>> x
1918 array([[3, 0, 0],
1919 [0, 4, 0],
1920 [5, 6, 0]])
1921 >>> np.nonzero(x)
1922 (array([0, 1, 2, 2]), array([0, 1, 0, 1]))
1924 >>> x[np.nonzero(x)]
1925 array([3, 4, 5, 6])
1926 >>> np.transpose(np.nonzero(x))
1927 array([[0, 0],
1928 [1, 1],
1929 [2, 0],
1930 [2, 1]])
1932 A common use for ``nonzero`` is to find the indices of an array, where
1933 a condition is True. Given an array `a`, the condition `a` > 3 is a
1934 boolean array and since False is interpreted as 0, np.nonzero(a > 3)
1935 yields the indices of the `a` where the condition is true.
1937 >>> a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
1938 >>> a > 3
1939 array([[False, False, False],
1940 [ True, True, True],
1941 [ True, True, True]])
1942 >>> np.nonzero(a > 3)
1943 (array([1, 1, 1, 2, 2, 2]), array([0, 1, 2, 0, 1, 2]))
1945 Using this result to index `a` is equivalent to using the mask directly:
1947 >>> a[np.nonzero(a > 3)]
1948 array([4, 5, 6, 7, 8, 9])
1949 >>> a[a > 3] # prefer this spelling
1950 array([4, 5, 6, 7, 8, 9])
1952 ``nonzero`` can also be called as a method of the array.
1954 >>> (a > 3).nonzero()
1955 (array([1, 1, 1, 2, 2, 2]), array([0, 1, 2, 0, 1, 2]))
1957 """
1958 return _wrapfunc(a, 'nonzero')
1961def _shape_dispatcher(a):
1962 return (a,)
1965@array_function_dispatch(_shape_dispatcher)
1966def shape(a):
1967 """
1968 Return the shape of an array.
1970 Parameters
1971 ----------
1972 a : array_like
1973 Input array.
1975 Returns
1976 -------
1977 shape : tuple of ints
1978 The elements of the shape tuple give the lengths of the
1979 corresponding array dimensions.
1981 See Also
1982 --------
1983 len : ``len(a)`` is equivalent to ``np.shape(a)[0]`` for N-D arrays with
1984 ``N>=1``.
1985 ndarray.shape : Equivalent array method.
1987 Examples
1988 --------
1989 >>> np.shape(np.eye(3))
1990 (3, 3)
1991 >>> np.shape([[1, 3]])
1992 (1, 2)
1993 >>> np.shape([0])
1994 (1,)
1995 >>> np.shape(0)
1996 ()
1998 >>> a = np.array([(1, 2), (3, 4), (5, 6)],
1999 ... dtype=[('x', 'i4'), ('y', 'i4')])
2000 >>> np.shape(a)
2001 (3,)
2002 >>> a.shape
2003 (3,)
2005 """
2006 try:
2007 result = a.shape
2008 except AttributeError:
2009 result = asarray(a).shape
2010 return result
2013def _compress_dispatcher(condition, a, axis=None, out=None):
2014 return (condition, a, out)
2017@array_function_dispatch(_compress_dispatcher)
2018def compress(condition, a, axis=None, out=None):
2019 """
2020 Return selected slices of an array along given axis.
2022 When working along a given axis, a slice along that axis is returned in
2023 `output` for each index where `condition` evaluates to True. When
2024 working on a 1-D array, `compress` is equivalent to `extract`.
2026 Parameters
2027 ----------
2028 condition : 1-D array of bools
2029 Array that selects which entries to return. If len(condition)
2030 is less than the size of `a` along the given axis, then output is
2031 truncated to the length of the condition array.
2032 a : array_like
2033 Array from which to extract a part.
2034 axis : int, optional
2035 Axis along which to take slices. If None (default), work on the
2036 flattened array.
2037 out : ndarray, optional
2038 Output array. Its type is preserved and it must be of the right
2039 shape to hold the output.
2041 Returns
2042 -------
2043 compressed_array : ndarray
2044 A copy of `a` without the slices along axis for which `condition`
2045 is false.
2047 See Also
2048 --------
2049 take, choose, diag, diagonal, select
2050 ndarray.compress : Equivalent method in ndarray
2051 extract : Equivalent method when working on 1-D arrays
2052 :ref:`ufuncs-output-type`
2054 Examples
2055 --------
2056 >>> a = np.array([[1, 2], [3, 4], [5, 6]])
2057 >>> a
2058 array([[1, 2],
2059 [3, 4],
2060 [5, 6]])
2061 >>> np.compress([0, 1], a, axis=0)
2062 array([[3, 4]])
2063 >>> np.compress([False, True, True], a, axis=0)
2064 array([[3, 4],
2065 [5, 6]])
2066 >>> np.compress([False, True], a, axis=1)
2067 array([[2],
2068 [4],
2069 [6]])
2071 Working on the flattened array does not return slices along an axis but
2072 selects elements.
2074 >>> np.compress([False, True], a)
2075 array([2])
2077 """
2078 return _wrapfunc(a, 'compress', condition, axis=axis, out=out)
2081def _clip_dispatcher(a, a_min, a_max, out=None, **kwargs):
2082 return (a, a_min, a_max)
2085@array_function_dispatch(_clip_dispatcher)
2086def clip(a, a_min, a_max, out=None, **kwargs):
2087 """
2088 Clip (limit) the values in an array.
2090 Given an interval, values outside the interval are clipped to
2091 the interval edges. For example, if an interval of ``[0, 1]``
2092 is specified, values smaller than 0 become 0, and values larger
2093 than 1 become 1.
2095 Equivalent to but faster than ``np.minimum(a_max, np.maximum(a, a_min))``.
2097 No check is performed to ensure ``a_min < a_max``.
2099 Parameters
2100 ----------
2101 a : array_like
2102 Array containing elements to clip.
2103 a_min, a_max : array_like or None
2104 Minimum and maximum value. If ``None``, clipping is not performed on
2105 the corresponding edge. Only one of `a_min` and `a_max` may be
2106 ``None``. Both are broadcast against `a`.
2107 out : ndarray, optional
2108 The results will be placed in this array. It may be the input
2109 array for in-place clipping. `out` must be of the right shape
2110 to hold the output. Its type is preserved.
2111 **kwargs
2112 For other keyword-only arguments, see the
2113 :ref:`ufunc docs <ufuncs.kwargs>`.
2115 .. versionadded:: 1.17.0
2117 Returns
2118 -------
2119 clipped_array : ndarray
2120 An array with the elements of `a`, but where values
2121 < `a_min` are replaced with `a_min`, and those > `a_max`
2122 with `a_max`.
2124 See Also
2125 --------
2126 :ref:`ufuncs-output-type`
2128 Notes
2129 -----
2130 When `a_min` is greater than `a_max`, `clip` returns an
2131 array in which all values are equal to `a_max`,
2132 as shown in the second example.
2134 Examples
2135 --------
2136 >>> a = np.arange(10)
2137 >>> a
2138 array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
2139 >>> np.clip(a, 1, 8)
2140 array([1, 1, 2, 3, 4, 5, 6, 7, 8, 8])
2141 >>> np.clip(a, 8, 1)
2142 array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1])
2143 >>> np.clip(a, 3, 6, out=a)
2144 array([3, 3, 3, 3, 4, 5, 6, 6, 6, 6])
2145 >>> a
2146 array([3, 3, 3, 3, 4, 5, 6, 6, 6, 6])
2147 >>> a = np.arange(10)
2148 >>> a
2149 array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
2150 >>> np.clip(a, [3, 4, 1, 1, 1, 4, 4, 4, 4, 4], 8)
2151 array([3, 4, 2, 3, 4, 5, 6, 7, 8, 8])
2153 """
2154 return _wrapfunc(a, 'clip', a_min, a_max, out=out, **kwargs)
2157def _sum_dispatcher(a, axis=None, dtype=None, out=None, keepdims=None,
2158 initial=None, where=None):
2159 return (a, out)
2162@array_function_dispatch(_sum_dispatcher)
2163def sum(a, axis=None, dtype=None, out=None, keepdims=np._NoValue,
2164 initial=np._NoValue, where=np._NoValue):
2165 """
2166 Sum of array elements over a given axis.
2168 Parameters
2169 ----------
2170 a : array_like
2171 Elements to sum.
2172 axis : None or int or tuple of ints, optional
2173 Axis or axes along which a sum is performed. The default,
2174 axis=None, will sum all of the elements of the input array. If
2175 axis is negative it counts from the last to the first axis.
2177 .. versionadded:: 1.7.0
2179 If axis is a tuple of ints, a sum is performed on all of the axes
2180 specified in the tuple instead of a single axis or all the axes as
2181 before.
2182 dtype : dtype, optional
2183 The type of the returned array and of the accumulator in which the
2184 elements are summed. The dtype of `a` is used by default unless `a`
2185 has an integer dtype of less precision than the default platform
2186 integer. In that case, if `a` is signed then the platform integer
2187 is used while if `a` is unsigned then an unsigned integer of the
2188 same precision as the platform integer is used.
2189 out : ndarray, optional
2190 Alternative output array in which to place the result. It must have
2191 the same shape as the expected output, but the type of the output
2192 values will be cast if necessary.
2193 keepdims : bool, optional
2194 If this is set to True, the axes which are reduced are left
2195 in the result as dimensions with size one. With this option,
2196 the result will broadcast correctly against the input array.
2198 If the default value is passed, then `keepdims` will not be
2199 passed through to the `sum` method of sub-classes of
2200 `ndarray`, however any non-default value will be. If the
2201 sub-class' method does not implement `keepdims` any
2202 exceptions will be raised.
2203 initial : scalar, optional
2204 Starting value for the sum. See `~numpy.ufunc.reduce` for details.
2206 .. versionadded:: 1.15.0
2208 where : array_like of bool, optional
2209 Elements to include in the sum. See `~numpy.ufunc.reduce` for details.
2211 .. versionadded:: 1.17.0
2213 Returns
2214 -------
2215 sum_along_axis : ndarray
2216 An array with the same shape as `a`, with the specified
2217 axis removed. If `a` is a 0-d array, or if `axis` is None, a scalar
2218 is returned. If an output array is specified, a reference to
2219 `out` is returned.
2221 See Also
2222 --------
2223 ndarray.sum : Equivalent method.
2225 add.reduce : Equivalent functionality of `add`.
2227 cumsum : Cumulative sum of array elements.
2229 trapz : Integration of array values using the composite trapezoidal rule.
2231 mean, average
2233 Notes
2234 -----
2235 Arithmetic is modular when using integer types, and no error is
2236 raised on overflow.
2238 The sum of an empty array is the neutral element 0:
2240 >>> np.sum([])
2241 0.0
2243 For floating point numbers the numerical precision of sum (and
2244 ``np.add.reduce``) is in general limited by directly adding each number
2245 individually to the result causing rounding errors in every step.
2246 However, often numpy will use a numerically better approach (partial
2247 pairwise summation) leading to improved precision in many use-cases.
2248 This improved precision is always provided when no ``axis`` is given.
2249 When ``axis`` is given, it will depend on which axis is summed.
2250 Technically, to provide the best speed possible, the improved precision
2251 is only used when the summation is along the fast axis in memory.
2252 Note that the exact precision may vary depending on other parameters.
2253 In contrast to NumPy, Python's ``math.fsum`` function uses a slower but
2254 more precise approach to summation.
2255 Especially when summing a large number of lower precision floating point
2256 numbers, such as ``float32``, numerical errors can become significant.
2257 In such cases it can be advisable to use `dtype="float64"` to use a higher
2258 precision for the output.
2260 Examples
2261 --------
2262 >>> np.sum([0.5, 1.5])
2263 2.0
2264 >>> np.sum([0.5, 0.7, 0.2, 1.5], dtype=np.int32)
2265 1
2266 >>> np.sum([[0, 1], [0, 5]])
2267 6
2268 >>> np.sum([[0, 1], [0, 5]], axis=0)
2269 array([0, 6])
2270 >>> np.sum([[0, 1], [0, 5]], axis=1)
2271 array([1, 5])
2272 >>> np.sum([[0, 1], [np.nan, 5]], where=[False, True], axis=1)
2273 array([1., 5.])
2275 If the accumulator is too small, overflow occurs:
2277 >>> np.ones(128, dtype=np.int8).sum(dtype=np.int8)
2278 -128
2280 You can also start the sum with a value other than zero:
2282 >>> np.sum([10], initial=5)
2283 15
2284 """
2285 if isinstance(a, _gentype):
2286 # 2018-02-25, 1.15.0
2287 warnings.warn(
2288 "Calling np.sum(generator) is deprecated, and in the future will give a different result. "
2289 "Use np.sum(np.fromiter(generator)) or the python sum builtin instead.",
2290 DeprecationWarning, stacklevel=3)
2292 res = _sum_(a)
2293 if out is not None:
2294 out[...] = res
2295 return out
2296 return res
2298 return _wrapreduction(a, np.add, 'sum', axis, dtype, out, keepdims=keepdims,
2299 initial=initial, where=where)
2302def _any_dispatcher(a, axis=None, out=None, keepdims=None, *,
2303 where=np._NoValue):
2304 return (a, where, out)
2307@array_function_dispatch(_any_dispatcher)
2308def any(a, axis=None, out=None, keepdims=np._NoValue, *, where=np._NoValue):
2309 """
2310 Test whether any array element along a given axis evaluates to True.
2312 Returns single boolean if `axis` is ``None``
2314 Parameters
2315 ----------
2316 a : array_like
2317 Input array or object that can be converted to an array.
2318 axis : None or int or tuple of ints, optional
2319 Axis or axes along which a logical OR reduction is performed.
2320 The default (``axis=None``) is to perform a logical OR over all
2321 the dimensions of the input array. `axis` may be negative, in
2322 which case it counts from the last to the first axis.
2324 .. versionadded:: 1.7.0
2326 If this is a tuple of ints, a reduction is performed on multiple
2327 axes, instead of a single axis or all the axes as before.
2328 out : ndarray, optional
2329 Alternate output array in which to place the result. It must have
2330 the same shape as the expected output and its type is preserved
2331 (e.g., if it is of type float, then it will remain so, returning
2332 1.0 for True and 0.0 for False, regardless of the type of `a`).
2333 See :ref:`ufuncs-output-type` for more details.
2335 keepdims : bool, optional
2336 If this is set to True, the axes which are reduced are left
2337 in the result as dimensions with size one. With this option,
2338 the result will broadcast correctly against the input array.
2340 If the default value is passed, then `keepdims` will not be
2341 passed through to the `any` method of sub-classes of
2342 `ndarray`, however any non-default value will be. If the
2343 sub-class' method does not implement `keepdims` any
2344 exceptions will be raised.
2346 where : array_like of bool, optional
2347 Elements to include in checking for any `True` values.
2348 See `~numpy.ufunc.reduce` for details.
2350 .. versionadded:: 1.20.0
2352 Returns
2353 -------
2354 any : bool or ndarray
2355 A new boolean or `ndarray` is returned unless `out` is specified,
2356 in which case a reference to `out` is returned.
2358 See Also
2359 --------
2360 ndarray.any : equivalent method
2362 all : Test whether all elements along a given axis evaluate to True.
2364 Notes
2365 -----
2366 Not a Number (NaN), positive infinity and negative infinity evaluate
2367 to `True` because these are not equal to zero.
2369 Examples
2370 --------
2371 >>> np.any([[True, False], [True, True]])
2372 True
2374 >>> np.any([[True, False], [False, False]], axis=0)
2375 array([ True, False])
2377 >>> np.any([-1, 0, 5])
2378 True
2380 >>> np.any(np.nan)
2381 True
2383 >>> np.any([[True, False], [False, False]], where=[[False], [True]])
2384 False
2386 >>> o=np.array(False)
2387 >>> z=np.any([-1, 4, 5], out=o)
2388 >>> z, o
2389 (array(True), array(True))
2390 >>> # Check now that z is a reference to o
2391 >>> z is o
2392 True
2393 >>> id(z), id(o) # identity of z and o # doctest: +SKIP
2394 (191614240, 191614240)
2396 """
2397 return _wrapreduction(a, np.logical_or, 'any', axis, None, out,
2398 keepdims=keepdims, where=where)
2401def _all_dispatcher(a, axis=None, out=None, keepdims=None, *,
2402 where=None):
2403 return (a, where, out)
2406@array_function_dispatch(_all_dispatcher)
2407def all(a, axis=None, out=None, keepdims=np._NoValue, *, where=np._NoValue):
2408 """
2409 Test whether all array elements along a given axis evaluate to True.
2411 Parameters
2412 ----------
2413 a : array_like
2414 Input array or object that can be converted to an array.
2415 axis : None or int or tuple of ints, optional
2416 Axis or axes along which a logical AND reduction is performed.
2417 The default (``axis=None``) is to perform a logical AND over all
2418 the dimensions of the input array. `axis` may be negative, in
2419 which case it counts from the last to the first axis.
2421 .. versionadded:: 1.7.0
2423 If this is a tuple of ints, a reduction is performed on multiple
2424 axes, instead of a single axis or all the axes as before.
2425 out : ndarray, optional
2426 Alternate output array in which to place the result.
2427 It must have the same shape as the expected output and its
2428 type is preserved (e.g., if ``dtype(out)`` is float, the result
2429 will consist of 0.0's and 1.0's). See :ref:`ufuncs-output-type` for more
2430 details.
2432 keepdims : bool, optional
2433 If this is set to True, the axes which are reduced are left
2434 in the result as dimensions with size one. With this option,
2435 the result will broadcast correctly against the input array.
2437 If the default value is passed, then `keepdims` will not be
2438 passed through to the `all` method of sub-classes of
2439 `ndarray`, however any non-default value will be. If the
2440 sub-class' method does not implement `keepdims` any
2441 exceptions will be raised.
2443 where : array_like of bool, optional
2444 Elements to include in checking for all `True` values.
2445 See `~numpy.ufunc.reduce` for details.
2447 .. versionadded:: 1.20.0
2449 Returns
2450 -------
2451 all : ndarray, bool
2452 A new boolean or array is returned unless `out` is specified,
2453 in which case a reference to `out` is returned.
2455 See Also
2456 --------
2457 ndarray.all : equivalent method
2459 any : Test whether any element along a given axis evaluates to True.
2461 Notes
2462 -----
2463 Not a Number (NaN), positive infinity and negative infinity
2464 evaluate to `True` because these are not equal to zero.
2466 Examples
2467 --------
2468 >>> np.all([[True,False],[True,True]])
2469 False
2471 >>> np.all([[True,False],[True,True]], axis=0)
2472 array([ True, False])
2474 >>> np.all([-1, 4, 5])
2475 True
2477 >>> np.all([1.0, np.nan])
2478 True
2480 >>> np.all([[True, True], [False, True]], where=[[True], [False]])
2481 True
2483 >>> o=np.array(False)
2484 >>> z=np.all([-1, 4, 5], out=o)
2485 >>> id(z), id(o), z
2486 (28293632, 28293632, array(True)) # may vary
2488 """
2489 return _wrapreduction(a, np.logical_and, 'all', axis, None, out,
2490 keepdims=keepdims, where=where)
2493def _cumsum_dispatcher(a, axis=None, dtype=None, out=None):
2494 return (a, out)
2497@array_function_dispatch(_cumsum_dispatcher)
2498def cumsum(a, axis=None, dtype=None, out=None):
2499 """
2500 Return the cumulative sum of the elements along a given axis.
2502 Parameters
2503 ----------
2504 a : array_like
2505 Input array.
2506 axis : int, optional
2507 Axis along which the cumulative sum is computed. The default
2508 (None) is to compute the cumsum over the flattened array.
2509 dtype : dtype, optional
2510 Type of the returned array and of the accumulator in which the
2511 elements are summed. If `dtype` is not specified, it defaults
2512 to the dtype of `a`, unless `a` has an integer dtype with a
2513 precision less than that of the default platform integer. In
2514 that case, the default platform integer is used.
2515 out : ndarray, optional
2516 Alternative output array in which to place the result. It must
2517 have the same shape and buffer length as the expected output
2518 but the type will be cast if necessary. See :ref:`ufuncs-output-type` for
2519 more details.
2521 Returns
2522 -------
2523 cumsum_along_axis : ndarray.
2524 A new array holding the result is returned unless `out` is
2525 specified, in which case a reference to `out` is returned. The
2526 result has the same size as `a`, and the same shape as `a` if
2527 `axis` is not None or `a` is a 1-d array.
2529 See Also
2530 --------
2531 sum : Sum array elements.
2532 trapz : Integration of array values using the composite trapezoidal rule.
2533 diff : Calculate the n-th discrete difference along given axis.
2535 Notes
2536 -----
2537 Arithmetic is modular when using integer types, and no error is
2538 raised on overflow.
2540 ``cumsum(a)[-1]`` may not be equal to ``sum(a)`` for floating-point
2541 values since ``sum`` may use a pairwise summation routine, reducing
2542 the roundoff-error. See `sum` for more information.
2544 Examples
2545 --------
2546 >>> a = np.array([[1,2,3], [4,5,6]])
2547 >>> a
2548 array([[1, 2, 3],
2549 [4, 5, 6]])
2550 >>> np.cumsum(a)
2551 array([ 1, 3, 6, 10, 15, 21])
2552 >>> np.cumsum(a, dtype=float) # specifies type of output value(s)
2553 array([ 1., 3., 6., 10., 15., 21.])
2555 >>> np.cumsum(a,axis=0) # sum over rows for each of the 3 columns
2556 array([[1, 2, 3],
2557 [5, 7, 9]])
2558 >>> np.cumsum(a,axis=1) # sum over columns for each of the 2 rows
2559 array([[ 1, 3, 6],
2560 [ 4, 9, 15]])
2562 ``cumsum(b)[-1]`` may not be equal to ``sum(b)``
2564 >>> b = np.array([1, 2e-9, 3e-9] * 1000000)
2565 >>> b.cumsum()[-1]
2566 1000000.0050045159
2567 >>> b.sum()
2568 1000000.0050000029
2570 """
2571 return _wrapfunc(a, 'cumsum', axis=axis, dtype=dtype, out=out)
2574def _ptp_dispatcher(a, axis=None, out=None, keepdims=None):
2575 return (a, out)
2578@array_function_dispatch(_ptp_dispatcher)
2579def ptp(a, axis=None, out=None, keepdims=np._NoValue):
2580 """
2581 Range of values (maximum - minimum) along an axis.
2583 The name of the function comes from the acronym for 'peak to peak'.
2585 .. warning::
2586 `ptp` preserves the data type of the array. This means the
2587 return value for an input of signed integers with n bits
2588 (e.g. `np.int8`, `np.int16`, etc) is also a signed integer
2589 with n bits. In that case, peak-to-peak values greater than
2590 ``2**(n-1)-1`` will be returned as negative values. An example
2591 with a work-around is shown below.
2593 Parameters
2594 ----------
2595 a : array_like
2596 Input values.
2597 axis : None or int or tuple of ints, optional
2598 Axis along which to find the peaks. By default, flatten the
2599 array. `axis` may be negative, in
2600 which case it counts from the last to the first axis.
2602 .. versionadded:: 1.15.0
2604 If this is a tuple of ints, a reduction is performed on multiple
2605 axes, instead of a single axis or all the axes as before.
2606 out : array_like
2607 Alternative output array in which to place the result. It must
2608 have the same shape and buffer length as the expected output,
2609 but the type of the output values will be cast if necessary.
2611 keepdims : bool, optional
2612 If this is set to True, the axes which are reduced are left
2613 in the result as dimensions with size one. With this option,
2614 the result will broadcast correctly against the input array.
2616 If the default value is passed, then `keepdims` will not be
2617 passed through to the `ptp` method of sub-classes of
2618 `ndarray`, however any non-default value will be. If the
2619 sub-class' method does not implement `keepdims` any
2620 exceptions will be raised.
2622 Returns
2623 -------
2624 ptp : ndarray
2625 A new array holding the result, unless `out` was
2626 specified, in which case a reference to `out` is returned.
2628 Examples
2629 --------
2630 >>> x = np.array([[4, 9, 2, 10],
2631 ... [6, 9, 7, 12]])
2633 >>> np.ptp(x, axis=1)
2634 array([8, 6])
2636 >>> np.ptp(x, axis=0)
2637 array([2, 0, 5, 2])
2639 >>> np.ptp(x)
2640 10
2642 This example shows that a negative value can be returned when
2643 the input is an array of signed integers.
2645 >>> y = np.array([[1, 127],
2646 ... [0, 127],
2647 ... [-1, 127],
2648 ... [-2, 127]], dtype=np.int8)
2649 >>> np.ptp(y, axis=1)
2650 array([ 126, 127, -128, -127], dtype=int8)
2652 A work-around is to use the `view()` method to view the result as
2653 unsigned integers with the same bit width:
2655 >>> np.ptp(y, axis=1).view(np.uint8)
2656 array([126, 127, 128, 129], dtype=uint8)
2658 """
2659 kwargs = {}
2660 if keepdims is not np._NoValue:
2661 kwargs['keepdims'] = keepdims
2662 if type(a) is not mu.ndarray:
2663 try:
2664 ptp = a.ptp
2665 except AttributeError:
2666 pass
2667 else:
2668 return ptp(axis=axis, out=out, **kwargs)
2669 return _methods._ptp(a, axis=axis, out=out, **kwargs)
2672def _amax_dispatcher(a, axis=None, out=None, keepdims=None, initial=None,
2673 where=None):
2674 return (a, out)
2677@array_function_dispatch(_amax_dispatcher)
2678def amax(a, axis=None, out=None, keepdims=np._NoValue, initial=np._NoValue,
2679 where=np._NoValue):
2680 """
2681 Return the maximum of an array or maximum along an axis.
2683 Parameters
2684 ----------
2685 a : array_like
2686 Input data.
2687 axis : None or int or tuple of ints, optional
2688 Axis or axes along which to operate. By default, flattened input is
2689 used.
2691 .. versionadded:: 1.7.0
2693 If this is a tuple of ints, the maximum is selected over multiple axes,
2694 instead of a single axis or all the axes as before.
2695 out : ndarray, optional
2696 Alternative output array in which to place the result. Must
2697 be of the same shape and buffer length as the expected output.
2698 See :ref:`ufuncs-output-type` for more details.
2700 keepdims : bool, optional
2701 If this is set to True, the axes which are reduced are left
2702 in the result as dimensions with size one. With this option,
2703 the result will broadcast correctly against the input array.
2705 If the default value is passed, then `keepdims` will not be
2706 passed through to the `amax` method of sub-classes of
2707 `ndarray`, however any non-default value will be. If the
2708 sub-class' method does not implement `keepdims` any
2709 exceptions will be raised.
2711 initial : scalar, optional
2712 The minimum value of an output element. Must be present to allow
2713 computation on empty slice. See `~numpy.ufunc.reduce` for details.
2715 .. versionadded:: 1.15.0
2717 where : array_like of bool, optional
2718 Elements to compare for the maximum. See `~numpy.ufunc.reduce`
2719 for details.
2721 .. versionadded:: 1.17.0
2723 Returns
2724 -------
2725 amax : ndarray or scalar
2726 Maximum of `a`. If `axis` is None, the result is a scalar value.
2727 If `axis` is given, the result is an array of dimension
2728 ``a.ndim - 1``.
2730 See Also
2731 --------
2732 amin :
2733 The minimum value of an array along a given axis, propagating any NaNs.
2734 nanmax :
2735 The maximum value of an array along a given axis, ignoring any NaNs.
2736 maximum :
2737 Element-wise maximum of two arrays, propagating any NaNs.
2738 fmax :
2739 Element-wise maximum of two arrays, ignoring any NaNs.
2740 argmax :
2741 Return the indices of the maximum values.
2743 nanmin, minimum, fmin
2745 Notes
2746 -----
2747 NaN values are propagated, that is if at least one item is NaN, the
2748 corresponding max value will be NaN as well. To ignore NaN values
2749 (MATLAB behavior), please use nanmax.
2751 Don't use `amax` for element-wise comparison of 2 arrays; when
2752 ``a.shape[0]`` is 2, ``maximum(a[0], a[1])`` is faster than
2753 ``amax(a, axis=0)``.
2755 Examples
2756 --------
2757 >>> a = np.arange(4).reshape((2,2))
2758 >>> a
2759 array([[0, 1],
2760 [2, 3]])
2761 >>> np.amax(a) # Maximum of the flattened array
2762 3
2763 >>> np.amax(a, axis=0) # Maxima along the first axis
2764 array([2, 3])
2765 >>> np.amax(a, axis=1) # Maxima along the second axis
2766 array([1, 3])
2767 >>> np.amax(a, where=[False, True], initial=-1, axis=0)
2768 array([-1, 3])
2769 >>> b = np.arange(5, dtype=float)
2770 >>> b[2] = np.NaN
2771 >>> np.amax(b)
2772 nan
2773 >>> np.amax(b, where=~np.isnan(b), initial=-1)
2774 4.0
2775 >>> np.nanmax(b)
2776 4.0
2778 You can use an initial value to compute the maximum of an empty slice, or
2779 to initialize it to a different value:
2781 >>> np.amax([[-50], [10]], axis=-1, initial=0)
2782 array([ 0, 10])
2784 Notice that the initial value is used as one of the elements for which the
2785 maximum is determined, unlike for the default argument Python's max
2786 function, which is only used for empty iterables.
2788 >>> np.amax([5], initial=6)
2789 6
2790 >>> max([5], default=6)
2791 5
2792 """
2793 return _wrapreduction(a, np.maximum, 'max', axis, None, out,
2794 keepdims=keepdims, initial=initial, where=where)
2797def _amin_dispatcher(a, axis=None, out=None, keepdims=None, initial=None,
2798 where=None):
2799 return (a, out)
2802@array_function_dispatch(_amin_dispatcher)
2803def amin(a, axis=None, out=None, keepdims=np._NoValue, initial=np._NoValue,
2804 where=np._NoValue):
2805 """
2806 Return the minimum of an array or minimum along an axis.
2808 Parameters
2809 ----------
2810 a : array_like
2811 Input data.
2812 axis : None or int or tuple of ints, optional
2813 Axis or axes along which to operate. By default, flattened input is
2814 used.
2816 .. versionadded:: 1.7.0
2818 If this is a tuple of ints, the minimum is selected over multiple axes,
2819 instead of a single axis or all the axes as before.
2820 out : ndarray, optional
2821 Alternative output array in which to place the result. Must
2822 be of the same shape and buffer length as the expected output.
2823 See :ref:`ufuncs-output-type` for more details.
2825 keepdims : bool, optional
2826 If this is set to True, the axes which are reduced are left
2827 in the result as dimensions with size one. With this option,
2828 the result will broadcast correctly against the input array.
2830 If the default value is passed, then `keepdims` will not be
2831 passed through to the `amin` method of sub-classes of
2832 `ndarray`, however any non-default value will be. If the
2833 sub-class' method does not implement `keepdims` any
2834 exceptions will be raised.
2836 initial : scalar, optional
2837 The maximum value of an output element. Must be present to allow
2838 computation on empty slice. See `~numpy.ufunc.reduce` for details.
2840 .. versionadded:: 1.15.0
2842 where : array_like of bool, optional
2843 Elements to compare for the minimum. See `~numpy.ufunc.reduce`
2844 for details.
2846 .. versionadded:: 1.17.0
2848 Returns
2849 -------
2850 amin : ndarray or scalar
2851 Minimum of `a`. If `axis` is None, the result is a scalar value.
2852 If `axis` is given, the result is an array of dimension
2853 ``a.ndim - 1``.
2855 See Also
2856 --------
2857 amax :
2858 The maximum value of an array along a given axis, propagating any NaNs.
2859 nanmin :
2860 The minimum value of an array along a given axis, ignoring any NaNs.
2861 minimum :
2862 Element-wise minimum of two arrays, propagating any NaNs.
2863 fmin :
2864 Element-wise minimum of two arrays, ignoring any NaNs.
2865 argmin :
2866 Return the indices of the minimum values.
2868 nanmax, maximum, fmax
2870 Notes
2871 -----
2872 NaN values are propagated, that is if at least one item is NaN, the
2873 corresponding min value will be NaN as well. To ignore NaN values
2874 (MATLAB behavior), please use nanmin.
2876 Don't use `amin` for element-wise comparison of 2 arrays; when
2877 ``a.shape[0]`` is 2, ``minimum(a[0], a[1])`` is faster than
2878 ``amin(a, axis=0)``.
2880 Examples
2881 --------
2882 >>> a = np.arange(4).reshape((2,2))
2883 >>> a
2884 array([[0, 1],
2885 [2, 3]])
2886 >>> np.amin(a) # Minimum of the flattened array
2887 0
2888 >>> np.amin(a, axis=0) # Minima along the first axis
2889 array([0, 1])
2890 >>> np.amin(a, axis=1) # Minima along the second axis
2891 array([0, 2])
2892 >>> np.amin(a, where=[False, True], initial=10, axis=0)
2893 array([10, 1])
2895 >>> b = np.arange(5, dtype=float)
2896 >>> b[2] = np.NaN
2897 >>> np.amin(b)
2898 nan
2899 >>> np.amin(b, where=~np.isnan(b), initial=10)
2900 0.0
2901 >>> np.nanmin(b)
2902 0.0
2904 >>> np.amin([[-50], [10]], axis=-1, initial=0)
2905 array([-50, 0])
2907 Notice that the initial value is used as one of the elements for which the
2908 minimum is determined, unlike for the default argument Python's max
2909 function, which is only used for empty iterables.
2911 Notice that this isn't the same as Python's ``default`` argument.
2913 >>> np.amin([6], initial=5)
2914 5
2915 >>> min([6], default=5)
2916 6
2917 """
2918 return _wrapreduction(a, np.minimum, 'min', axis, None, out,
2919 keepdims=keepdims, initial=initial, where=where)
2922def _prod_dispatcher(a, axis=None, dtype=None, out=None, keepdims=None,
2923 initial=None, where=None):
2924 return (a, out)
2927@array_function_dispatch(_prod_dispatcher)
2928def prod(a, axis=None, dtype=None, out=None, keepdims=np._NoValue,
2929 initial=np._NoValue, where=np._NoValue):
2930 """
2931 Return the product of array elements over a given axis.
2933 Parameters
2934 ----------
2935 a : array_like
2936 Input data.
2937 axis : None or int or tuple of ints, optional
2938 Axis or axes along which a product is performed. The default,
2939 axis=None, will calculate the product of all the elements in the
2940 input array. If axis is negative it counts from the last to the
2941 first axis.
2943 .. versionadded:: 1.7.0
2945 If axis is a tuple of ints, a product is performed on all of the
2946 axes specified in the tuple instead of a single axis or all the
2947 axes as before.
2948 dtype : dtype, optional
2949 The type of the returned array, as well as of the accumulator in
2950 which the elements are multiplied. The dtype of `a` is used by
2951 default unless `a` has an integer dtype of less precision than the
2952 default platform integer. In that case, if `a` is signed then the
2953 platform integer is used while if `a` is unsigned then an unsigned
2954 integer of the same precision as the platform integer is used.
2955 out : ndarray, optional
2956 Alternative output array in which to place the result. It must have
2957 the same shape as the expected output, but the type of the output
2958 values will be cast if necessary.
2959 keepdims : bool, optional
2960 If this is set to True, the axes which are reduced are left in the
2961 result as dimensions with size one. With this option, the result
2962 will broadcast correctly against the input array.
2964 If the default value is passed, then `keepdims` will not be
2965 passed through to the `prod` method of sub-classes of
2966 `ndarray`, however any non-default value will be. If the
2967 sub-class' method does not implement `keepdims` any
2968 exceptions will be raised.
2969 initial : scalar, optional
2970 The starting value for this product. See `~numpy.ufunc.reduce` for details.
2972 .. versionadded:: 1.15.0
2974 where : array_like of bool, optional
2975 Elements to include in the product. See `~numpy.ufunc.reduce` for details.
2977 .. versionadded:: 1.17.0
2979 Returns
2980 -------
2981 product_along_axis : ndarray, see `dtype` parameter above.
2982 An array shaped as `a` but with the specified axis removed.
2983 Returns a reference to `out` if specified.
2985 See Also
2986 --------
2987 ndarray.prod : equivalent method
2988 :ref:`ufuncs-output-type`
2990 Notes
2991 -----
2992 Arithmetic is modular when using integer types, and no error is
2993 raised on overflow. That means that, on a 32-bit platform:
2995 >>> x = np.array([536870910, 536870910, 536870910, 536870910])
2996 >>> np.prod(x)
2997 16 # may vary
2999 The product of an empty array is the neutral element 1:
3001 >>> np.prod([])
3002 1.0
3004 Examples
3005 --------
3006 By default, calculate the product of all elements:
3008 >>> np.prod([1.,2.])
3009 2.0
3011 Even when the input array is two-dimensional:
3013 >>> np.prod([[1.,2.],[3.,4.]])
3014 24.0
3016 But we can also specify the axis over which to multiply:
3018 >>> np.prod([[1.,2.],[3.,4.]], axis=1)
3019 array([ 2., 12.])
3021 Or select specific elements to include:
3023 >>> np.prod([1., np.nan, 3.], where=[True, False, True])
3024 3.0
3026 If the type of `x` is unsigned, then the output type is
3027 the unsigned platform integer:
3029 >>> x = np.array([1, 2, 3], dtype=np.uint8)
3030 >>> np.prod(x).dtype == np.uint
3031 True
3033 If `x` is of a signed integer type, then the output type
3034 is the default platform integer:
3036 >>> x = np.array([1, 2, 3], dtype=np.int8)
3037 >>> np.prod(x).dtype == int
3038 True
3040 You can also start the product with a value other than one:
3042 >>> np.prod([1, 2], initial=5)
3043 10
3044 """
3045 return _wrapreduction(a, np.multiply, 'prod', axis, dtype, out,
3046 keepdims=keepdims, initial=initial, where=where)
3049def _cumprod_dispatcher(a, axis=None, dtype=None, out=None):
3050 return (a, out)
3053@array_function_dispatch(_cumprod_dispatcher)
3054def cumprod(a, axis=None, dtype=None, out=None):
3055 """
3056 Return the cumulative product of elements along a given axis.
3058 Parameters
3059 ----------
3060 a : array_like
3061 Input array.
3062 axis : int, optional
3063 Axis along which the cumulative product is computed. By default
3064 the input is flattened.
3065 dtype : dtype, optional
3066 Type of the returned array, as well as of the accumulator in which
3067 the elements are multiplied. If *dtype* is not specified, it
3068 defaults to the dtype of `a`, unless `a` has an integer dtype with
3069 a precision less than that of the default platform integer. In
3070 that case, the default platform integer is used instead.
3071 out : ndarray, optional
3072 Alternative output array in which to place the result. It must
3073 have the same shape and buffer length as the expected output
3074 but the type of the resulting values will be cast if necessary.
3076 Returns
3077 -------
3078 cumprod : ndarray
3079 A new array holding the result is returned unless `out` is
3080 specified, in which case a reference to out is returned.
3082 See Also
3083 --------
3084 :ref:`ufuncs-output-type`
3086 Notes
3087 -----
3088 Arithmetic is modular when using integer types, and no error is
3089 raised on overflow.
3091 Examples
3092 --------
3093 >>> a = np.array([1,2,3])
3094 >>> np.cumprod(a) # intermediate results 1, 1*2
3095 ... # total product 1*2*3 = 6
3096 array([1, 2, 6])
3097 >>> a = np.array([[1, 2, 3], [4, 5, 6]])
3098 >>> np.cumprod(a, dtype=float) # specify type of output
3099 array([ 1., 2., 6., 24., 120., 720.])
3101 The cumulative product for each column (i.e., over the rows) of `a`:
3103 >>> np.cumprod(a, axis=0)
3104 array([[ 1, 2, 3],
3105 [ 4, 10, 18]])
3107 The cumulative product for each row (i.e. over the columns) of `a`:
3109 >>> np.cumprod(a,axis=1)
3110 array([[ 1, 2, 6],
3111 [ 4, 20, 120]])
3113 """
3114 return _wrapfunc(a, 'cumprod', axis=axis, dtype=dtype, out=out)
3117def _ndim_dispatcher(a):
3118 return (a,)
3121@array_function_dispatch(_ndim_dispatcher)
3122def ndim(a):
3123 """
3124 Return the number of dimensions of an array.
3126 Parameters
3127 ----------
3128 a : array_like
3129 Input array. If it is not already an ndarray, a conversion is
3130 attempted.
3132 Returns
3133 -------
3134 number_of_dimensions : int
3135 The number of dimensions in `a`. Scalars are zero-dimensional.
3137 See Also
3138 --------
3139 ndarray.ndim : equivalent method
3140 shape : dimensions of array
3141 ndarray.shape : dimensions of array
3143 Examples
3144 --------
3145 >>> np.ndim([[1,2,3],[4,5,6]])
3146 2
3147 >>> np.ndim(np.array([[1,2,3],[4,5,6]]))
3148 2
3149 >>> np.ndim(1)
3150 0
3152 """
3153 try:
3154 return a.ndim
3155 except AttributeError:
3156 return asarray(a).ndim
3159def _size_dispatcher(a, axis=None):
3160 return (a,)
3163@array_function_dispatch(_size_dispatcher)
3164def size(a, axis=None):
3165 """
3166 Return the number of elements along a given axis.
3168 Parameters
3169 ----------
3170 a : array_like
3171 Input data.
3172 axis : int, optional
3173 Axis along which the elements are counted. By default, give
3174 the total number of elements.
3176 Returns
3177 -------
3178 element_count : int
3179 Number of elements along the specified axis.
3181 See Also
3182 --------
3183 shape : dimensions of array
3184 ndarray.shape : dimensions of array
3185 ndarray.size : number of elements in array
3187 Examples
3188 --------
3189 >>> a = np.array([[1,2,3],[4,5,6]])
3190 >>> np.size(a)
3191 6
3192 >>> np.size(a,1)
3193 3
3194 >>> np.size(a,0)
3195 2
3197 """
3198 if axis is None:
3199 try:
3200 return a.size
3201 except AttributeError:
3202 return asarray(a).size
3203 else:
3204 try:
3205 return a.shape[axis]
3206 except AttributeError:
3207 return asarray(a).shape[axis]
3210def _around_dispatcher(a, decimals=None, out=None):
3211 return (a, out)
3214@array_function_dispatch(_around_dispatcher)
3215def around(a, decimals=0, out=None):
3216 """
3217 Evenly round to the given number of decimals.
3219 Parameters
3220 ----------
3221 a : array_like
3222 Input data.
3223 decimals : int, optional
3224 Number of decimal places to round to (default: 0). If
3225 decimals is negative, it specifies the number of positions to
3226 the left of the decimal point.
3227 out : ndarray, optional
3228 Alternative output array in which to place the result. It must have
3229 the same shape as the expected output, but the type of the output
3230 values will be cast if necessary. See :ref:`ufuncs-output-type` for more
3231 details.
3233 Returns
3234 -------
3235 rounded_array : ndarray
3236 An array of the same type as `a`, containing the rounded values.
3237 Unless `out` was specified, a new array is created. A reference to
3238 the result is returned.
3240 The real and imaginary parts of complex numbers are rounded
3241 separately. The result of rounding a float is a float.
3243 See Also
3244 --------
3245 ndarray.round : equivalent method
3247 ceil, fix, floor, rint, trunc
3250 Notes
3251 -----
3252 For values exactly halfway between rounded decimal values, NumPy
3253 rounds to the nearest even value. Thus 1.5 and 2.5 round to 2.0,
3254 -0.5 and 0.5 round to 0.0, etc.
3256 ``np.around`` uses a fast but sometimes inexact algorithm to round
3257 floating-point datatypes. For positive `decimals` it is equivalent to
3258 ``np.true_divide(np.rint(a * 10**decimals), 10**decimals)``, which has
3259 error due to the inexact representation of decimal fractions in the IEEE
3260 floating point standard [1]_ and errors introduced when scaling by powers
3261 of ten. For instance, note the extra "1" in the following:
3263 >>> np.round(56294995342131.5, 3)
3264 56294995342131.51
3266 If your goal is to print such values with a fixed number of decimals, it is
3267 preferable to use numpy's float printing routines to limit the number of
3268 printed decimals:
3270 >>> np.format_float_positional(56294995342131.5, precision=3)
3271 '56294995342131.5'
3273 The float printing routines use an accurate but much more computationally
3274 demanding algorithm to compute the number of digits after the decimal
3275 point.
3277 Alternatively, Python's builtin `round` function uses a more accurate
3278 but slower algorithm for 64-bit floating point values:
3280 >>> round(56294995342131.5, 3)
3281 56294995342131.5
3282 >>> np.round(16.055, 2), round(16.055, 2) # equals 16.0549999999999997
3283 (16.06, 16.05)
3286 References
3287 ----------
3288 .. [1] "Lecture Notes on the Status of IEEE 754", William Kahan,
3289 https://people.eecs.berkeley.edu/~wkahan/ieee754status/IEEE754.PDF
3291 Examples
3292 --------
3293 >>> np.around([0.37, 1.64])
3294 array([0., 2.])
3295 >>> np.around([0.37, 1.64], decimals=1)
3296 array([0.4, 1.6])
3297 >>> np.around([.5, 1.5, 2.5, 3.5, 4.5]) # rounds to nearest even value
3298 array([0., 2., 2., 4., 4.])
3299 >>> np.around([1,2,3,11], decimals=1) # ndarray of ints is returned
3300 array([ 1, 2, 3, 11])
3301 >>> np.around([1,2,3,11], decimals=-1)
3302 array([ 0, 0, 0, 10])
3304 """
3305 return _wrapfunc(a, 'round', decimals=decimals, out=out)
3308def _mean_dispatcher(a, axis=None, dtype=None, out=None, keepdims=None, *,
3309 where=None):
3310 return (a, where, out)
3313@array_function_dispatch(_mean_dispatcher)
3314def mean(a, axis=None, dtype=None, out=None, keepdims=np._NoValue, *,
3315 where=np._NoValue):
3316 """
3317 Compute the arithmetic mean along the specified axis.
3319 Returns the average of the array elements. The average is taken over
3320 the flattened array by default, otherwise over the specified axis.
3321 `float64` intermediate and return values are used for integer inputs.
3323 Parameters
3324 ----------
3325 a : array_like
3326 Array containing numbers whose mean is desired. If `a` is not an
3327 array, a conversion is attempted.
3328 axis : None or int or tuple of ints, optional
3329 Axis or axes along which the means are computed. The default is to
3330 compute the mean of the flattened array.
3332 .. versionadded:: 1.7.0
3334 If this is a tuple of ints, a mean is performed over multiple axes,
3335 instead of a single axis or all the axes as before.
3336 dtype : data-type, optional
3337 Type to use in computing the mean. For integer inputs, the default
3338 is `float64`; for floating point inputs, it is the same as the
3339 input dtype.
3340 out : ndarray, optional
3341 Alternate output array in which to place the result. The default
3342 is ``None``; if provided, it must have the same shape as the
3343 expected output, but the type will be cast if necessary.
3344 See :ref:`ufuncs-output-type` for more details.
3346 keepdims : bool, optional
3347 If this is set to True, the axes which are reduced are left
3348 in the result as dimensions with size one. With this option,
3349 the result will broadcast correctly against the input array.
3351 If the default value is passed, then `keepdims` will not be
3352 passed through to the `mean` method of sub-classes of
3353 `ndarray`, however any non-default value will be. If the
3354 sub-class' method does not implement `keepdims` any
3355 exceptions will be raised.
3357 where : array_like of bool, optional
3358 Elements to include in the mean. See `~numpy.ufunc.reduce` for details.
3360 .. versionadded:: 1.20.0
3362 Returns
3363 -------
3364 m : ndarray, see dtype parameter above
3365 If `out=None`, returns a new array containing the mean values,
3366 otherwise a reference to the output array is returned.
3368 See Also
3369 --------
3370 average : Weighted average
3371 std, var, nanmean, nanstd, nanvar
3373 Notes
3374 -----
3375 The arithmetic mean is the sum of the elements along the axis divided
3376 by the number of elements.
3378 Note that for floating-point input, the mean is computed using the
3379 same precision the input has. Depending on the input data, this can
3380 cause the results to be inaccurate, especially for `float32` (see
3381 example below). Specifying a higher-precision accumulator using the
3382 `dtype` keyword can alleviate this issue.
3384 By default, `float16` results are computed using `float32` intermediates
3385 for extra precision.
3387 Examples
3388 --------
3389 >>> a = np.array([[1, 2], [3, 4]])
3390 >>> np.mean(a)
3391 2.5
3392 >>> np.mean(a, axis=0)
3393 array([2., 3.])
3394 >>> np.mean(a, axis=1)
3395 array([1.5, 3.5])
3397 In single precision, `mean` can be inaccurate:
3399 >>> a = np.zeros((2, 512*512), dtype=np.float32)
3400 >>> a[0, :] = 1.0
3401 >>> a[1, :] = 0.1
3402 >>> np.mean(a)
3403 0.54999924
3405 Computing the mean in float64 is more accurate:
3407 >>> np.mean(a, dtype=np.float64)
3408 0.55000000074505806 # may vary
3410 Specifying a where argument:
3412 >>> a = np.array([[5, 9, 13], [14, 10, 12], [11, 15, 19]])
3413 >>> np.mean(a)
3414 12.0
3415 >>> np.mean(a, where=[[True], [False], [False]])
3416 9.0
3418 """
3419 kwargs = {}
3420 if keepdims is not np._NoValue:
3421 kwargs['keepdims'] = keepdims
3422 if where is not np._NoValue:
3423 kwargs['where'] = where
3424 if type(a) is not mu.ndarray:
3425 try:
3426 mean = a.mean
3427 except AttributeError:
3428 pass
3429 else:
3430 return mean(axis=axis, dtype=dtype, out=out, **kwargs)
3432 return _methods._mean(a, axis=axis, dtype=dtype,
3433 out=out, **kwargs)
3436def _std_dispatcher(a, axis=None, dtype=None, out=None, ddof=None,
3437 keepdims=None, *, where=None):
3438 return (a, where, out)
3441@array_function_dispatch(_std_dispatcher)
3442def std(a, axis=None, dtype=None, out=None, ddof=0, keepdims=np._NoValue, *,
3443 where=np._NoValue):
3444 """
3445 Compute the standard deviation along the specified axis.
3447 Returns the standard deviation, a measure of the spread of a distribution,
3448 of the array elements. The standard deviation is computed for the
3449 flattened array by default, otherwise over the specified axis.
3451 Parameters
3452 ----------
3453 a : array_like
3454 Calculate the standard deviation of these values.
3455 axis : None or int or tuple of ints, optional
3456 Axis or axes along which the standard deviation is computed. The
3457 default is to compute the standard deviation of the flattened array.
3459 .. versionadded:: 1.7.0
3461 If this is a tuple of ints, a standard deviation is performed over
3462 multiple axes, instead of a single axis or all the axes as before.
3463 dtype : dtype, optional
3464 Type to use in computing the standard deviation. For arrays of
3465 integer type the default is float64, for arrays of float types it is
3466 the same as the array type.
3467 out : ndarray, optional
3468 Alternative output array in which to place the result. It must have
3469 the same shape as the expected output but the type (of the calculated
3470 values) will be cast if necessary.
3471 ddof : int, optional
3472 Means Delta Degrees of Freedom. The divisor used in calculations
3473 is ``N - ddof``, where ``N`` represents the number of elements.
3474 By default `ddof` is zero.
3475 keepdims : bool, optional
3476 If this is set to True, the axes which are reduced are left
3477 in the result as dimensions with size one. With this option,
3478 the result will broadcast correctly against the input array.
3480 If the default value is passed, then `keepdims` will not be
3481 passed through to the `std` method of sub-classes of
3482 `ndarray`, however any non-default value will be. If the
3483 sub-class' method does not implement `keepdims` any
3484 exceptions will be raised.
3486 where : array_like of bool, optional
3487 Elements to include in the standard deviation.
3488 See `~numpy.ufunc.reduce` for details.
3490 .. versionadded:: 1.20.0
3492 Returns
3493 -------
3494 standard_deviation : ndarray, see dtype parameter above.
3495 If `out` is None, return a new array containing the standard deviation,
3496 otherwise return a reference to the output array.
3498 See Also
3499 --------
3500 var, mean, nanmean, nanstd, nanvar
3501 :ref:`ufuncs-output-type`
3503 Notes
3504 -----
3505 The standard deviation is the square root of the average of the squared
3506 deviations from the mean, i.e., ``std = sqrt(mean(x))``, where
3507 ``x = abs(a - a.mean())**2``.
3509 The average squared deviation is typically calculated as ``x.sum() / N``,
3510 where ``N = len(x)``. If, however, `ddof` is specified, the divisor
3511 ``N - ddof`` is used instead. In standard statistical practice, ``ddof=1``
3512 provides an unbiased estimator of the variance of the infinite population.
3513 ``ddof=0`` provides a maximum likelihood estimate of the variance for
3514 normally distributed variables. The standard deviation computed in this
3515 function is the square root of the estimated variance, so even with
3516 ``ddof=1``, it will not be an unbiased estimate of the standard deviation
3517 per se.
3519 Note that, for complex numbers, `std` takes the absolute
3520 value before squaring, so that the result is always real and nonnegative.
3522 For floating-point input, the *std* is computed using the same
3523 precision the input has. Depending on the input data, this can cause
3524 the results to be inaccurate, especially for float32 (see example below).
3525 Specifying a higher-accuracy accumulator using the `dtype` keyword can
3526 alleviate this issue.
3528 Examples
3529 --------
3530 >>> a = np.array([[1, 2], [3, 4]])
3531 >>> np.std(a)
3532 1.1180339887498949 # may vary
3533 >>> np.std(a, axis=0)
3534 array([1., 1.])
3535 >>> np.std(a, axis=1)
3536 array([0.5, 0.5])
3538 In single precision, std() can be inaccurate:
3540 >>> a = np.zeros((2, 512*512), dtype=np.float32)
3541 >>> a[0, :] = 1.0
3542 >>> a[1, :] = 0.1
3543 >>> np.std(a)
3544 0.45000005
3546 Computing the standard deviation in float64 is more accurate:
3548 >>> np.std(a, dtype=np.float64)
3549 0.44999999925494177 # may vary
3551 Specifying a where argument:
3553 >>> a = np.array([[14, 8, 11, 10], [7, 9, 10, 11], [10, 15, 5, 10]])
3554 >>> np.std(a)
3555 2.614064523559687 # may vary
3556 >>> np.std(a, where=[[True], [True], [False]])
3557 2.0
3559 """
3560 kwargs = {}
3561 if keepdims is not np._NoValue:
3562 kwargs['keepdims'] = keepdims
3563 if where is not np._NoValue:
3564 kwargs['where'] = where
3565 if type(a) is not mu.ndarray:
3566 try:
3567 std = a.std
3568 except AttributeError:
3569 pass
3570 else:
3571 return std(axis=axis, dtype=dtype, out=out, ddof=ddof, **kwargs)
3573 return _methods._std(a, axis=axis, dtype=dtype, out=out, ddof=ddof,
3574 **kwargs)
3577def _var_dispatcher(a, axis=None, dtype=None, out=None, ddof=None,
3578 keepdims=None, *, where=None):
3579 return (a, where, out)
3582@array_function_dispatch(_var_dispatcher)
3583def var(a, axis=None, dtype=None, out=None, ddof=0, keepdims=np._NoValue, *,
3584 where=np._NoValue):
3585 """
3586 Compute the variance along the specified axis.
3588 Returns the variance of the array elements, a measure of the spread of a
3589 distribution. The variance is computed for the flattened array by
3590 default, otherwise over the specified axis.
3592 Parameters
3593 ----------
3594 a : array_like
3595 Array containing numbers whose variance is desired. If `a` is not an
3596 array, a conversion is attempted.
3597 axis : None or int or tuple of ints, optional
3598 Axis or axes along which the variance is computed. The default is to
3599 compute the variance of the flattened array.
3601 .. versionadded:: 1.7.0
3603 If this is a tuple of ints, a variance is performed over multiple axes,
3604 instead of a single axis or all the axes as before.
3605 dtype : data-type, optional
3606 Type to use in computing the variance. For arrays of integer type
3607 the default is `float64`; for arrays of float types it is the same as
3608 the array type.
3609 out : ndarray, optional
3610 Alternate output array in which to place the result. It must have
3611 the same shape as the expected output, but the type is cast if
3612 necessary.
3613 ddof : int, optional
3614 "Delta Degrees of Freedom": the divisor used in the calculation is
3615 ``N - ddof``, where ``N`` represents the number of elements. By
3616 default `ddof` is zero.
3617 keepdims : bool, optional
3618 If this is set to True, the axes which are reduced are left
3619 in the result as dimensions with size one. With this option,
3620 the result will broadcast correctly against the input array.
3622 If the default value is passed, then `keepdims` will not be
3623 passed through to the `var` method of sub-classes of
3624 `ndarray`, however any non-default value will be. If the
3625 sub-class' method does not implement `keepdims` any
3626 exceptions will be raised.
3628 where : array_like of bool, optional
3629 Elements to include in the variance. See `~numpy.ufunc.reduce` for
3630 details.
3632 .. versionadded:: 1.20.0
3634 Returns
3635 -------
3636 variance : ndarray, see dtype parameter above
3637 If ``out=None``, returns a new array containing the variance;
3638 otherwise, a reference to the output array is returned.
3640 See Also
3641 --------
3642 std, mean, nanmean, nanstd, nanvar
3643 :ref:`ufuncs-output-type`
3645 Notes
3646 -----
3647 The variance is the average of the squared deviations from the mean,
3648 i.e., ``var = mean(x)``, where ``x = abs(a - a.mean())**2``.
3650 The mean is typically calculated as ``x.sum() / N``, where ``N = len(x)``.
3651 If, however, `ddof` is specified, the divisor ``N - ddof`` is used
3652 instead. In standard statistical practice, ``ddof=1`` provides an
3653 unbiased estimator of the variance of a hypothetical infinite population.
3654 ``ddof=0`` provides a maximum likelihood estimate of the variance for
3655 normally distributed variables.
3657 Note that for complex numbers, the absolute value is taken before
3658 squaring, so that the result is always real and nonnegative.
3660 For floating-point input, the variance is computed using the same
3661 precision the input has. Depending on the input data, this can cause
3662 the results to be inaccurate, especially for `float32` (see example
3663 below). Specifying a higher-accuracy accumulator using the ``dtype``
3664 keyword can alleviate this issue.
3666 Examples
3667 --------
3668 >>> a = np.array([[1, 2], [3, 4]])
3669 >>> np.var(a)
3670 1.25
3671 >>> np.var(a, axis=0)
3672 array([1., 1.])
3673 >>> np.var(a, axis=1)
3674 array([0.25, 0.25])
3676 In single precision, var() can be inaccurate:
3678 >>> a = np.zeros((2, 512*512), dtype=np.float32)
3679 >>> a[0, :] = 1.0
3680 >>> a[1, :] = 0.1
3681 >>> np.var(a)
3682 0.20250003
3684 Computing the variance in float64 is more accurate:
3686 >>> np.var(a, dtype=np.float64)
3687 0.20249999932944759 # may vary
3688 >>> ((1-0.55)**2 + (0.1-0.55)**2)/2
3689 0.2025
3691 Specifying a where argument:
3693 >>> a = np.array([[14, 8, 11, 10], [7, 9, 10, 11], [10, 15, 5, 10]])
3694 >>> np.var(a)
3695 6.833333333333333 # may vary
3696 >>> np.var(a, where=[[True], [True], [False]])
3697 4.0
3699 """
3700 kwargs = {}
3701 if keepdims is not np._NoValue:
3702 kwargs['keepdims'] = keepdims
3703 if where is not np._NoValue:
3704 kwargs['where'] = where
3706 if type(a) is not mu.ndarray:
3707 try:
3708 var = a.var
3710 except AttributeError:
3711 pass
3712 else:
3713 return var(axis=axis, dtype=dtype, out=out, ddof=ddof, **kwargs)
3715 return _methods._var(a, axis=axis, dtype=dtype, out=out, ddof=ddof,
3716 **kwargs)
3719# Aliases of other functions. These have their own definitions only so that
3720# they can have unique docstrings.
3722@array_function_dispatch(_around_dispatcher)
3723def round_(a, decimals=0, out=None):
3724 """
3725 Round an array to the given number of decimals.
3727 See Also
3728 --------
3729 around : equivalent function; see for details.
3730 """
3731 return around(a, decimals=decimals, out=out)
3734@array_function_dispatch(_prod_dispatcher, verify=False)
3735def product(*args, **kwargs):
3736 """
3737 Return the product of array elements over a given axis.
3739 See Also
3740 --------
3741 prod : equivalent function; see for details.
3742 """
3743 return prod(*args, **kwargs)
3746@array_function_dispatch(_cumprod_dispatcher, verify=False)
3747def cumproduct(*args, **kwargs):
3748 """
3749 Return the cumulative product over the given axis.
3751 See Also
3752 --------
3753 cumprod : equivalent function; see for details.
3754 """
3755 return cumprod(*args, **kwargs)
3758@array_function_dispatch(_any_dispatcher, verify=False)
3759def sometrue(*args, **kwargs):
3760 """
3761 Check whether some values are true.
3763 Refer to `any` for full documentation.
3765 See Also
3766 --------
3767 any : equivalent function; see for details.
3768 """
3769 return any(*args, **kwargs)
3772@array_function_dispatch(_all_dispatcher, verify=False)
3773def alltrue(*args, **kwargs):
3774 """
3775 Check if all elements of input array are true.
3777 See Also
3778 --------
3779 numpy.all : Equivalent function; see for details.
3780 """
3781 return all(*args, **kwargs)