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