Coverage for /home/martinb/.local/share/virtualenvs/camcops/lib/python3.6/site-packages/numpy/core/fromnumeric.py : 47%

Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1"""Module containing non-deprecated functions borrowed from Numeric.
3"""
4import functools
5import types
6import warnings
8import numpy as np
9from . import multiarray as mu
10from . import overrides
11from . import umath as um
12from . import numerictypes as nt
13from ._asarray import asarray, array, asanyarray
14from .multiarray import concatenate
15from . import _methods
17_dt_ = nt.sctype2char
19# functions that are methods
20__all__ = [
21 'alen', 'all', 'alltrue', 'amax', 'amin', 'any', 'argmax',
22 'argmin', 'argpartition', 'argsort', 'around', 'choose', 'clip',
23 'compress', 'cumprod', 'cumproduct', 'cumsum', 'diagonal', 'mean',
24 'ndim', 'nonzero', 'partition', 'prod', 'product', 'ptp', 'put',
25 'ravel', 'repeat', 'reshape', 'resize', 'round_',
26 'searchsorted', 'shape', 'size', 'sometrue', 'sort', 'squeeze',
27 'std', 'sum', 'swapaxes', 'take', 'trace', 'transpose', 'var',
28]
30_gentype = types.GeneratorType
31# save away Python sum
32_sum_ = sum
34array_function_dispatch = functools.partial(
35 overrides.array_function_dispatch, module='numpy')
38# functions that are now methods
39def _wrapit(obj, method, *args, **kwds):
40 try:
41 wrap = obj.__array_wrap__
42 except AttributeError:
43 wrap = None
44 result = getattr(asarray(obj), method)(*args, **kwds)
45 if wrap:
46 if not isinstance(result, mu.ndarray):
47 result = asarray(result)
48 result = wrap(result)
49 return result
52def _wrapfunc(obj, method, *args, **kwds):
53 bound = getattr(obj, method, None)
54 if bound is None:
55 return _wrapit(obj, method, *args, **kwds)
57 try:
58 return bound(*args, **kwds)
59 except TypeError:
60 # A TypeError occurs if the object does have such a method in its
61 # class, but its signature is not identical to that of NumPy's. This
62 # situation has occurred in the case of a downstream library like
63 # 'pandas'.
64 #
65 # Call _wrapit from within the except clause to ensure a potential
66 # exception has a traceback chain.
67 return _wrapit(obj, method, *args, **kwds)
70def _wrapreduction(obj, ufunc, method, axis, dtype, out, **kwargs):
71 passkwargs = {k: v for k, v in kwargs.items()
72 if v is not np._NoValue}
74 if type(obj) is not mu.ndarray:
75 try:
76 reduction = getattr(obj, method)
77 except AttributeError:
78 pass
79 else:
80 # This branch is needed for reductions like any which don't
81 # support a dtype.
82 if dtype is not None:
83 return reduction(axis=axis, dtype=dtype, out=out, **passkwargs)
84 else:
85 return reduction(axis=axis, out=out, **passkwargs)
87 return ufunc.reduce(obj, axis, dtype, out, **passkwargs)
90def _take_dispatcher(a, indices, axis=None, out=None, mode=None):
91 return (a, out)
94@array_function_dispatch(_take_dispatcher)
95def take(a, indices, axis=None, out=None, mode='raise'):
96 """
97 Take elements from an array along an axis.
99 When axis is not None, this function does the same thing as "fancy"
100 indexing (indexing arrays using arrays); however, it can be easier to use
101 if you need elements along a given axis. A call such as
102 ``np.take(arr, indices, axis=3)`` is equivalent to
103 ``arr[:,:,:,indices,...]``.
105 Explained without fancy indexing, this is equivalent to the following use
106 of `ndindex`, which sets each of ``ii``, ``jj``, and ``kk`` to a tuple of
107 indices::
109 Ni, Nk = a.shape[:axis], a.shape[axis+1:]
110 Nj = indices.shape
111 for ii in ndindex(Ni):
112 for jj in ndindex(Nj):
113 for kk in ndindex(Nk):
114 out[ii + jj + kk] = a[ii + (indices[jj],) + kk]
116 Parameters
117 ----------
118 a : array_like (Ni..., M, Nk...)
119 The source array.
120 indices : array_like (Nj...)
121 The indices of the values to extract.
123 .. versionadded:: 1.8.0
125 Also allow scalars for indices.
126 axis : int, optional
127 The axis over which to select values. By default, the flattened
128 input array is used.
129 out : ndarray, optional (Ni..., Nj..., Nk...)
130 If provided, the result will be placed in this array. It should
131 be of the appropriate shape and dtype. Note that `out` is always
132 buffered if `mode='raise'`; use other modes for better performance.
133 mode : {'raise', 'wrap', 'clip'}, optional
134 Specifies how out-of-bounds indices will behave.
136 * 'raise' -- raise an error (default)
137 * 'wrap' -- wrap around
138 * 'clip' -- clip to the range
140 'clip' mode means that all indices that are too large are replaced
141 by the index that addresses the last element along that axis. Note
142 that this disables indexing with negative numbers.
144 Returns
145 -------
146 out : ndarray (Ni..., Nj..., Nk...)
147 The returned array has the same type as `a`.
149 See Also
150 --------
151 compress : Take elements using a boolean mask
152 ndarray.take : equivalent method
153 take_along_axis : Take elements by matching the array and the index arrays
155 Notes
156 -----
158 By eliminating the inner loop in the description above, and using `s_` to
159 build simple slice objects, `take` can be expressed in terms of applying
160 fancy indexing to each 1-d slice::
162 Ni, Nk = a.shape[:axis], a.shape[axis+1:]
163 for ii in ndindex(Ni):
164 for kk in ndindex(Nj):
165 out[ii + s_[...,] + kk] = a[ii + s_[:,] + kk][indices]
167 For this reason, it is equivalent to (but faster than) the following use
168 of `apply_along_axis`::
170 out = np.apply_along_axis(lambda a_1d: a_1d[indices], axis, a)
172 Examples
173 --------
174 >>> a = [4, 3, 5, 7, 6, 8]
175 >>> indices = [0, 1, 4]
176 >>> np.take(a, indices)
177 array([4, 3, 6])
179 In this example if `a` is an ndarray, "fancy" indexing can be used.
181 >>> a = np.array(a)
182 >>> a[indices]
183 array([4, 3, 6])
185 If `indices` is not one dimensional, the output also has these dimensions.
187 >>> np.take(a, [[0, 1], [2, 3]])
188 array([[4, 3],
189 [5, 7]])
190 """
191 return _wrapfunc(a, 'take', indices, axis=axis, out=out, mode=mode)
194def _reshape_dispatcher(a, newshape, order=None):
195 return (a,)
198# not deprecated --- copy if necessary, view otherwise
199@array_function_dispatch(_reshape_dispatcher)
200def reshape(a, newshape, order='C'):
201 """
202 Gives a new shape to an array without changing its data.
204 Parameters
205 ----------
206 a : array_like
207 Array to be reshaped.
208 newshape : int or tuple of ints
209 The new shape should be compatible with the original shape. If
210 an integer, then the result will be a 1-D array of that length.
211 One shape dimension can be -1. In this case, the value is
212 inferred from the length of the array and remaining dimensions.
213 order : {'C', 'F', 'A'}, optional
214 Read the elements of `a` using this index order, and place the
215 elements into the reshaped array using this index order. 'C'
216 means to read / write the elements using C-like index order,
217 with the last axis index changing fastest, back to the first
218 axis index changing slowest. 'F' means to read / write the
219 elements using Fortran-like index order, with the first index
220 changing fastest, and the last index changing slowest. Note that
221 the 'C' and 'F' options take no account of the memory layout of
222 the underlying array, and only refer to the order of indexing.
223 'A' means to read / write the elements in Fortran-like index
224 order if `a` is Fortran *contiguous* in memory, C-like order
225 otherwise.
227 Returns
228 -------
229 reshaped_array : ndarray
230 This will be a new view object if possible; otherwise, it will
231 be a copy. Note there is no guarantee of the *memory layout* (C- or
232 Fortran- contiguous) of the returned array.
234 See Also
235 --------
236 ndarray.reshape : Equivalent method.
238 Notes
239 -----
240 It is not always possible to change the shape of an array without
241 copying the data. If you want an error to be raised when the data is copied,
242 you should assign the new shape to the shape attribute of the array::
244 >>> a = np.zeros((10, 2))
246 # A transpose makes the array non-contiguous
247 >>> b = a.T
249 # Taking a view makes it possible to modify the shape without modifying
250 # the initial object.
251 >>> c = b.view()
252 >>> c.shape = (20)
253 Traceback (most recent call last):
254 ...
255 AttributeError: Incompatible shape for in-place modification. Use
256 `.reshape()` to make a copy with the desired shape.
258 The `order` keyword gives the index ordering both for *fetching* the values
259 from `a`, and then *placing* the values into the output array.
260 For example, let's say you have an array:
262 >>> a = np.arange(6).reshape((3, 2))
263 >>> a
264 array([[0, 1],
265 [2, 3],
266 [4, 5]])
268 You can think of reshaping as first raveling the array (using the given
269 index order), then inserting the elements from the raveled array into the
270 new array using the same kind of index ordering as was used for the
271 raveling.
273 >>> np.reshape(a, (2, 3)) # C-like index ordering
274 array([[0, 1, 2],
275 [3, 4, 5]])
276 >>> np.reshape(np.ravel(a), (2, 3)) # equivalent to C ravel then C reshape
277 array([[0, 1, 2],
278 [3, 4, 5]])
279 >>> np.reshape(a, (2, 3), order='F') # Fortran-like index ordering
280 array([[0, 4, 3],
281 [2, 1, 5]])
282 >>> np.reshape(np.ravel(a, order='F'), (2, 3), order='F')
283 array([[0, 4, 3],
284 [2, 1, 5]])
286 Examples
287 --------
288 >>> a = np.array([[1,2,3], [4,5,6]])
289 >>> np.reshape(a, 6)
290 array([1, 2, 3, 4, 5, 6])
291 >>> np.reshape(a, 6, order='F')
292 array([1, 4, 2, 5, 3, 6])
294 >>> np.reshape(a, (3,-1)) # the unspecified value is inferred to be 2
295 array([[1, 2],
296 [3, 4],
297 [5, 6]])
298 """
299 return _wrapfunc(a, 'reshape', newshape, order=order)
302def _choose_dispatcher(a, choices, out=None, mode=None):
303 yield a
304 yield from choices
305 yield out
308@array_function_dispatch(_choose_dispatcher)
309def choose(a, choices, out=None, mode='raise'):
310 """
311 Construct an array from an index array and a set of arrays to choose from.
313 First of all, if confused or uncertain, definitely look at the Examples -
314 in its full generality, this function is less simple than it might
315 seem from the following code description (below ndi =
316 `numpy.lib.index_tricks`):
318 ``np.choose(a,c) == np.array([c[a[I]][I] for I in ndi.ndindex(a.shape)])``.
320 But this omits some subtleties. Here is a fully general summary:
322 Given an "index" array (`a`) of integers and a sequence of `n` arrays
323 (`choices`), `a` and each choice array are first broadcast, as necessary,
324 to arrays of a common shape; calling these *Ba* and *Bchoices[i], i =
325 0,...,n-1* we have that, necessarily, ``Ba.shape == Bchoices[i].shape``
326 for each `i`. Then, a new array with shape ``Ba.shape`` is created as
327 follows:
329 * if ``mode=raise`` (the default), then, first of all, each element of
330 `a` (and thus `Ba`) must be in the range `[0, n-1]`; now, suppose that
331 `i` (in that range) is the value at the `(j0, j1, ..., jm)` position
332 in `Ba` - then the value at the same position in the new array is the
333 value in `Bchoices[i]` at that same position;
335 * if ``mode=wrap``, values in `a` (and thus `Ba`) may be any (signed)
336 integer; modular arithmetic is used to map integers outside the range
337 `[0, n-1]` back into that range; and then the new array is constructed
338 as above;
340 * if ``mode=clip``, values in `a` (and thus `Ba`) may be any (signed)
341 integer; negative integers are mapped to 0; values greater than `n-1`
342 are mapped to `n-1`; and then the new array is constructed as above.
344 Parameters
345 ----------
346 a : int array
347 This array must contain integers in `[0, n-1]`, where `n` is the number
348 of choices, unless ``mode=wrap`` or ``mode=clip``, in which cases any
349 integers are permissible.
350 choices : sequence of arrays
351 Choice arrays. `a` and all of the choices must be broadcastable to the
352 same shape. If `choices` is itself an array (not recommended), then
353 its outermost dimension (i.e., the one corresponding to
354 ``choices.shape[0]``) is taken as defining the "sequence".
355 out : array, optional
356 If provided, the result will be inserted into this array. It should
357 be of the appropriate shape and dtype. Note that `out` is always
358 buffered if `mode='raise'`; use other modes for better performance.
359 mode : {'raise' (default), 'wrap', 'clip'}, optional
360 Specifies how indices outside `[0, n-1]` will be treated:
362 * 'raise' : an exception is raised
363 * 'wrap' : value becomes value mod `n`
364 * 'clip' : values < 0 are mapped to 0, values > n-1 are mapped to n-1
366 Returns
367 -------
368 merged_array : array
369 The merged result.
371 Raises
372 ------
373 ValueError: shape mismatch
374 If `a` and each choice array are not all broadcastable to the same
375 shape.
377 See Also
378 --------
379 ndarray.choose : equivalent method
380 numpy.take_along_axis : Preferable if `choices` is an array
382 Notes
383 -----
384 To reduce the chance of misinterpretation, even though the following
385 "abuse" is nominally supported, `choices` should neither be, nor be
386 thought of as, a single array, i.e., the outermost sequence-like container
387 should be either a list or a tuple.
389 Examples
390 --------
392 >>> choices = [[0, 1, 2, 3], [10, 11, 12, 13],
393 ... [20, 21, 22, 23], [30, 31, 32, 33]]
394 >>> np.choose([2, 3, 1, 0], choices
395 ... # the first element of the result will be the first element of the
396 ... # third (2+1) "array" in choices, namely, 20; the second element
397 ... # will be the second element of the fourth (3+1) choice array, i.e.,
398 ... # 31, etc.
399 ... )
400 array([20, 31, 12, 3])
401 >>> np.choose([2, 4, 1, 0], choices, mode='clip') # 4 goes to 3 (4-1)
402 array([20, 31, 12, 3])
403 >>> # because there are 4 choice arrays
404 >>> np.choose([2, 4, 1, 0], choices, mode='wrap') # 4 goes to (4 mod 4)
405 array([20, 1, 12, 3])
406 >>> # i.e., 0
408 A couple examples illustrating how choose broadcasts:
410 >>> a = [[1, 0, 1], [0, 1, 0], [1, 0, 1]]
411 >>> choices = [-10, 10]
412 >>> np.choose(a, choices)
413 array([[ 10, -10, 10],
414 [-10, 10, -10],
415 [ 10, -10, 10]])
417 >>> # With thanks to Anne Archibald
418 >>> a = np.array([0, 1]).reshape((2,1,1))
419 >>> c1 = np.array([1, 2, 3]).reshape((1,3,1))
420 >>> c2 = np.array([-1, -2, -3, -4, -5]).reshape((1,1,5))
421 >>> np.choose(a, (c1, c2)) # result is 2x3x5, res[0,:,:]=c1, res[1,:,:]=c2
422 array([[[ 1, 1, 1, 1, 1],
423 [ 2, 2, 2, 2, 2],
424 [ 3, 3, 3, 3, 3]],
425 [[-1, -2, -3, -4, -5],
426 [-1, -2, -3, -4, -5],
427 [-1, -2, -3, -4, -5]]])
429 """
430 return _wrapfunc(a, 'choose', choices, out=out, mode=mode)
433def _repeat_dispatcher(a, repeats, axis=None):
434 return (a,)
437@array_function_dispatch(_repeat_dispatcher)
438def repeat(a, repeats, axis=None):
439 """
440 Repeat elements of an array.
442 Parameters
443 ----------
444 a : array_like
445 Input array.
446 repeats : int or array of ints
447 The number of repetitions for each element. `repeats` is broadcasted
448 to fit the shape of the given axis.
449 axis : int, optional
450 The axis along which to repeat values. By default, use the
451 flattened input array, and return a flat output array.
453 Returns
454 -------
455 repeated_array : ndarray
456 Output array which has the same shape as `a`, except along
457 the given axis.
459 See Also
460 --------
461 tile : Tile an array.
463 Examples
464 --------
465 >>> np.repeat(3, 4)
466 array([3, 3, 3, 3])
467 >>> x = np.array([[1,2],[3,4]])
468 >>> np.repeat(x, 2)
469 array([1, 1, 2, 2, 3, 3, 4, 4])
470 >>> np.repeat(x, 3, axis=1)
471 array([[1, 1, 1, 2, 2, 2],
472 [3, 3, 3, 4, 4, 4]])
473 >>> np.repeat(x, [1, 2], axis=0)
474 array([[1, 2],
475 [3, 4],
476 [3, 4]])
478 """
479 return _wrapfunc(a, 'repeat', repeats, axis=axis)
482def _put_dispatcher(a, ind, v, mode=None):
483 return (a, ind, v)
486@array_function_dispatch(_put_dispatcher)
487def put(a, ind, v, mode='raise'):
488 """
489 Replaces specified elements of an array with given values.
491 The indexing works on the flattened target array. `put` is roughly
492 equivalent to:
494 ::
496 a.flat[ind] = v
498 Parameters
499 ----------
500 a : ndarray
501 Target array.
502 ind : array_like
503 Target indices, interpreted as integers.
504 v : array_like
505 Values to place in `a` at target indices. If `v` is shorter than
506 `ind` it will be repeated as necessary.
507 mode : {'raise', 'wrap', 'clip'}, optional
508 Specifies how out-of-bounds indices will behave.
510 * 'raise' -- raise an error (default)
511 * 'wrap' -- wrap around
512 * 'clip' -- clip to the range
514 'clip' mode means that all indices that are too large are replaced
515 by the index that addresses the last element along that axis. Note
516 that this disables indexing with negative numbers. In 'raise' mode,
517 if an exception occurs the target array may still be modified.
519 See Also
520 --------
521 putmask, place
522 put_along_axis : Put elements by matching the array and the index arrays
524 Examples
525 --------
526 >>> a = np.arange(5)
527 >>> np.put(a, [0, 2], [-44, -55])
528 >>> a
529 array([-44, 1, -55, 3, 4])
531 >>> a = np.arange(5)
532 >>> np.put(a, 22, -5, mode='clip')
533 >>> a
534 array([ 0, 1, 2, 3, -5])
536 """
537 try:
538 put = a.put
539 except AttributeError:
540 raise TypeError("argument 1 must be numpy.ndarray, "
541 "not {name}".format(name=type(a).__name__))
543 return put(ind, v, mode=mode)
546def _swapaxes_dispatcher(a, axis1, axis2):
547 return (a,)
550@array_function_dispatch(_swapaxes_dispatcher)
551def swapaxes(a, axis1, axis2):
552 """
553 Interchange two axes of an array.
555 Parameters
556 ----------
557 a : array_like
558 Input array.
559 axis1 : int
560 First axis.
561 axis2 : int
562 Second axis.
564 Returns
565 -------
566 a_swapped : ndarray
567 For NumPy >= 1.10.0, if `a` is an ndarray, then a view of `a` is
568 returned; otherwise a new array is created. For earlier NumPy
569 versions a view of `a` is returned only if the order of the
570 axes is changed, otherwise the input array is returned.
572 Examples
573 --------
574 >>> x = np.array([[1,2,3]])
575 >>> np.swapaxes(x,0,1)
576 array([[1],
577 [2],
578 [3]])
580 >>> x = np.array([[[0,1],[2,3]],[[4,5],[6,7]]])
581 >>> x
582 array([[[0, 1],
583 [2, 3]],
584 [[4, 5],
585 [6, 7]]])
587 >>> np.swapaxes(x,0,2)
588 array([[[0, 4],
589 [2, 6]],
590 [[1, 5],
591 [3, 7]]])
593 """
594 return _wrapfunc(a, 'swapaxes', axis1, axis2)
597def _transpose_dispatcher(a, axes=None):
598 return (a,)
601@array_function_dispatch(_transpose_dispatcher)
602def transpose(a, axes=None):
603 """
604 Reverse or permute the axes of an array; returns the modified array.
606 For an array a with two axes, transpose(a) gives the matrix transpose.
608 Parameters
609 ----------
610 a : array_like
611 Input array.
612 axes : tuple or list of ints, optional
613 If specified, it must be a tuple or list which contains a permutation of
614 [0,1,..,N-1] where N is the number of axes of a. The i'th axis of the
615 returned array will correspond to the axis numbered ``axes[i]`` of the
616 input. If not specified, defaults to ``range(a.ndim)[::-1]``, which
617 reverses the order of the axes.
619 Returns
620 -------
621 p : ndarray
622 `a` with its axes permuted. A view is returned whenever
623 possible.
625 See Also
626 --------
627 moveaxis
628 argsort
630 Notes
631 -----
632 Use `transpose(a, argsort(axes))` to invert the transposition of tensors
633 when using the `axes` keyword argument.
635 Transposing a 1-D array returns an unchanged view of the original array.
637 Examples
638 --------
639 >>> x = np.arange(4).reshape((2,2))
640 >>> x
641 array([[0, 1],
642 [2, 3]])
644 >>> np.transpose(x)
645 array([[0, 2],
646 [1, 3]])
648 >>> x = np.ones((1, 2, 3))
649 >>> np.transpose(x, (1, 0, 2)).shape
650 (2, 1, 3)
652 """
653 return _wrapfunc(a, 'transpose', axes)
656def _partition_dispatcher(a, kth, axis=None, kind=None, order=None):
657 return (a,)
660@array_function_dispatch(_partition_dispatcher)
661def partition(a, kth, axis=-1, kind='introselect', order=None):
662 """
663 Return a partitioned copy of an array.
665 Creates a copy of the array with its elements rearranged in such a
666 way that the value of the element in k-th position is in the
667 position it would be in a sorted array. All elements smaller than
668 the k-th element are moved before this element and all equal or
669 greater are moved behind it. The ordering of the elements in the two
670 partitions is undefined.
672 .. versionadded:: 1.8.0
674 Parameters
675 ----------
676 a : array_like
677 Array to be sorted.
678 kth : int or sequence of ints
679 Element index to partition by. The k-th value of the element
680 will be in its final sorted position and all smaller elements
681 will be moved before it and all equal or greater elements behind
682 it. The order of all elements in the partitions is undefined. If
683 provided with a sequence of k-th it will partition all elements
684 indexed by k-th of them into their sorted position at once.
685 axis : int or None, optional
686 Axis along which to sort. If None, the array is flattened before
687 sorting. The default is -1, which sorts along the last axis.
688 kind : {'introselect'}, optional
689 Selection algorithm. Default is 'introselect'.
690 order : str or list of str, optional
691 When `a` is an array with fields defined, this argument
692 specifies which fields to compare first, second, etc. A single
693 field can be specified as a string. Not all fields need be
694 specified, but unspecified fields will still be used, in the
695 order in which they come up in the dtype, to break ties.
697 Returns
698 -------
699 partitioned_array : ndarray
700 Array of the same type and shape as `a`.
702 See Also
703 --------
704 ndarray.partition : Method to sort an array in-place.
705 argpartition : Indirect partition.
706 sort : Full sorting
708 Notes
709 -----
710 The various selection algorithms are characterized by their average
711 speed, worst case performance, work space size, and whether they are
712 stable. A stable sort keeps items with the same key in the same
713 relative order. The available algorithms have the following
714 properties:
716 ================= ======= ============= ============ =======
717 kind speed worst case work space stable
718 ================= ======= ============= ============ =======
719 'introselect' 1 O(n) 0 no
720 ================= ======= ============= ============ =======
722 All the partition algorithms make temporary copies of the data when
723 partitioning along any but the last axis. Consequently,
724 partitioning along the last axis is faster and uses less space than
725 partitioning along any other axis.
727 The sort order for complex numbers is lexicographic. If both the
728 real and imaginary parts are non-nan then the order is determined by
729 the real parts except when they are equal, in which case the order
730 is determined by the imaginary parts.
732 Examples
733 --------
734 >>> a = np.array([3, 4, 2, 1])
735 >>> np.partition(a, 3)
736 array([2, 1, 3, 4])
738 >>> np.partition(a, (1, 3))
739 array([1, 2, 3, 4])
741 """
742 if axis is None:
743 # flatten returns (1, N) for np.matrix, so always use the last axis
744 a = asanyarray(a).flatten()
745 axis = -1
746 else:
747 a = asanyarray(a).copy(order="K")
748 a.partition(kth, axis=axis, kind=kind, order=order)
749 return a
752def _argpartition_dispatcher(a, kth, axis=None, kind=None, order=None):
753 return (a,)
756@array_function_dispatch(_argpartition_dispatcher)
757def argpartition(a, kth, axis=-1, kind='introselect', order=None):
758 """
759 Perform an indirect partition along the given axis using the
760 algorithm specified by the `kind` keyword. It returns an array of
761 indices of the same shape as `a` that index data along the given
762 axis in partitioned order.
764 .. versionadded:: 1.8.0
766 Parameters
767 ----------
768 a : array_like
769 Array to sort.
770 kth : int or sequence of ints
771 Element index to partition by. The k-th element will be in its
772 final sorted position and all smaller elements will be moved
773 before it and all larger elements behind it. The order all
774 elements in the partitions is undefined. If provided with a
775 sequence of k-th it will partition all of them into their sorted
776 position at once.
777 axis : int or None, optional
778 Axis along which to sort. The default is -1 (the last axis). If
779 None, the flattened array is used.
780 kind : {'introselect'}, optional
781 Selection algorithm. Default is 'introselect'
782 order : str or list of str, optional
783 When `a` is an array with fields defined, this argument
784 specifies which fields to compare first, second, etc. A single
785 field can be specified as a string, and not all fields need be
786 specified, but unspecified fields will still be used, in the
787 order in which they come up in the dtype, to break ties.
789 Returns
790 -------
791 index_array : ndarray, int
792 Array of indices that partition `a` along the specified axis.
793 If `a` is one-dimensional, ``a[index_array]`` yields a partitioned `a`.
794 More generally, ``np.take_along_axis(a, index_array, axis=a)`` always
795 yields the partitioned `a`, irrespective of dimensionality.
797 See Also
798 --------
799 partition : Describes partition algorithms used.
800 ndarray.partition : Inplace partition.
801 argsort : Full indirect sort.
802 take_along_axis : Apply ``index_array`` from argpartition
803 to an array as if by calling partition.
805 Notes
806 -----
807 See `partition` for notes on the different selection algorithms.
809 Examples
810 --------
811 One dimensional array:
813 >>> x = np.array([3, 4, 2, 1])
814 >>> x[np.argpartition(x, 3)]
815 array([2, 1, 3, 4])
816 >>> x[np.argpartition(x, (1, 3))]
817 array([1, 2, 3, 4])
819 >>> x = [3, 4, 2, 1]
820 >>> np.array(x)[np.argpartition(x, 3)]
821 array([2, 1, 3, 4])
823 Multi-dimensional array:
825 >>> x = np.array([[3, 4, 2], [1, 3, 1]])
826 >>> index_array = np.argpartition(x, kth=1, axis=-1)
827 >>> np.take_along_axis(x, index_array, axis=-1) # same as np.partition(x, kth=1)
828 array([[2, 3, 4],
829 [1, 1, 3]])
831 """
832 return _wrapfunc(a, 'argpartition', kth, axis=axis, kind=kind, order=order)
835def _sort_dispatcher(a, axis=None, kind=None, order=None):
836 return (a,)
839@array_function_dispatch(_sort_dispatcher)
840def sort(a, axis=-1, kind=None, order=None):
841 """
842 Return a sorted copy of an array.
844 Parameters
845 ----------
846 a : array_like
847 Array to be sorted.
848 axis : int or None, optional
849 Axis along which to sort. If None, the array is flattened before
850 sorting. The default is -1, which sorts along the last axis.
851 kind : {'quicksort', 'mergesort', 'heapsort', 'stable'}, optional
852 Sorting algorithm. The default is 'quicksort'. Note that both 'stable'
853 and 'mergesort' use timsort or radix sort under the covers and, in general,
854 the actual implementation will vary with data type. The 'mergesort' option
855 is retained for backwards compatibility.
857 .. versionchanged:: 1.15.0.
858 The 'stable' option was added.
860 order : str or list of str, optional
861 When `a` is an array with fields defined, this argument specifies
862 which fields to compare first, second, etc. A single field can
863 be specified as a string, and not all fields need be specified,
864 but unspecified fields will still be used, in the order in which
865 they come up in the dtype, to break ties.
867 Returns
868 -------
869 sorted_array : ndarray
870 Array of the same type and shape as `a`.
872 See Also
873 --------
874 ndarray.sort : Method to sort an array in-place.
875 argsort : Indirect sort.
876 lexsort : Indirect stable sort on multiple keys.
877 searchsorted : Find elements in a sorted array.
878 partition : Partial sort.
880 Notes
881 -----
882 The various sorting algorithms are characterized by their average speed,
883 worst case performance, work space size, and whether they are stable. A
884 stable sort keeps items with the same key in the same relative
885 order. The four algorithms implemented in NumPy have the following
886 properties:
888 =========== ======= ============= ============ ========
889 kind speed worst case work space stable
890 =========== ======= ============= ============ ========
891 'quicksort' 1 O(n^2) 0 no
892 'heapsort' 3 O(n*log(n)) 0 no
893 'mergesort' 2 O(n*log(n)) ~n/2 yes
894 'timsort' 2 O(n*log(n)) ~n/2 yes
895 =========== ======= ============= ============ ========
897 .. note:: The datatype determines which of 'mergesort' or 'timsort'
898 is actually used, even if 'mergesort' is specified. User selection
899 at a finer scale is not currently available.
901 All the sort algorithms make temporary copies of the data when
902 sorting along any but the last axis. Consequently, sorting along
903 the last axis is faster and uses less space than sorting along
904 any other axis.
906 The sort order for complex numbers is lexicographic. If both the real
907 and imaginary parts are non-nan then the order is determined by the
908 real parts except when they are equal, in which case the order is
909 determined by the imaginary parts.
911 Previous to numpy 1.4.0 sorting real and complex arrays containing nan
912 values led to undefined behaviour. In numpy versions >= 1.4.0 nan
913 values are sorted to the end. The extended sort order is:
915 * Real: [R, nan]
916 * Complex: [R + Rj, R + nanj, nan + Rj, nan + nanj]
918 where R is a non-nan real value. Complex values with the same nan
919 placements are sorted according to the non-nan part if it exists.
920 Non-nan values are sorted as before.
922 .. versionadded:: 1.12.0
924 quicksort has been changed to `introsort <https://en.wikipedia.org/wiki/Introsort>`_.
925 When sorting does not make enough progress it switches to
926 `heapsort <https://en.wikipedia.org/wiki/Heapsort>`_.
927 This implementation makes quicksort O(n*log(n)) in the worst case.
929 'stable' automatically chooses the best stable sorting algorithm
930 for the data type being sorted.
931 It, along with 'mergesort' is currently mapped to
932 `timsort <https://en.wikipedia.org/wiki/Timsort>`_
933 or `radix sort <https://en.wikipedia.org/wiki/Radix_sort>`_
934 depending on the data type.
935 API forward compatibility currently limits the
936 ability to select the implementation and it is hardwired for the different
937 data types.
939 .. versionadded:: 1.17.0
941 Timsort is added for better performance on already or nearly
942 sorted data. On random data timsort is almost identical to
943 mergesort. It is now used for stable sort while quicksort is still the
944 default sort if none is chosen. For timsort details, refer to
945 `CPython listsort.txt <https://github.com/python/cpython/blob/3.7/Objects/listsort.txt>`_.
946 'mergesort' and 'stable' are mapped to radix sort for integer data types. Radix sort is an
947 O(n) sort instead of O(n log n).
949 .. versionchanged:: 1.18.0
951 NaT now sorts to the end of arrays for consistency with NaN.
953 Examples
954 --------
955 >>> a = np.array([[1,4],[3,1]])
956 >>> np.sort(a) # sort along the last axis
957 array([[1, 4],
958 [1, 3]])
959 >>> np.sort(a, axis=None) # sort the flattened array
960 array([1, 1, 3, 4])
961 >>> np.sort(a, axis=0) # sort along the first axis
962 array([[1, 1],
963 [3, 4]])
965 Use the `order` keyword to specify a field to use when sorting a
966 structured array:
968 >>> dtype = [('name', 'S10'), ('height', float), ('age', int)]
969 >>> values = [('Arthur', 1.8, 41), ('Lancelot', 1.9, 38),
970 ... ('Galahad', 1.7, 38)]
971 >>> a = np.array(values, dtype=dtype) # create a structured array
972 >>> np.sort(a, order='height') # doctest: +SKIP
973 array([('Galahad', 1.7, 38), ('Arthur', 1.8, 41),
974 ('Lancelot', 1.8999999999999999, 38)],
975 dtype=[('name', '|S10'), ('height', '<f8'), ('age', '<i4')])
977 Sort by age, then height if ages are equal:
979 >>> np.sort(a, order=['age', 'height']) # doctest: +SKIP
980 array([('Galahad', 1.7, 38), ('Lancelot', 1.8999999999999999, 38),
981 ('Arthur', 1.8, 41)],
982 dtype=[('name', '|S10'), ('height', '<f8'), ('age', '<i4')])
984 """
985 if axis is None:
986 # flatten returns (1, N) for np.matrix, so always use the last axis
987 a = asanyarray(a).flatten()
988 axis = -1
989 else:
990 a = asanyarray(a).copy(order="K")
991 a.sort(axis=axis, kind=kind, order=order)
992 return a
995def _argsort_dispatcher(a, axis=None, kind=None, order=None):
996 return (a,)
999@array_function_dispatch(_argsort_dispatcher)
1000def argsort(a, axis=-1, kind=None, order=None):
1001 """
1002 Returns the indices that would sort an array.
1004 Perform an indirect sort along the given axis using the algorithm specified
1005 by the `kind` keyword. It returns an array of indices of the same shape as
1006 `a` that index data along the given axis in sorted order.
1008 Parameters
1009 ----------
1010 a : array_like
1011 Array to sort.
1012 axis : int or None, optional
1013 Axis along which to sort. The default is -1 (the last axis). If None,
1014 the flattened array is used.
1015 kind : {'quicksort', 'mergesort', 'heapsort', 'stable'}, optional
1016 Sorting algorithm. The default is 'quicksort'. Note that both 'stable'
1017 and 'mergesort' use timsort under the covers and, in general, the
1018 actual implementation will vary with data type. The 'mergesort' option
1019 is retained for backwards compatibility.
1021 .. versionchanged:: 1.15.0.
1022 The 'stable' option was added.
1023 order : str or list of str, optional
1024 When `a` is an array with fields defined, this argument specifies
1025 which fields to compare first, second, etc. A single field can
1026 be specified as a string, and not all fields need be specified,
1027 but unspecified fields will still be used, in the order in which
1028 they come up in the dtype, to break ties.
1030 Returns
1031 -------
1032 index_array : ndarray, int
1033 Array of indices that sort `a` along the specified `axis`.
1034 If `a` is one-dimensional, ``a[index_array]`` yields a sorted `a`.
1035 More generally, ``np.take_along_axis(a, index_array, axis=axis)``
1036 always yields the sorted `a`, irrespective of dimensionality.
1038 See Also
1039 --------
1040 sort : Describes sorting algorithms used.
1041 lexsort : Indirect stable sort with multiple keys.
1042 ndarray.sort : Inplace sort.
1043 argpartition : Indirect partial sort.
1044 take_along_axis : Apply ``index_array`` from argsort
1045 to an array as if by calling sort.
1047 Notes
1048 -----
1049 See `sort` for notes on the different sorting algorithms.
1051 As of NumPy 1.4.0 `argsort` works with real/complex arrays containing
1052 nan values. The enhanced sort order is documented in `sort`.
1054 Examples
1055 --------
1056 One dimensional array:
1058 >>> x = np.array([3, 1, 2])
1059 >>> np.argsort(x)
1060 array([1, 2, 0])
1062 Two-dimensional array:
1064 >>> x = np.array([[0, 3], [2, 2]])
1065 >>> x
1066 array([[0, 3],
1067 [2, 2]])
1069 >>> ind = np.argsort(x, axis=0) # sorts along first axis (down)
1070 >>> ind
1071 array([[0, 1],
1072 [1, 0]])
1073 >>> np.take_along_axis(x, ind, axis=0) # same as np.sort(x, axis=0)
1074 array([[0, 2],
1075 [2, 3]])
1077 >>> ind = np.argsort(x, axis=1) # sorts along last axis (across)
1078 >>> ind
1079 array([[0, 1],
1080 [0, 1]])
1081 >>> np.take_along_axis(x, ind, axis=1) # same as np.sort(x, axis=1)
1082 array([[0, 3],
1083 [2, 2]])
1085 Indices of the sorted elements of a N-dimensional array:
1087 >>> ind = np.unravel_index(np.argsort(x, axis=None), x.shape)
1088 >>> ind
1089 (array([0, 1, 1, 0]), array([0, 0, 1, 1]))
1090 >>> x[ind] # same as np.sort(x, axis=None)
1091 array([0, 2, 2, 3])
1093 Sorting with keys:
1095 >>> x = np.array([(1, 0), (0, 1)], dtype=[('x', '<i4'), ('y', '<i4')])
1096 >>> x
1097 array([(1, 0), (0, 1)],
1098 dtype=[('x', '<i4'), ('y', '<i4')])
1100 >>> np.argsort(x, order=('x','y'))
1101 array([1, 0])
1103 >>> np.argsort(x, order=('y','x'))
1104 array([0, 1])
1106 """
1107 return _wrapfunc(a, 'argsort', axis=axis, kind=kind, order=order)
1110def _argmax_dispatcher(a, axis=None, out=None):
1111 return (a, out)
1114@array_function_dispatch(_argmax_dispatcher)
1115def argmax(a, axis=None, out=None):
1116 """
1117 Returns the indices of the maximum values along an axis.
1119 Parameters
1120 ----------
1121 a : array_like
1122 Input array.
1123 axis : int, optional
1124 By default, the index is into the flattened array, otherwise
1125 along the specified axis.
1126 out : array, optional
1127 If provided, the result will be inserted into this array. It should
1128 be of the appropriate shape and dtype.
1130 Returns
1131 -------
1132 index_array : ndarray of ints
1133 Array of indices into the array. It has the same shape as `a.shape`
1134 with the dimension along `axis` removed.
1136 See Also
1137 --------
1138 ndarray.argmax, argmin
1139 amax : The maximum value along a given axis.
1140 unravel_index : Convert a flat index into an index tuple.
1141 take_along_axis : Apply ``np.expand_dims(index_array, axis)``
1142 from argmax to an array as if by calling max.
1144 Notes
1145 -----
1146 In case of multiple occurrences of the maximum values, the indices
1147 corresponding to the first occurrence are returned.
1149 Examples
1150 --------
1151 >>> a = np.arange(6).reshape(2,3) + 10
1152 >>> a
1153 array([[10, 11, 12],
1154 [13, 14, 15]])
1155 >>> np.argmax(a)
1156 5
1157 >>> np.argmax(a, axis=0)
1158 array([1, 1, 1])
1159 >>> np.argmax(a, axis=1)
1160 array([2, 2])
1162 Indexes of the maximal elements of a N-dimensional array:
1164 >>> ind = np.unravel_index(np.argmax(a, axis=None), a.shape)
1165 >>> ind
1166 (1, 2)
1167 >>> a[ind]
1168 15
1170 >>> b = np.arange(6)
1171 >>> b[1] = 5
1172 >>> b
1173 array([0, 5, 2, 3, 4, 5])
1174 >>> np.argmax(b) # Only the first occurrence is returned.
1175 1
1177 >>> x = np.array([[4,2,3], [1,0,3]])
1178 >>> index_array = np.argmax(x, axis=-1)
1179 >>> # Same as np.max(x, axis=-1, keepdims=True)
1180 >>> np.take_along_axis(x, np.expand_dims(index_array, axis=-1), axis=-1)
1181 array([[4],
1182 [3]])
1183 >>> # Same as np.max(x, axis=-1)
1184 >>> np.take_along_axis(x, np.expand_dims(index_array, axis=-1), axis=-1).squeeze(axis=-1)
1185 array([4, 3])
1187 """
1188 return _wrapfunc(a, 'argmax', axis=axis, out=out)
1191def _argmin_dispatcher(a, axis=None, out=None):
1192 return (a, out)
1195@array_function_dispatch(_argmin_dispatcher)
1196def argmin(a, axis=None, out=None):
1197 """
1198 Returns the indices of the minimum values along an axis.
1200 Parameters
1201 ----------
1202 a : array_like
1203 Input array.
1204 axis : int, optional
1205 By default, the index is into the flattened array, otherwise
1206 along the specified axis.
1207 out : array, optional
1208 If provided, the result will be inserted into this array. It should
1209 be of the appropriate shape and dtype.
1211 Returns
1212 -------
1213 index_array : ndarray of ints
1214 Array of indices into the array. It has the same shape as `a.shape`
1215 with the dimension along `axis` removed.
1217 See Also
1218 --------
1219 ndarray.argmin, argmax
1220 amin : The minimum value along a given axis.
1221 unravel_index : Convert a flat index into an index tuple.
1222 take_along_axis : Apply ``np.expand_dims(index_array, axis)``
1223 from argmin to an array as if by calling min.
1225 Notes
1226 -----
1227 In case of multiple occurrences of the minimum values, the indices
1228 corresponding to the first occurrence are returned.
1230 Examples
1231 --------
1232 >>> a = np.arange(6).reshape(2,3) + 10
1233 >>> a
1234 array([[10, 11, 12],
1235 [13, 14, 15]])
1236 >>> np.argmin(a)
1237 0
1238 >>> np.argmin(a, axis=0)
1239 array([0, 0, 0])
1240 >>> np.argmin(a, axis=1)
1241 array([0, 0])
1243 Indices of the minimum elements of a N-dimensional array:
1245 >>> ind = np.unravel_index(np.argmin(a, axis=None), a.shape)
1246 >>> ind
1247 (0, 0)
1248 >>> a[ind]
1249 10
1251 >>> b = np.arange(6) + 10
1252 >>> b[4] = 10
1253 >>> b
1254 array([10, 11, 12, 13, 10, 15])
1255 >>> np.argmin(b) # Only the first occurrence is returned.
1256 0
1258 >>> x = np.array([[4,2,3], [1,0,3]])
1259 >>> index_array = np.argmin(x, axis=-1)
1260 >>> # Same as np.min(x, axis=-1, keepdims=True)
1261 >>> np.take_along_axis(x, np.expand_dims(index_array, axis=-1), axis=-1)
1262 array([[2],
1263 [0]])
1264 >>> # Same as np.max(x, axis=-1)
1265 >>> np.take_along_axis(x, np.expand_dims(index_array, axis=-1), axis=-1).squeeze(axis=-1)
1266 array([2, 0])
1268 """
1269 return _wrapfunc(a, 'argmin', axis=axis, out=out)
1272def _searchsorted_dispatcher(a, v, side=None, sorter=None):
1273 return (a, v, sorter)
1276@array_function_dispatch(_searchsorted_dispatcher)
1277def searchsorted(a, v, side='left', sorter=None):
1278 """
1279 Find indices where elements should be inserted to maintain order.
1281 Find the indices into a sorted array `a` such that, if the
1282 corresponding elements in `v` were inserted before the indices, the
1283 order of `a` would be preserved.
1285 Assuming that `a` is sorted:
1287 ====== ============================
1288 `side` returned index `i` satisfies
1289 ====== ============================
1290 left ``a[i-1] < v <= a[i]``
1291 right ``a[i-1] <= v < a[i]``
1292 ====== ============================
1294 Parameters
1295 ----------
1296 a : 1-D array_like
1297 Input array. If `sorter` is None, then it must be sorted in
1298 ascending order, otherwise `sorter` must be an array of indices
1299 that sort it.
1300 v : array_like
1301 Values to insert into `a`.
1302 side : {'left', 'right'}, optional
1303 If 'left', the index of the first suitable location found is given.
1304 If 'right', return the last such index. If there is no suitable
1305 index, return either 0 or N (where N is the length of `a`).
1306 sorter : 1-D array_like, optional
1307 Optional array of integer indices that sort array a into ascending
1308 order. They are typically the result of argsort.
1310 .. versionadded:: 1.7.0
1312 Returns
1313 -------
1314 indices : array of ints
1315 Array of insertion points with the same shape as `v`.
1317 See Also
1318 --------
1319 sort : Return a sorted copy of an array.
1320 histogram : Produce histogram from 1-D data.
1322 Notes
1323 -----
1324 Binary search is used to find the required insertion points.
1326 As of NumPy 1.4.0 `searchsorted` works with real/complex arrays containing
1327 `nan` values. The enhanced sort order is documented in `sort`.
1329 This function uses the same algorithm as the builtin python `bisect.bisect_left`
1330 (``side='left'``) and `bisect.bisect_right` (``side='right'``) functions,
1331 which is also vectorized in the `v` argument.
1333 Examples
1334 --------
1335 >>> np.searchsorted([1,2,3,4,5], 3)
1336 2
1337 >>> np.searchsorted([1,2,3,4,5], 3, side='right')
1338 3
1339 >>> np.searchsorted([1,2,3,4,5], [-10, 10, 2, 3])
1340 array([0, 5, 1, 2])
1342 """
1343 return _wrapfunc(a, 'searchsorted', v, side=side, sorter=sorter)
1346def _resize_dispatcher(a, new_shape):
1347 return (a,)
1350@array_function_dispatch(_resize_dispatcher)
1351def resize(a, new_shape):
1352 """
1353 Return a new array with the specified shape.
1355 If the new array is larger than the original array, then the new
1356 array is filled with repeated copies of `a`. Note that this behavior
1357 is different from a.resize(new_shape) which fills with zeros instead
1358 of repeated copies of `a`.
1360 Parameters
1361 ----------
1362 a : array_like
1363 Array to be resized.
1365 new_shape : int or tuple of int
1366 Shape of resized array.
1368 Returns
1369 -------
1370 reshaped_array : ndarray
1371 The new array is formed from the data in the old array, repeated
1372 if necessary to fill out the required number of elements. The
1373 data are repeated in the order that they are stored in memory.
1375 See Also
1376 --------
1377 ndarray.resize : resize an array in-place.
1379 Notes
1380 -----
1381 Warning: This functionality does **not** consider axes separately,
1382 i.e. it does not apply interpolation/extrapolation.
1383 It fills the return array with the required number of elements, taken
1384 from `a` as they are laid out in memory, disregarding strides and axes.
1385 (This is in case the new shape is smaller. For larger, see above.)
1386 This functionality is therefore not suitable to resize images,
1387 or data where each axis represents a separate and distinct entity.
1389 Examples
1390 --------
1391 >>> a=np.array([[0,1],[2,3]])
1392 >>> np.resize(a,(2,3))
1393 array([[0, 1, 2],
1394 [3, 0, 1]])
1395 >>> np.resize(a,(1,4))
1396 array([[0, 1, 2, 3]])
1397 >>> np.resize(a,(2,4))
1398 array([[0, 1, 2, 3],
1399 [0, 1, 2, 3]])
1401 """
1402 if isinstance(new_shape, (int, nt.integer)):
1403 new_shape = (new_shape,)
1404 a = ravel(a)
1405 Na = len(a)
1406 total_size = um.multiply.reduce(new_shape)
1407 if Na == 0 or total_size == 0:
1408 return mu.zeros(new_shape, a.dtype)
1410 n_copies = int(total_size / Na)
1411 extra = total_size % Na
1413 if extra != 0:
1414 n_copies = n_copies + 1
1415 extra = Na - extra
1417 a = concatenate((a,) * n_copies)
1418 if extra > 0:
1419 a = a[:-extra]
1421 return reshape(a, new_shape)
1424def _squeeze_dispatcher(a, axis=None):
1425 return (a,)
1428@array_function_dispatch(_squeeze_dispatcher)
1429def squeeze(a, axis=None):
1430 """
1431 Remove single-dimensional entries from the shape of an array.
1433 Parameters
1434 ----------
1435 a : array_like
1436 Input data.
1437 axis : None or int or tuple of ints, optional
1438 .. versionadded:: 1.7.0
1440 Selects a subset of the single-dimensional entries in the
1441 shape. If an axis is selected with shape entry greater than
1442 one, an error is raised.
1444 Returns
1445 -------
1446 squeezed : ndarray
1447 The input array, but with all or a subset of the
1448 dimensions of length 1 removed. This is always `a` itself
1449 or a view into `a`. Note that if all axes are squeezed,
1450 the result is a 0d array and not a scalar.
1452 Raises
1453 ------
1454 ValueError
1455 If `axis` is not None, and an axis being squeezed is not of length 1
1457 See Also
1458 --------
1459 expand_dims : The inverse operation, adding singleton dimensions
1460 reshape : Insert, remove, and combine dimensions, and resize existing ones
1462 Examples
1463 --------
1464 >>> x = np.array([[[0], [1], [2]]])
1465 >>> x.shape
1466 (1, 3, 1)
1467 >>> np.squeeze(x).shape
1468 (3,)
1469 >>> np.squeeze(x, axis=0).shape
1470 (3, 1)
1471 >>> np.squeeze(x, axis=1).shape
1472 Traceback (most recent call last):
1473 ...
1474 ValueError: cannot select an axis to squeeze out which has size not equal to one
1475 >>> np.squeeze(x, axis=2).shape
1476 (1, 3)
1477 >>> x = np.array([[1234]])
1478 >>> x.shape
1479 (1, 1)
1480 >>> np.squeeze(x)
1481 array(1234) # 0d array
1482 >>> np.squeeze(x).shape
1483 ()
1484 >>> np.squeeze(x)[()]
1485 1234
1487 """
1488 try:
1489 squeeze = a.squeeze
1490 except AttributeError:
1491 return _wrapit(a, 'squeeze', axis=axis)
1492 if axis is None:
1493 return squeeze()
1494 else:
1495 return squeeze(axis=axis)
1498def _diagonal_dispatcher(a, offset=None, axis1=None, axis2=None):
1499 return (a,)
1502@array_function_dispatch(_diagonal_dispatcher)
1503def diagonal(a, offset=0, axis1=0, axis2=1):
1504 """
1505 Return specified diagonals.
1507 If `a` is 2-D, returns the diagonal of `a` with the given offset,
1508 i.e., the collection of elements of the form ``a[i, i+offset]``. If
1509 `a` has more than two dimensions, then the axes specified by `axis1`
1510 and `axis2` are used to determine the 2-D sub-array whose diagonal is
1511 returned. The shape of the resulting array can be determined by
1512 removing `axis1` and `axis2` and appending an index to the right equal
1513 to the size of the resulting diagonals.
1515 In versions of NumPy prior to 1.7, this function always returned a new,
1516 independent array containing a copy of the values in the diagonal.
1518 In NumPy 1.7 and 1.8, it continues to return a copy of the diagonal,
1519 but depending on this fact is deprecated. Writing to the resulting
1520 array continues to work as it used to, but a FutureWarning is issued.
1522 Starting in NumPy 1.9 it returns a read-only view on the original array.
1523 Attempting to write to the resulting array will produce an error.
1525 In some future release, it will return a read/write view and writing to
1526 the returned array will alter your original array. The returned array
1527 will have the same type as the input array.
1529 If you don't write to the array returned by this function, then you can
1530 just ignore all of the above.
1532 If you depend on the current behavior, then we suggest copying the
1533 returned array explicitly, i.e., use ``np.diagonal(a).copy()`` instead
1534 of just ``np.diagonal(a)``. This will work with both past and future
1535 versions of NumPy.
1537 Parameters
1538 ----------
1539 a : array_like
1540 Array from which the diagonals are taken.
1541 offset : int, optional
1542 Offset of the diagonal from the main diagonal. Can be positive or
1543 negative. Defaults to main diagonal (0).
1544 axis1 : int, optional
1545 Axis to be used as the first axis of the 2-D sub-arrays from which
1546 the diagonals should be taken. Defaults to first axis (0).
1547 axis2 : int, optional
1548 Axis to be used as the second axis of the 2-D sub-arrays from
1549 which the diagonals should be taken. Defaults to second axis (1).
1551 Returns
1552 -------
1553 array_of_diagonals : ndarray
1554 If `a` is 2-D, then a 1-D array containing the diagonal and of the
1555 same type as `a` is returned unless `a` is a `matrix`, in which case
1556 a 1-D array rather than a (2-D) `matrix` is returned in order to
1557 maintain backward compatibility.
1559 If ``a.ndim > 2``, then the dimensions specified by `axis1` and `axis2`
1560 are removed, and a new axis inserted at the end corresponding to the
1561 diagonal.
1563 Raises
1564 ------
1565 ValueError
1566 If the dimension of `a` is less than 2.
1568 See Also
1569 --------
1570 diag : MATLAB work-a-like for 1-D and 2-D arrays.
1571 diagflat : Create diagonal arrays.
1572 trace : Sum along diagonals.
1574 Examples
1575 --------
1576 >>> a = np.arange(4).reshape(2,2)
1577 >>> a
1578 array([[0, 1],
1579 [2, 3]])
1580 >>> a.diagonal()
1581 array([0, 3])
1582 >>> a.diagonal(1)
1583 array([1])
1585 A 3-D example:
1587 >>> a = np.arange(8).reshape(2,2,2); a
1588 array([[[0, 1],
1589 [2, 3]],
1590 [[4, 5],
1591 [6, 7]]])
1592 >>> a.diagonal(0, # Main diagonals of two arrays created by skipping
1593 ... 0, # across the outer(left)-most axis last and
1594 ... 1) # the "middle" (row) axis first.
1595 array([[0, 6],
1596 [1, 7]])
1598 The sub-arrays whose main diagonals we just obtained; note that each
1599 corresponds to fixing the right-most (column) axis, and that the
1600 diagonals are "packed" in rows.
1602 >>> a[:,:,0] # main diagonal is [0 6]
1603 array([[0, 2],
1604 [4, 6]])
1605 >>> a[:,:,1] # main diagonal is [1 7]
1606 array([[1, 3],
1607 [5, 7]])
1609 The anti-diagonal can be obtained by reversing the order of elements
1610 using either `numpy.flipud` or `numpy.fliplr`.
1612 >>> a = np.arange(9).reshape(3, 3)
1613 >>> a
1614 array([[0, 1, 2],
1615 [3, 4, 5],
1616 [6, 7, 8]])
1617 >>> np.fliplr(a).diagonal() # Horizontal flip
1618 array([2, 4, 6])
1619 >>> np.flipud(a).diagonal() # Vertical flip
1620 array([6, 4, 2])
1622 Note that the order in which the diagonal is retrieved varies depending
1623 on the flip function.
1624 """
1625 if isinstance(a, np.matrix):
1626 # Make diagonal of matrix 1-D to preserve backward compatibility.
1627 return asarray(a).diagonal(offset=offset, axis1=axis1, axis2=axis2)
1628 else:
1629 return asanyarray(a).diagonal(offset=offset, axis1=axis1, axis2=axis2)
1632def _trace_dispatcher(
1633 a, offset=None, axis1=None, axis2=None, dtype=None, out=None):
1634 return (a, out)
1637@array_function_dispatch(_trace_dispatcher)
1638def trace(a, offset=0, axis1=0, axis2=1, dtype=None, out=None):
1639 """
1640 Return the sum along diagonals of the array.
1642 If `a` is 2-D, the sum along its diagonal with the given offset
1643 is returned, i.e., the sum of elements ``a[i,i+offset]`` for all i.
1645 If `a` has more than two dimensions, then the axes specified by axis1 and
1646 axis2 are used to determine the 2-D sub-arrays whose traces are returned.
1647 The shape of the resulting array is the same as that of `a` with `axis1`
1648 and `axis2` removed.
1650 Parameters
1651 ----------
1652 a : array_like
1653 Input array, from which the diagonals are taken.
1654 offset : int, optional
1655 Offset of the diagonal from the main diagonal. Can be both positive
1656 and negative. Defaults to 0.
1657 axis1, axis2 : int, optional
1658 Axes to be used as the first and second axis of the 2-D sub-arrays
1659 from which the diagonals should be taken. Defaults are the first two
1660 axes of `a`.
1661 dtype : dtype, optional
1662 Determines the data-type of the returned array and of the accumulator
1663 where the elements are summed. If dtype has the value None and `a` is
1664 of integer type of precision less than the default integer
1665 precision, then the default integer precision is used. Otherwise,
1666 the precision is the same as that of `a`.
1667 out : ndarray, optional
1668 Array into which the output is placed. Its type is preserved and
1669 it must be of the right shape to hold the output.
1671 Returns
1672 -------
1673 sum_along_diagonals : ndarray
1674 If `a` is 2-D, the sum along the diagonal is returned. If `a` has
1675 larger dimensions, then an array of sums along diagonals is returned.
1677 See Also
1678 --------
1679 diag, diagonal, diagflat
1681 Examples
1682 --------
1683 >>> np.trace(np.eye(3))
1684 3.0
1685 >>> a = np.arange(8).reshape((2,2,2))
1686 >>> np.trace(a)
1687 array([6, 8])
1689 >>> a = np.arange(24).reshape((2,2,2,3))
1690 >>> np.trace(a).shape
1691 (2, 3)
1693 """
1694 if isinstance(a, np.matrix):
1695 # Get trace of matrix via an array to preserve backward compatibility.
1696 return asarray(a).trace(offset=offset, axis1=axis1, axis2=axis2, dtype=dtype, out=out)
1697 else:
1698 return asanyarray(a).trace(offset=offset, axis1=axis1, axis2=axis2, dtype=dtype, out=out)
1701def _ravel_dispatcher(a, order=None):
1702 return (a,)
1705@array_function_dispatch(_ravel_dispatcher)
1706def ravel(a, order='C'):
1707 """Return a contiguous flattened array.
1709 A 1-D array, containing the elements of the input, is returned. A copy is
1710 made only if needed.
1712 As of NumPy 1.10, the returned array will have the same type as the input
1713 array. (for example, a masked array will be returned for a masked array
1714 input)
1716 Parameters
1717 ----------
1718 a : array_like
1719 Input array. The elements in `a` are read in the order specified by
1720 `order`, and packed as a 1-D array.
1721 order : {'C','F', 'A', 'K'}, optional
1723 The elements of `a` are read using this index order. 'C' means
1724 to index the elements in row-major, C-style order,
1725 with the last axis index changing fastest, back to the first
1726 axis index changing slowest. 'F' means to index the elements
1727 in column-major, Fortran-style order, with the
1728 first index changing fastest, and the last index changing
1729 slowest. Note that the 'C' and 'F' options take no account of
1730 the memory layout of the underlying array, and only refer to
1731 the order of axis indexing. 'A' means to read the elements in
1732 Fortran-like index order if `a` is Fortran *contiguous* in
1733 memory, C-like order otherwise. 'K' means to read the
1734 elements in the order they occur in memory, except for
1735 reversing the data when strides are negative. By default, 'C'
1736 index order is used.
1738 Returns
1739 -------
1740 y : array_like
1741 y is an array of the same subtype as `a`, with shape ``(a.size,)``.
1742 Note that matrices are special cased for backward compatibility, if `a`
1743 is a matrix, then y is a 1-D ndarray.
1745 See Also
1746 --------
1747 ndarray.flat : 1-D iterator over an array.
1748 ndarray.flatten : 1-D array copy of the elements of an array
1749 in row-major order.
1750 ndarray.reshape : Change the shape of an array without changing its data.
1752 Notes
1753 -----
1754 In row-major, C-style order, in two dimensions, the row index
1755 varies the slowest, and the column index the quickest. This can
1756 be generalized to multiple dimensions, where row-major order
1757 implies that the index along the first axis varies slowest, and
1758 the index along the last quickest. The opposite holds for
1759 column-major, Fortran-style index ordering.
1761 When a view is desired in as many cases as possible, ``arr.reshape(-1)``
1762 may be preferable.
1764 Examples
1765 --------
1766 It is equivalent to ``reshape(-1, order=order)``.
1768 >>> x = np.array([[1, 2, 3], [4, 5, 6]])
1769 >>> np.ravel(x)
1770 array([1, 2, 3, 4, 5, 6])
1772 >>> x.reshape(-1)
1773 array([1, 2, 3, 4, 5, 6])
1775 >>> np.ravel(x, order='F')
1776 array([1, 4, 2, 5, 3, 6])
1778 When ``order`` is 'A', it will preserve the array's 'C' or 'F' ordering:
1780 >>> np.ravel(x.T)
1781 array([1, 4, 2, 5, 3, 6])
1782 >>> np.ravel(x.T, order='A')
1783 array([1, 2, 3, 4, 5, 6])
1785 When ``order`` is 'K', it will preserve orderings that are neither 'C'
1786 nor 'F', but won't reverse axes:
1788 >>> a = np.arange(3)[::-1]; a
1789 array([2, 1, 0])
1790 >>> a.ravel(order='C')
1791 array([2, 1, 0])
1792 >>> a.ravel(order='K')
1793 array([2, 1, 0])
1795 >>> a = np.arange(12).reshape(2,3,2).swapaxes(1,2); a
1796 array([[[ 0, 2, 4],
1797 [ 1, 3, 5]],
1798 [[ 6, 8, 10],
1799 [ 7, 9, 11]]])
1800 >>> a.ravel(order='C')
1801 array([ 0, 2, 4, 1, 3, 5, 6, 8, 10, 7, 9, 11])
1802 >>> a.ravel(order='K')
1803 array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
1805 """
1806 if isinstance(a, np.matrix):
1807 return asarray(a).ravel(order=order)
1808 else:
1809 return asanyarray(a).ravel(order=order)
1812def _nonzero_dispatcher(a):
1813 return (a,)
1816@array_function_dispatch(_nonzero_dispatcher)
1817def nonzero(a):
1818 """
1819 Return the indices of the elements that are non-zero.
1821 Returns a tuple of arrays, one for each dimension of `a`,
1822 containing the indices of the non-zero elements in that
1823 dimension. The values in `a` are always tested and returned in
1824 row-major, C-style order.
1826 To group the indices by element, rather than dimension, use `argwhere`,
1827 which returns a row for each non-zero element.
1829 .. note::
1831 When called on a zero-d array or scalar, ``nonzero(a)`` is treated
1832 as ``nonzero(atleast1d(a))``.
1834 .. deprecated:: 1.17.0
1836 Use `atleast1d` explicitly if this behavior is deliberate.
1838 Parameters
1839 ----------
1840 a : array_like
1841 Input array.
1843 Returns
1844 -------
1845 tuple_of_arrays : tuple
1846 Indices of elements that are non-zero.
1848 See Also
1849 --------
1850 flatnonzero :
1851 Return indices that are non-zero in the flattened version of the input
1852 array.
1853 ndarray.nonzero :
1854 Equivalent ndarray method.
1855 count_nonzero :
1856 Counts the number of non-zero elements in the input array.
1858 Notes
1859 -----
1860 While the nonzero values can be obtained with ``a[nonzero(a)]``, it is
1861 recommended to use ``x[x.astype(bool)]`` or ``x[x != 0]`` instead, which
1862 will correctly handle 0-d arrays.
1864 Examples
1865 --------
1866 >>> x = np.array([[3, 0, 0], [0, 4, 0], [5, 6, 0]])
1867 >>> x
1868 array([[3, 0, 0],
1869 [0, 4, 0],
1870 [5, 6, 0]])
1871 >>> np.nonzero(x)
1872 (array([0, 1, 2, 2]), array([0, 1, 0, 1]))
1874 >>> x[np.nonzero(x)]
1875 array([3, 4, 5, 6])
1876 >>> np.transpose(np.nonzero(x))
1877 array([[0, 0],
1878 [1, 1],
1879 [2, 0],
1880 [2, 1]])
1882 A common use for ``nonzero`` is to find the indices of an array, where
1883 a condition is True. Given an array `a`, the condition `a` > 3 is a
1884 boolean array and since False is interpreted as 0, np.nonzero(a > 3)
1885 yields the indices of the `a` where the condition is true.
1887 >>> a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
1888 >>> a > 3
1889 array([[False, False, False],
1890 [ True, True, True],
1891 [ True, True, True]])
1892 >>> np.nonzero(a > 3)
1893 (array([1, 1, 1, 2, 2, 2]), array([0, 1, 2, 0, 1, 2]))
1895 Using this result to index `a` is equivalent to using the mask directly:
1897 >>> a[np.nonzero(a > 3)]
1898 array([4, 5, 6, 7, 8, 9])
1899 >>> a[a > 3] # prefer this spelling
1900 array([4, 5, 6, 7, 8, 9])
1902 ``nonzero`` can also be called as a method of the array.
1904 >>> (a > 3).nonzero()
1905 (array([1, 1, 1, 2, 2, 2]), array([0, 1, 2, 0, 1, 2]))
1907 """
1908 return _wrapfunc(a, 'nonzero')
1911def _shape_dispatcher(a):
1912 return (a,)
1915@array_function_dispatch(_shape_dispatcher)
1916def shape(a):
1917 """
1918 Return the shape of an array.
1920 Parameters
1921 ----------
1922 a : array_like
1923 Input array.
1925 Returns
1926 -------
1927 shape : tuple of ints
1928 The elements of the shape tuple give the lengths of the
1929 corresponding array dimensions.
1931 See Also
1932 --------
1933 alen
1934 ndarray.shape : Equivalent array method.
1936 Examples
1937 --------
1938 >>> np.shape(np.eye(3))
1939 (3, 3)
1940 >>> np.shape([[1, 2]])
1941 (1, 2)
1942 >>> np.shape([0])
1943 (1,)
1944 >>> np.shape(0)
1945 ()
1947 >>> a = np.array([(1, 2), (3, 4)], dtype=[('x', 'i4'), ('y', 'i4')])
1948 >>> np.shape(a)
1949 (2,)
1950 >>> a.shape
1951 (2,)
1953 """
1954 try:
1955 result = a.shape
1956 except AttributeError:
1957 result = asarray(a).shape
1958 return result
1961def _compress_dispatcher(condition, a, axis=None, out=None):
1962 return (condition, a, out)
1965@array_function_dispatch(_compress_dispatcher)
1966def compress(condition, a, axis=None, out=None):
1967 """
1968 Return selected slices of an array along given axis.
1970 When working along a given axis, a slice along that axis is returned in
1971 `output` for each index where `condition` evaluates to True. When
1972 working on a 1-D array, `compress` is equivalent to `extract`.
1974 Parameters
1975 ----------
1976 condition : 1-D array of bools
1977 Array that selects which entries to return. If len(condition)
1978 is less than the size of `a` along the given axis, then output is
1979 truncated to the length of the condition array.
1980 a : array_like
1981 Array from which to extract a part.
1982 axis : int, optional
1983 Axis along which to take slices. If None (default), work on the
1984 flattened array.
1985 out : ndarray, optional
1986 Output array. Its type is preserved and it must be of the right
1987 shape to hold the output.
1989 Returns
1990 -------
1991 compressed_array : ndarray
1992 A copy of `a` without the slices along axis for which `condition`
1993 is false.
1995 See Also
1996 --------
1997 take, choose, diag, diagonal, select
1998 ndarray.compress : Equivalent method in ndarray
1999 np.extract: Equivalent method when working on 1-D arrays
2000 ufuncs-output-type
2002 Examples
2003 --------
2004 >>> a = np.array([[1, 2], [3, 4], [5, 6]])
2005 >>> a
2006 array([[1, 2],
2007 [3, 4],
2008 [5, 6]])
2009 >>> np.compress([0, 1], a, axis=0)
2010 array([[3, 4]])
2011 >>> np.compress([False, True, True], a, axis=0)
2012 array([[3, 4],
2013 [5, 6]])
2014 >>> np.compress([False, True], a, axis=1)
2015 array([[2],
2016 [4],
2017 [6]])
2019 Working on the flattened array does not return slices along an axis but
2020 selects elements.
2022 >>> np.compress([False, True], a)
2023 array([2])
2025 """
2026 return _wrapfunc(a, 'compress', condition, axis=axis, out=out)
2029def _clip_dispatcher(a, a_min, a_max, out=None, **kwargs):
2030 return (a, a_min, a_max)
2033@array_function_dispatch(_clip_dispatcher)
2034def clip(a, a_min, a_max, out=None, **kwargs):
2035 """
2036 Clip (limit) the values in an array.
2038 Given an interval, values outside the interval are clipped to
2039 the interval edges. For example, if an interval of ``[0, 1]``
2040 is specified, values smaller than 0 become 0, and values larger
2041 than 1 become 1.
2043 Equivalent to but faster than ``np.minimum(a_max, np.maximum(a, a_min))``.
2045 No check is performed to ensure ``a_min < a_max``.
2047 Parameters
2048 ----------
2049 a : array_like
2050 Array containing elements to clip.
2051 a_min : scalar or array_like or None
2052 Minimum value. If None, clipping is not performed on lower
2053 interval edge. Not more than one of `a_min` and `a_max` may be
2054 None.
2055 a_max : scalar or array_like or None
2056 Maximum value. If None, clipping is not performed on upper
2057 interval edge. Not more than one of `a_min` and `a_max` may be
2058 None. If `a_min` or `a_max` are array_like, then the three
2059 arrays will be broadcasted to match their shapes.
2060 out : ndarray, optional
2061 The results will be placed in this array. It may be the input
2062 array for in-place clipping. `out` must be of the right shape
2063 to hold the output. Its type is preserved.
2064 **kwargs
2065 For other keyword-only arguments, see the
2066 :ref:`ufunc docs <ufuncs.kwargs>`.
2068 .. versionadded:: 1.17.0
2070 Returns
2071 -------
2072 clipped_array : ndarray
2073 An array with the elements of `a`, but where values
2074 < `a_min` are replaced with `a_min`, and those > `a_max`
2075 with `a_max`.
2077 See Also
2078 --------
2079 ufuncs-output-type
2081 Examples
2082 --------
2083 >>> a = np.arange(10)
2084 >>> np.clip(a, 1, 8)
2085 array([1, 1, 2, 3, 4, 5, 6, 7, 8, 8])
2086 >>> a
2087 array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
2088 >>> np.clip(a, 3, 6, out=a)
2089 array([3, 3, 3, 3, 4, 5, 6, 6, 6, 6])
2090 >>> a = np.arange(10)
2091 >>> a
2092 array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
2093 >>> np.clip(a, [3, 4, 1, 1, 1, 4, 4, 4, 4, 4], 8)
2094 array([3, 4, 2, 3, 4, 5, 6, 7, 8, 8])
2096 """
2097 return _wrapfunc(a, 'clip', a_min, a_max, out=out, **kwargs)
2100def _sum_dispatcher(a, axis=None, dtype=None, out=None, keepdims=None,
2101 initial=None, where=None):
2102 return (a, out)
2105@array_function_dispatch(_sum_dispatcher)
2106def sum(a, axis=None, dtype=None, out=None, keepdims=np._NoValue,
2107 initial=np._NoValue, where=np._NoValue):
2108 """
2109 Sum of array elements over a given axis.
2111 Parameters
2112 ----------
2113 a : array_like
2114 Elements to sum.
2115 axis : None or int or tuple of ints, optional
2116 Axis or axes along which a sum is performed. The default,
2117 axis=None, will sum all of the elements of the input array. If
2118 axis is negative it counts from the last to the first axis.
2120 .. versionadded:: 1.7.0
2122 If axis is a tuple of ints, a sum is performed on all of the axes
2123 specified in the tuple instead of a single axis or all the axes as
2124 before.
2125 dtype : dtype, optional
2126 The type of the returned array and of the accumulator in which the
2127 elements are summed. The dtype of `a` is used by default unless `a`
2128 has an integer dtype of less precision than the default platform
2129 integer. In that case, if `a` is signed then the platform integer
2130 is used while if `a` is unsigned then an unsigned integer of the
2131 same precision as the platform integer is used.
2132 out : ndarray, optional
2133 Alternative output array in which to place the result. It must have
2134 the same shape as the expected output, but the type of the output
2135 values will be cast if necessary.
2136 keepdims : bool, optional
2137 If this is set to True, the axes which are reduced are left
2138 in the result as dimensions with size one. With this option,
2139 the result will broadcast correctly against the input array.
2141 If the default value is passed, then `keepdims` will not be
2142 passed through to the `sum` method of sub-classes of
2143 `ndarray`, however any non-default value will be. If the
2144 sub-class' method does not implement `keepdims` any
2145 exceptions will be raised.
2146 initial : scalar, optional
2147 Starting value for the sum. See `~numpy.ufunc.reduce` for details.
2149 .. versionadded:: 1.15.0
2151 where : array_like of bool, optional
2152 Elements to include in the sum. See `~numpy.ufunc.reduce` for details.
2154 .. versionadded:: 1.17.0
2156 Returns
2157 -------
2158 sum_along_axis : ndarray
2159 An array with the same shape as `a`, with the specified
2160 axis removed. If `a` is a 0-d array, or if `axis` is None, a scalar
2161 is returned. If an output array is specified, a reference to
2162 `out` is returned.
2164 See Also
2165 --------
2166 ndarray.sum : Equivalent method.
2168 add.reduce : Equivalent functionality of `add`.
2170 cumsum : Cumulative sum of array elements.
2172 trapz : Integration of array values using the composite trapezoidal rule.
2174 mean, average
2176 Notes
2177 -----
2178 Arithmetic is modular when using integer types, and no error is
2179 raised on overflow.
2181 The sum of an empty array is the neutral element 0:
2183 >>> np.sum([])
2184 0.0
2186 For floating point numbers the numerical precision of sum (and
2187 ``np.add.reduce``) is in general limited by directly adding each number
2188 individually to the result causing rounding errors in every step.
2189 However, often numpy will use a numerically better approach (partial
2190 pairwise summation) leading to improved precision in many use-cases.
2191 This improved precision is always provided when no ``axis`` is given.
2192 When ``axis`` is given, it will depend on which axis is summed.
2193 Technically, to provide the best speed possible, the improved precision
2194 is only used when the summation is along the fast axis in memory.
2195 Note that the exact precision may vary depending on other parameters.
2196 In contrast to NumPy, Python's ``math.fsum`` function uses a slower but
2197 more precise approach to summation.
2198 Especially when summing a large number of lower precision floating point
2199 numbers, such as ``float32``, numerical errors can become significant.
2200 In such cases it can be advisable to use `dtype="float64"` to use a higher
2201 precision for the output.
2203 Examples
2204 --------
2205 >>> np.sum([0.5, 1.5])
2206 2.0
2207 >>> np.sum([0.5, 0.7, 0.2, 1.5], dtype=np.int32)
2208 1
2209 >>> np.sum([[0, 1], [0, 5]])
2210 6
2211 >>> np.sum([[0, 1], [0, 5]], axis=0)
2212 array([0, 6])
2213 >>> np.sum([[0, 1], [0, 5]], axis=1)
2214 array([1, 5])
2215 >>> np.sum([[0, 1], [np.nan, 5]], where=[False, True], axis=1)
2216 array([1., 5.])
2218 If the accumulator is too small, overflow occurs:
2220 >>> np.ones(128, dtype=np.int8).sum(dtype=np.int8)
2221 -128
2223 You can also start the sum with a value other than zero:
2225 >>> np.sum([10], initial=5)
2226 15
2227 """
2228 if isinstance(a, _gentype):
2229 # 2018-02-25, 1.15.0
2230 warnings.warn(
2231 "Calling np.sum(generator) is deprecated, and in the future will give a different result. "
2232 "Use np.sum(np.fromiter(generator)) or the python sum builtin instead.",
2233 DeprecationWarning, stacklevel=3)
2235 res = _sum_(a)
2236 if out is not None:
2237 out[...] = res
2238 return out
2239 return res
2241 return _wrapreduction(a, np.add, 'sum', axis, dtype, out, keepdims=keepdims,
2242 initial=initial, where=where)
2245def _any_dispatcher(a, axis=None, out=None, keepdims=None):
2246 return (a, out)
2249@array_function_dispatch(_any_dispatcher)
2250def any(a, axis=None, out=None, keepdims=np._NoValue):
2251 """
2252 Test whether any array element along a given axis evaluates to True.
2254 Returns single boolean unless `axis` is not ``None``
2256 Parameters
2257 ----------
2258 a : array_like
2259 Input array or object that can be converted to an array.
2260 axis : None or int or tuple of ints, optional
2261 Axis or axes along which a logical OR reduction is performed.
2262 The default (``axis=None``) is to perform a logical OR over all
2263 the dimensions of the input array. `axis` may be negative, in
2264 which case it counts from the last to the first axis.
2266 .. versionadded:: 1.7.0
2268 If this is a tuple of ints, a reduction is performed on multiple
2269 axes, instead of a single axis or all the axes as before.
2270 out : ndarray, optional
2271 Alternate output array in which to place the result. It must have
2272 the same shape as the expected output and its type is preserved
2273 (e.g., if it is of type float, then it will remain so, returning
2274 1.0 for True and 0.0 for False, regardless of the type of `a`).
2275 See `ufuncs-output-type` for more details.
2277 keepdims : bool, optional
2278 If this is set to True, the axes which are reduced are left
2279 in the result as dimensions with size one. With this option,
2280 the result will broadcast correctly against the input array.
2282 If the default value is passed, then `keepdims` will not be
2283 passed through to the `any` method of sub-classes of
2284 `ndarray`, however any non-default value will be. If the
2285 sub-class' method does not implement `keepdims` any
2286 exceptions will be raised.
2288 Returns
2289 -------
2290 any : bool or ndarray
2291 A new boolean or `ndarray` is returned unless `out` is specified,
2292 in which case a reference to `out` is returned.
2294 See Also
2295 --------
2296 ndarray.any : equivalent method
2298 all : Test whether all elements along a given axis evaluate to True.
2300 Notes
2301 -----
2302 Not a Number (NaN), positive infinity and negative infinity evaluate
2303 to `True` because these are not equal to zero.
2305 Examples
2306 --------
2307 >>> np.any([[True, False], [True, True]])
2308 True
2310 >>> np.any([[True, False], [False, False]], axis=0)
2311 array([ True, False])
2313 >>> np.any([-1, 0, 5])
2314 True
2316 >>> np.any(np.nan)
2317 True
2319 >>> o=np.array(False)
2320 >>> z=np.any([-1, 4, 5], out=o)
2321 >>> z, o
2322 (array(True), array(True))
2323 >>> # Check now that z is a reference to o
2324 >>> z is o
2325 True
2326 >>> id(z), id(o) # identity of z and o # doctest: +SKIP
2327 (191614240, 191614240)
2329 """
2330 return _wrapreduction(a, np.logical_or, 'any', axis, None, out, keepdims=keepdims)
2333def _all_dispatcher(a, axis=None, out=None, keepdims=None):
2334 return (a, out)
2337@array_function_dispatch(_all_dispatcher)
2338def all(a, axis=None, out=None, keepdims=np._NoValue):
2339 """
2340 Test whether all array elements along a given axis evaluate to True.
2342 Parameters
2343 ----------
2344 a : array_like
2345 Input array or object that can be converted to an array.
2346 axis : None or int or tuple of ints, optional
2347 Axis or axes along which a logical AND reduction is performed.
2348 The default (``axis=None``) is to perform a logical AND over all
2349 the dimensions of the input array. `axis` may be negative, in
2350 which case it counts from the last to the first axis.
2352 .. versionadded:: 1.7.0
2354 If this is a tuple of ints, a reduction is performed on multiple
2355 axes, instead of a single axis or all the axes as before.
2356 out : ndarray, optional
2357 Alternate output array in which to place the result.
2358 It must have the same shape as the expected output and its
2359 type is preserved (e.g., if ``dtype(out)`` is float, the result
2360 will consist of 0.0's and 1.0's). See `ufuncs-output-type` for more
2361 details.
2363 keepdims : bool, optional
2364 If this is set to True, the axes which are reduced are left
2365 in the result as dimensions with size one. With this option,
2366 the result will broadcast correctly against the input array.
2368 If the default value is passed, then `keepdims` will not be
2369 passed through to the `all` method of sub-classes of
2370 `ndarray`, however any non-default value will be. If the
2371 sub-class' method does not implement `keepdims` any
2372 exceptions will be raised.
2374 Returns
2375 -------
2376 all : ndarray, bool
2377 A new boolean or array is returned unless `out` is specified,
2378 in which case a reference to `out` is returned.
2380 See Also
2381 --------
2382 ndarray.all : equivalent method
2384 any : Test whether any element along a given axis evaluates to True.
2386 Notes
2387 -----
2388 Not a Number (NaN), positive infinity and negative infinity
2389 evaluate to `True` because these are not equal to zero.
2391 Examples
2392 --------
2393 >>> np.all([[True,False],[True,True]])
2394 False
2396 >>> np.all([[True,False],[True,True]], axis=0)
2397 array([ True, False])
2399 >>> np.all([-1, 4, 5])
2400 True
2402 >>> np.all([1.0, np.nan])
2403 True
2405 >>> o=np.array(False)
2406 >>> z=np.all([-1, 4, 5], out=o)
2407 >>> id(z), id(o), z
2408 (28293632, 28293632, array(True)) # may vary
2410 """
2411 return _wrapreduction(a, np.logical_and, 'all', axis, None, out, keepdims=keepdims)
2414def _cumsum_dispatcher(a, axis=None, dtype=None, out=None):
2415 return (a, out)
2418@array_function_dispatch(_cumsum_dispatcher)
2419def cumsum(a, axis=None, dtype=None, out=None):
2420 """
2421 Return the cumulative sum of the elements along a given axis.
2423 Parameters
2424 ----------
2425 a : array_like
2426 Input array.
2427 axis : int, optional
2428 Axis along which the cumulative sum is computed. The default
2429 (None) is to compute the cumsum over the flattened array.
2430 dtype : dtype, optional
2431 Type of the returned array and of the accumulator in which the
2432 elements are summed. If `dtype` is not specified, it defaults
2433 to the dtype of `a`, unless `a` has an integer dtype with a
2434 precision less than that of the default platform integer. In
2435 that case, the default platform integer is used.
2436 out : ndarray, optional
2437 Alternative output array in which to place the result. It must
2438 have the same shape and buffer length as the expected output
2439 but the type will be cast if necessary. See `ufuncs-output-type` for
2440 more details.
2442 Returns
2443 -------
2444 cumsum_along_axis : ndarray.
2445 A new array holding the result is returned unless `out` is
2446 specified, in which case a reference to `out` is returned. The
2447 result has the same size as `a`, and the same shape as `a` if
2448 `axis` is not None or `a` is a 1-d array.
2451 See Also
2452 --------
2453 sum : Sum array elements.
2455 trapz : Integration of array values using the composite trapezoidal rule.
2457 diff : Calculate the n-th discrete difference along given axis.
2459 Notes
2460 -----
2461 Arithmetic is modular when using integer types, and no error is
2462 raised on overflow.
2464 Examples
2465 --------
2466 >>> a = np.array([[1,2,3], [4,5,6]])
2467 >>> a
2468 array([[1, 2, 3],
2469 [4, 5, 6]])
2470 >>> np.cumsum(a)
2471 array([ 1, 3, 6, 10, 15, 21])
2472 >>> np.cumsum(a, dtype=float) # specifies type of output value(s)
2473 array([ 1., 3., 6., 10., 15., 21.])
2475 >>> np.cumsum(a,axis=0) # sum over rows for each of the 3 columns
2476 array([[1, 2, 3],
2477 [5, 7, 9]])
2478 >>> np.cumsum(a,axis=1) # sum over columns for each of the 2 rows
2479 array([[ 1, 3, 6],
2480 [ 4, 9, 15]])
2482 """
2483 return _wrapfunc(a, 'cumsum', axis=axis, dtype=dtype, out=out)
2486def _ptp_dispatcher(a, axis=None, out=None, keepdims=None):
2487 return (a, out)
2490@array_function_dispatch(_ptp_dispatcher)
2491def ptp(a, axis=None, out=None, keepdims=np._NoValue):
2492 """
2493 Range of values (maximum - minimum) along an axis.
2495 The name of the function comes from the acronym for 'peak to peak'.
2497 .. warning::
2498 `ptp` preserves the data type of the array. This means the
2499 return value for an input of signed integers with n bits
2500 (e.g. `np.int8`, `np.int16`, etc) is also a signed integer
2501 with n bits. In that case, peak-to-peak values greater than
2502 ``2**(n-1)-1`` will be returned as negative values. An example
2503 with a work-around is shown below.
2505 Parameters
2506 ----------
2507 a : array_like
2508 Input values.
2509 axis : None or int or tuple of ints, optional
2510 Axis along which to find the peaks. By default, flatten the
2511 array. `axis` may be negative, in
2512 which case it counts from the last to the first axis.
2514 .. versionadded:: 1.15.0
2516 If this is a tuple of ints, a reduction is performed on multiple
2517 axes, instead of a single axis or all the axes as before.
2518 out : array_like
2519 Alternative output array in which to place the result. It must
2520 have the same shape and buffer length as the expected output,
2521 but the type of the output values will be cast if necessary.
2523 keepdims : bool, optional
2524 If this is set to True, the axes which are reduced are left
2525 in the result as dimensions with size one. With this option,
2526 the result will broadcast correctly against the input array.
2528 If the default value is passed, then `keepdims` will not be
2529 passed through to the `ptp` method of sub-classes of
2530 `ndarray`, however any non-default value will be. If the
2531 sub-class' method does not implement `keepdims` any
2532 exceptions will be raised.
2534 Returns
2535 -------
2536 ptp : ndarray
2537 A new array holding the result, unless `out` was
2538 specified, in which case a reference to `out` is returned.
2540 Examples
2541 --------
2542 >>> x = np.array([[4, 9, 2, 10],
2543 ... [6, 9, 7, 12]])
2545 >>> np.ptp(x, axis=1)
2546 array([8, 6])
2548 >>> np.ptp(x, axis=0)
2549 array([2, 0, 5, 2])
2551 >>> np.ptp(x)
2552 10
2554 This example shows that a negative value can be returned when
2555 the input is an array of signed integers.
2557 >>> y = np.array([[1, 127],
2558 ... [0, 127],
2559 ... [-1, 127],
2560 ... [-2, 127]], dtype=np.int8)
2561 >>> np.ptp(y, axis=1)
2562 array([ 126, 127, -128, -127], dtype=int8)
2564 A work-around is to use the `view()` method to view the result as
2565 unsigned integers with the same bit width:
2567 >>> np.ptp(y, axis=1).view(np.uint8)
2568 array([126, 127, 128, 129], dtype=uint8)
2570 """
2571 kwargs = {}
2572 if keepdims is not np._NoValue:
2573 kwargs['keepdims'] = keepdims
2574 if type(a) is not mu.ndarray:
2575 try:
2576 ptp = a.ptp
2577 except AttributeError:
2578 pass
2579 else:
2580 return ptp(axis=axis, out=out, **kwargs)
2581 return _methods._ptp(a, axis=axis, out=out, **kwargs)
2584def _amax_dispatcher(a, axis=None, out=None, keepdims=None, initial=None,
2585 where=None):
2586 return (a, out)
2589@array_function_dispatch(_amax_dispatcher)
2590def amax(a, axis=None, out=None, keepdims=np._NoValue, initial=np._NoValue,
2591 where=np._NoValue):
2592 """
2593 Return the maximum of an array or maximum along an axis.
2595 Parameters
2596 ----------
2597 a : array_like
2598 Input data.
2599 axis : None or int or tuple of ints, optional
2600 Axis or axes along which to operate. By default, flattened input is
2601 used.
2603 .. versionadded:: 1.7.0
2605 If this is a tuple of ints, the maximum is selected over multiple axes,
2606 instead of a single axis or all the axes as before.
2607 out : ndarray, optional
2608 Alternative output array in which to place the result. Must
2609 be of the same shape and buffer length as the expected output.
2610 See `ufuncs-output-type` for more details.
2612 keepdims : bool, optional
2613 If this is set to True, the axes which are reduced are left
2614 in the result as dimensions with size one. With this option,
2615 the result will broadcast correctly against the input array.
2617 If the default value is passed, then `keepdims` will not be
2618 passed through to the `amax` method of sub-classes of
2619 `ndarray`, however any non-default value will be. If the
2620 sub-class' method does not implement `keepdims` any
2621 exceptions will be raised.
2623 initial : scalar, optional
2624 The minimum value of an output element. Must be present to allow
2625 computation on empty slice. See `~numpy.ufunc.reduce` for details.
2627 .. versionadded:: 1.15.0
2629 where : array_like of bool, optional
2630 Elements to compare for the maximum. See `~numpy.ufunc.reduce`
2631 for details.
2633 .. versionadded:: 1.17.0
2635 Returns
2636 -------
2637 amax : ndarray or scalar
2638 Maximum of `a`. If `axis` is None, the result is a scalar value.
2639 If `axis` is given, the result is an array of dimension
2640 ``a.ndim - 1``.
2642 See Also
2643 --------
2644 amin :
2645 The minimum value of an array along a given axis, propagating any NaNs.
2646 nanmax :
2647 The maximum value of an array along a given axis, ignoring any NaNs.
2648 maximum :
2649 Element-wise maximum of two arrays, propagating any NaNs.
2650 fmax :
2651 Element-wise maximum of two arrays, ignoring any NaNs.
2652 argmax :
2653 Return the indices of the maximum values.
2655 nanmin, minimum, fmin
2657 Notes
2658 -----
2659 NaN values are propagated, that is if at least one item is NaN, the
2660 corresponding max value will be NaN as well. To ignore NaN values
2661 (MATLAB behavior), please use nanmax.
2663 Don't use `amax` for element-wise comparison of 2 arrays; when
2664 ``a.shape[0]`` is 2, ``maximum(a[0], a[1])`` is faster than
2665 ``amax(a, axis=0)``.
2667 Examples
2668 --------
2669 >>> a = np.arange(4).reshape((2,2))
2670 >>> a
2671 array([[0, 1],
2672 [2, 3]])
2673 >>> np.amax(a) # Maximum of the flattened array
2674 3
2675 >>> np.amax(a, axis=0) # Maxima along the first axis
2676 array([2, 3])
2677 >>> np.amax(a, axis=1) # Maxima along the second axis
2678 array([1, 3])
2679 >>> np.amax(a, where=[False, True], initial=-1, axis=0)
2680 array([-1, 3])
2681 >>> b = np.arange(5, dtype=float)
2682 >>> b[2] = np.NaN
2683 >>> np.amax(b)
2684 nan
2685 >>> np.amax(b, where=~np.isnan(b), initial=-1)
2686 4.0
2687 >>> np.nanmax(b)
2688 4.0
2690 You can use an initial value to compute the maximum of an empty slice, or
2691 to initialize it to a different value:
2693 >>> np.max([[-50], [10]], axis=-1, initial=0)
2694 array([ 0, 10])
2696 Notice that the initial value is used as one of the elements for which the
2697 maximum is determined, unlike for the default argument Python's max
2698 function, which is only used for empty iterables.
2700 >>> np.max([5], initial=6)
2701 6
2702 >>> max([5], default=6)
2703 5
2704 """
2705 return _wrapreduction(a, np.maximum, 'max', axis, None, out,
2706 keepdims=keepdims, initial=initial, where=where)
2709def _amin_dispatcher(a, axis=None, out=None, keepdims=None, initial=None,
2710 where=None):
2711 return (a, out)
2714@array_function_dispatch(_amin_dispatcher)
2715def amin(a, axis=None, out=None, keepdims=np._NoValue, initial=np._NoValue,
2716 where=np._NoValue):
2717 """
2718 Return the minimum of an array or minimum along an axis.
2720 Parameters
2721 ----------
2722 a : array_like
2723 Input data.
2724 axis : None or int or tuple of ints, optional
2725 Axis or axes along which to operate. By default, flattened input is
2726 used.
2728 .. versionadded:: 1.7.0
2730 If this is a tuple of ints, the minimum is selected over multiple axes,
2731 instead of a single axis or all the axes as before.
2732 out : ndarray, optional
2733 Alternative output array in which to place the result. Must
2734 be of the same shape and buffer length as the expected output.
2735 See `ufuncs-output-type` for more details.
2737 keepdims : bool, optional
2738 If this is set to True, the axes which are reduced are left
2739 in the result as dimensions with size one. With this option,
2740 the result will broadcast correctly against the input array.
2742 If the default value is passed, then `keepdims` will not be
2743 passed through to the `amin` method of sub-classes of
2744 `ndarray`, however any non-default value will be. If the
2745 sub-class' method does not implement `keepdims` any
2746 exceptions will be raised.
2748 initial : scalar, optional
2749 The maximum value of an output element. Must be present to allow
2750 computation on empty slice. See `~numpy.ufunc.reduce` for details.
2752 .. versionadded:: 1.15.0
2754 where : array_like of bool, optional
2755 Elements to compare for the minimum. See `~numpy.ufunc.reduce`
2756 for details.
2758 .. versionadded:: 1.17.0
2760 Returns
2761 -------
2762 amin : ndarray or scalar
2763 Minimum of `a`. If `axis` is None, the result is a scalar value.
2764 If `axis` is given, the result is an array of dimension
2765 ``a.ndim - 1``.
2767 See Also
2768 --------
2769 amax :
2770 The maximum value of an array along a given axis, propagating any NaNs.
2771 nanmin :
2772 The minimum value of an array along a given axis, ignoring any NaNs.
2773 minimum :
2774 Element-wise minimum of two arrays, propagating any NaNs.
2775 fmin :
2776 Element-wise minimum of two arrays, ignoring any NaNs.
2777 argmin :
2778 Return the indices of the minimum values.
2780 nanmax, maximum, fmax
2782 Notes
2783 -----
2784 NaN values are propagated, that is if at least one item is NaN, the
2785 corresponding min value will be NaN as well. To ignore NaN values
2786 (MATLAB behavior), please use nanmin.
2788 Don't use `amin` for element-wise comparison of 2 arrays; when
2789 ``a.shape[0]`` is 2, ``minimum(a[0], a[1])`` is faster than
2790 ``amin(a, axis=0)``.
2792 Examples
2793 --------
2794 >>> a = np.arange(4).reshape((2,2))
2795 >>> a
2796 array([[0, 1],
2797 [2, 3]])
2798 >>> np.amin(a) # Minimum of the flattened array
2799 0
2800 >>> np.amin(a, axis=0) # Minima along the first axis
2801 array([0, 1])
2802 >>> np.amin(a, axis=1) # Minima along the second axis
2803 array([0, 2])
2804 >>> np.amin(a, where=[False, True], initial=10, axis=0)
2805 array([10, 1])
2807 >>> b = np.arange(5, dtype=float)
2808 >>> b[2] = np.NaN
2809 >>> np.amin(b)
2810 nan
2811 >>> np.amin(b, where=~np.isnan(b), initial=10)
2812 0.0
2813 >>> np.nanmin(b)
2814 0.0
2816 >>> np.min([[-50], [10]], axis=-1, initial=0)
2817 array([-50, 0])
2819 Notice that the initial value is used as one of the elements for which the
2820 minimum is determined, unlike for the default argument Python's max
2821 function, which is only used for empty iterables.
2823 Notice that this isn't the same as Python's ``default`` argument.
2825 >>> np.min([6], initial=5)
2826 5
2827 >>> min([6], default=5)
2828 6
2829 """
2830 return _wrapreduction(a, np.minimum, 'min', axis, None, out,
2831 keepdims=keepdims, initial=initial, where=where)
2834def _alen_dispathcer(a):
2835 return (a,)
2838@array_function_dispatch(_alen_dispathcer)
2839def alen(a):
2840 """
2841 Return the length of the first dimension of the input array.
2843 Parameters
2844 ----------
2845 a : array_like
2846 Input array.
2848 Returns
2849 -------
2850 alen : int
2851 Length of the first dimension of `a`.
2853 See Also
2854 --------
2855 shape, size
2857 Examples
2858 --------
2859 >>> a = np.zeros((7,4,5))
2860 >>> a.shape[0]
2861 7
2862 >>> np.alen(a)
2863 7
2865 """
2866 # NumPy 1.18.0, 2019-08-02
2867 warnings.warn(
2868 "`np.alen` is deprecated, use `len` instead",
2869 DeprecationWarning, stacklevel=2)
2870 try:
2871 return len(a)
2872 except TypeError:
2873 return len(array(a, ndmin=1))
2876def _prod_dispatcher(a, axis=None, dtype=None, out=None, keepdims=None,
2877 initial=None, where=None):
2878 return (a, out)
2881@array_function_dispatch(_prod_dispatcher)
2882def prod(a, axis=None, dtype=None, out=None, keepdims=np._NoValue,
2883 initial=np._NoValue, where=np._NoValue):
2884 """
2885 Return the product of array elements over a given axis.
2887 Parameters
2888 ----------
2889 a : array_like
2890 Input data.
2891 axis : None or int or tuple of ints, optional
2892 Axis or axes along which a product is performed. The default,
2893 axis=None, will calculate the product of all the elements in the
2894 input array. If axis is negative it counts from the last to the
2895 first axis.
2897 .. versionadded:: 1.7.0
2899 If axis is a tuple of ints, a product is performed on all of the
2900 axes specified in the tuple instead of a single axis or all the
2901 axes as before.
2902 dtype : dtype, optional
2903 The type of the returned array, as well as of the accumulator in
2904 which the elements are multiplied. The dtype of `a` is used by
2905 default unless `a` has an integer dtype of less precision than the
2906 default platform integer. In that case, if `a` is signed then the
2907 platform integer is used while if `a` is unsigned then an unsigned
2908 integer of the same precision as the platform integer is used.
2909 out : ndarray, optional
2910 Alternative output array in which to place the result. It must have
2911 the same shape as the expected output, but the type of the output
2912 values will be cast if necessary.
2913 keepdims : bool, optional
2914 If this is set to True, the axes which are reduced are left in the
2915 result as dimensions with size one. With this option, the result
2916 will broadcast correctly against the input array.
2918 If the default value is passed, then `keepdims` will not be
2919 passed through to the `prod` method of sub-classes of
2920 `ndarray`, however any non-default value will be. If the
2921 sub-class' method does not implement `keepdims` any
2922 exceptions will be raised.
2923 initial : scalar, optional
2924 The starting value for this product. See `~numpy.ufunc.reduce` for details.
2926 .. versionadded:: 1.15.0
2928 where : array_like of bool, optional
2929 Elements to include in the product. See `~numpy.ufunc.reduce` for details.
2931 .. versionadded:: 1.17.0
2933 Returns
2934 -------
2935 product_along_axis : ndarray, see `dtype` parameter above.
2936 An array shaped as `a` but with the specified axis removed.
2937 Returns a reference to `out` if specified.
2939 See Also
2940 --------
2941 ndarray.prod : equivalent method
2942 ufuncs-output-type
2944 Notes
2945 -----
2946 Arithmetic is modular when using integer types, and no error is
2947 raised on overflow. That means that, on a 32-bit platform:
2949 >>> x = np.array([536870910, 536870910, 536870910, 536870910])
2950 >>> np.prod(x)
2951 16 # may vary
2953 The product of an empty array is the neutral element 1:
2955 >>> np.prod([])
2956 1.0
2958 Examples
2959 --------
2960 By default, calculate the product of all elements:
2962 >>> np.prod([1.,2.])
2963 2.0
2965 Even when the input array is two-dimensional:
2967 >>> np.prod([[1.,2.],[3.,4.]])
2968 24.0
2970 But we can also specify the axis over which to multiply:
2972 >>> np.prod([[1.,2.],[3.,4.]], axis=1)
2973 array([ 2., 12.])
2975 Or select specific elements to include:
2977 >>> np.prod([1., np.nan, 3.], where=[True, False, True])
2978 3.0
2980 If the type of `x` is unsigned, then the output type is
2981 the unsigned platform integer:
2983 >>> x = np.array([1, 2, 3], dtype=np.uint8)
2984 >>> np.prod(x).dtype == np.uint
2985 True
2987 If `x` is of a signed integer type, then the output type
2988 is the default platform integer:
2990 >>> x = np.array([1, 2, 3], dtype=np.int8)
2991 >>> np.prod(x).dtype == int
2992 True
2994 You can also start the product with a value other than one:
2996 >>> np.prod([1, 2], initial=5)
2997 10
2998 """
2999 return _wrapreduction(a, np.multiply, 'prod', axis, dtype, out,
3000 keepdims=keepdims, initial=initial, where=where)
3003def _cumprod_dispatcher(a, axis=None, dtype=None, out=None):
3004 return (a, out)
3007@array_function_dispatch(_cumprod_dispatcher)
3008def cumprod(a, axis=None, dtype=None, out=None):
3009 """
3010 Return the cumulative product of elements along a given axis.
3012 Parameters
3013 ----------
3014 a : array_like
3015 Input array.
3016 axis : int, optional
3017 Axis along which the cumulative product is computed. By default
3018 the input is flattened.
3019 dtype : dtype, optional
3020 Type of the returned array, as well as of the accumulator in which
3021 the elements are multiplied. If *dtype* is not specified, it
3022 defaults to the dtype of `a`, unless `a` has an integer dtype with
3023 a precision less than that of the default platform integer. In
3024 that case, the default platform integer is used instead.
3025 out : ndarray, optional
3026 Alternative output array in which to place the result. It must
3027 have the same shape and buffer length as the expected output
3028 but the type of the resulting values will be cast if necessary.
3030 Returns
3031 -------
3032 cumprod : ndarray
3033 A new array holding the result is returned unless `out` is
3034 specified, in which case a reference to out is returned.
3036 See Also
3037 --------
3038 ufuncs-output-type
3040 Notes
3041 -----
3042 Arithmetic is modular when using integer types, and no error is
3043 raised on overflow.
3045 Examples
3046 --------
3047 >>> a = np.array([1,2,3])
3048 >>> np.cumprod(a) # intermediate results 1, 1*2
3049 ... # total product 1*2*3 = 6
3050 array([1, 2, 6])
3051 >>> a = np.array([[1, 2, 3], [4, 5, 6]])
3052 >>> np.cumprod(a, dtype=float) # specify type of output
3053 array([ 1., 2., 6., 24., 120., 720.])
3055 The cumulative product for each column (i.e., over the rows) of `a`:
3057 >>> np.cumprod(a, axis=0)
3058 array([[ 1, 2, 3],
3059 [ 4, 10, 18]])
3061 The cumulative product for each row (i.e. over the columns) of `a`:
3063 >>> np.cumprod(a,axis=1)
3064 array([[ 1, 2, 6],
3065 [ 4, 20, 120]])
3067 """
3068 return _wrapfunc(a, 'cumprod', axis=axis, dtype=dtype, out=out)
3071def _ndim_dispatcher(a):
3072 return (a,)
3075@array_function_dispatch(_ndim_dispatcher)
3076def ndim(a):
3077 """
3078 Return the number of dimensions of an array.
3080 Parameters
3081 ----------
3082 a : array_like
3083 Input array. If it is not already an ndarray, a conversion is
3084 attempted.
3086 Returns
3087 -------
3088 number_of_dimensions : int
3089 The number of dimensions in `a`. Scalars are zero-dimensional.
3091 See Also
3092 --------
3093 ndarray.ndim : equivalent method
3094 shape : dimensions of array
3095 ndarray.shape : dimensions of array
3097 Examples
3098 --------
3099 >>> np.ndim([[1,2,3],[4,5,6]])
3100 2
3101 >>> np.ndim(np.array([[1,2,3],[4,5,6]]))
3102 2
3103 >>> np.ndim(1)
3104 0
3106 """
3107 try:
3108 return a.ndim
3109 except AttributeError:
3110 return asarray(a).ndim
3113def _size_dispatcher(a, axis=None):
3114 return (a,)
3117@array_function_dispatch(_size_dispatcher)
3118def size(a, axis=None):
3119 """
3120 Return the number of elements along a given axis.
3122 Parameters
3123 ----------
3124 a : array_like
3125 Input data.
3126 axis : int, optional
3127 Axis along which the elements are counted. By default, give
3128 the total number of elements.
3130 Returns
3131 -------
3132 element_count : int
3133 Number of elements along the specified axis.
3135 See Also
3136 --------
3137 shape : dimensions of array
3138 ndarray.shape : dimensions of array
3139 ndarray.size : number of elements in array
3141 Examples
3142 --------
3143 >>> a = np.array([[1,2,3],[4,5,6]])
3144 >>> np.size(a)
3145 6
3146 >>> np.size(a,1)
3147 3
3148 >>> np.size(a,0)
3149 2
3151 """
3152 if axis is None:
3153 try:
3154 return a.size
3155 except AttributeError:
3156 return asarray(a).size
3157 else:
3158 try:
3159 return a.shape[axis]
3160 except AttributeError:
3161 return asarray(a).shape[axis]
3164def _around_dispatcher(a, decimals=None, out=None):
3165 return (a, out)
3168@array_function_dispatch(_around_dispatcher)
3169def around(a, decimals=0, out=None):
3170 """
3171 Evenly round to the given number of decimals.
3173 Parameters
3174 ----------
3175 a : array_like
3176 Input data.
3177 decimals : int, optional
3178 Number of decimal places to round to (default: 0). If
3179 decimals is negative, it specifies the number of positions to
3180 the left of the decimal point.
3181 out : ndarray, optional
3182 Alternative output array in which to place the result. It must have
3183 the same shape as the expected output, but the type of the output
3184 values will be cast if necessary. See `ufuncs-output-type` for more
3185 details.
3187 Returns
3188 -------
3189 rounded_array : ndarray
3190 An array of the same type as `a`, containing the rounded values.
3191 Unless `out` was specified, a new array is created. A reference to
3192 the result is returned.
3194 The real and imaginary parts of complex numbers are rounded
3195 separately. The result of rounding a float is a float.
3197 See Also
3198 --------
3199 ndarray.round : equivalent method
3201 ceil, fix, floor, rint, trunc
3204 Notes
3205 -----
3206 For values exactly halfway between rounded decimal values, NumPy
3207 rounds to the nearest even value. Thus 1.5 and 2.5 round to 2.0,
3208 -0.5 and 0.5 round to 0.0, etc.
3210 ``np.around`` uses a fast but sometimes inexact algorithm to round
3211 floating-point datatypes. For positive `decimals` it is equivalent to
3212 ``np.true_divide(np.rint(a * 10**decimals), 10**decimals)``, which has
3213 error due to the inexact representation of decimal fractions in the IEEE
3214 floating point standard [1]_ and errors introduced when scaling by powers
3215 of ten. For instance, note the extra "1" in the following:
3217 >>> np.round(56294995342131.5, 3)
3218 56294995342131.51
3220 If your goal is to print such values with a fixed number of decimals, it is
3221 preferable to use numpy's float printing routines to limit the number of
3222 printed decimals:
3224 >>> np.format_float_positional(56294995342131.5, precision=3)
3225 '56294995342131.5'
3227 The float printing routines use an accurate but much more computationally
3228 demanding algorithm to compute the number of digits after the decimal
3229 point.
3231 Alternatively, Python's builtin `round` function uses a more accurate
3232 but slower algorithm for 64-bit floating point values:
3234 >>> round(56294995342131.5, 3)
3235 56294995342131.5
3236 >>> np.round(16.055, 2), round(16.055, 2) # equals 16.0549999999999997
3237 (16.06, 16.05)
3240 References
3241 ----------
3242 .. [1] "Lecture Notes on the Status of IEEE 754", William Kahan,
3243 https://people.eecs.berkeley.edu/~wkahan/ieee754status/IEEE754.PDF
3244 .. [2] "How Futile are Mindless Assessments of
3245 Roundoff in Floating-Point Computation?", William Kahan,
3246 https://people.eecs.berkeley.edu/~wkahan/Mindless.pdf
3248 Examples
3249 --------
3250 >>> np.around([0.37, 1.64])
3251 array([0., 2.])
3252 >>> np.around([0.37, 1.64], decimals=1)
3253 array([0.4, 1.6])
3254 >>> np.around([.5, 1.5, 2.5, 3.5, 4.5]) # rounds to nearest even value
3255 array([0., 2., 2., 4., 4.])
3256 >>> np.around([1,2,3,11], decimals=1) # ndarray of ints is returned
3257 array([ 1, 2, 3, 11])
3258 >>> np.around([1,2,3,11], decimals=-1)
3259 array([ 0, 0, 0, 10])
3261 """
3262 return _wrapfunc(a, 'round', decimals=decimals, out=out)
3265def _mean_dispatcher(a, axis=None, dtype=None, out=None, keepdims=None):
3266 return (a, out)
3269@array_function_dispatch(_mean_dispatcher)
3270def mean(a, axis=None, dtype=None, out=None, keepdims=np._NoValue):
3271 """
3272 Compute the arithmetic mean along the specified axis.
3274 Returns the average of the array elements. The average is taken over
3275 the flattened array by default, otherwise over the specified axis.
3276 `float64` intermediate and return values are used for integer inputs.
3278 Parameters
3279 ----------
3280 a : array_like
3281 Array containing numbers whose mean is desired. If `a` is not an
3282 array, a conversion is attempted.
3283 axis : None or int or tuple of ints, optional
3284 Axis or axes along which the means are computed. The default is to
3285 compute the mean of the flattened array.
3287 .. versionadded:: 1.7.0
3289 If this is a tuple of ints, a mean is performed over multiple axes,
3290 instead of a single axis or all the axes as before.
3291 dtype : data-type, optional
3292 Type to use in computing the mean. For integer inputs, the default
3293 is `float64`; for floating point inputs, it is the same as the
3294 input dtype.
3295 out : ndarray, optional
3296 Alternate output array in which to place the result. The default
3297 is ``None``; if provided, it must have the same shape as the
3298 expected output, but the type will be cast if necessary.
3299 See `ufuncs-output-type` for more details.
3301 keepdims : bool, optional
3302 If this is set to True, the axes which are reduced are left
3303 in the result as dimensions with size one. With this option,
3304 the result will broadcast correctly against the input array.
3306 If the default value is passed, then `keepdims` will not be
3307 passed through to the `mean` method of sub-classes of
3308 `ndarray`, however any non-default value will be. If the
3309 sub-class' method does not implement `keepdims` any
3310 exceptions will be raised.
3312 Returns
3313 -------
3314 m : ndarray, see dtype parameter above
3315 If `out=None`, returns a new array containing the mean values,
3316 otherwise a reference to the output array is returned.
3318 See Also
3319 --------
3320 average : Weighted average
3321 std, var, nanmean, nanstd, nanvar
3323 Notes
3324 -----
3325 The arithmetic mean is the sum of the elements along the axis divided
3326 by the number of elements.
3328 Note that for floating-point input, the mean is computed using the
3329 same precision the input has. Depending on the input data, this can
3330 cause the results to be inaccurate, especially for `float32` (see
3331 example below). Specifying a higher-precision accumulator using the
3332 `dtype` keyword can alleviate this issue.
3334 By default, `float16` results are computed using `float32` intermediates
3335 for extra precision.
3337 Examples
3338 --------
3339 >>> a = np.array([[1, 2], [3, 4]])
3340 >>> np.mean(a)
3341 2.5
3342 >>> np.mean(a, axis=0)
3343 array([2., 3.])
3344 >>> np.mean(a, axis=1)
3345 array([1.5, 3.5])
3347 In single precision, `mean` can be inaccurate:
3349 >>> a = np.zeros((2, 512*512), dtype=np.float32)
3350 >>> a[0, :] = 1.0
3351 >>> a[1, :] = 0.1
3352 >>> np.mean(a)
3353 0.54999924
3355 Computing the mean in float64 is more accurate:
3357 >>> np.mean(a, dtype=np.float64)
3358 0.55000000074505806 # may vary
3360 """
3361 kwargs = {}
3362 if keepdims is not np._NoValue:
3363 kwargs['keepdims'] = keepdims
3364 if type(a) is not mu.ndarray:
3365 try:
3366 mean = a.mean
3367 except AttributeError:
3368 pass
3369 else:
3370 return mean(axis=axis, dtype=dtype, out=out, **kwargs)
3372 return _methods._mean(a, axis=axis, dtype=dtype,
3373 out=out, **kwargs)
3376def _std_dispatcher(
3377 a, axis=None, dtype=None, out=None, ddof=None, keepdims=None):
3378 return (a, out)
3381@array_function_dispatch(_std_dispatcher)
3382def std(a, axis=None, dtype=None, out=None, ddof=0, keepdims=np._NoValue):
3383 """
3384 Compute the standard deviation along the specified axis.
3386 Returns the standard deviation, a measure of the spread of a distribution,
3387 of the array elements. The standard deviation is computed for the
3388 flattened array by default, otherwise over the specified axis.
3390 Parameters
3391 ----------
3392 a : array_like
3393 Calculate the standard deviation of these values.
3394 axis : None or int or tuple of ints, optional
3395 Axis or axes along which the standard deviation is computed. The
3396 default is to compute the standard deviation of the flattened array.
3398 .. versionadded:: 1.7.0
3400 If this is a tuple of ints, a standard deviation is performed over
3401 multiple axes, instead of a single axis or all the axes as before.
3402 dtype : dtype, optional
3403 Type to use in computing the standard deviation. For arrays of
3404 integer type the default is float64, for arrays of float types it is
3405 the same as the array type.
3406 out : ndarray, optional
3407 Alternative output array in which to place the result. It must have
3408 the same shape as the expected output but the type (of the calculated
3409 values) will be cast if necessary.
3410 ddof : int, optional
3411 Means Delta Degrees of Freedom. The divisor used in calculations
3412 is ``N - ddof``, where ``N`` represents the number of elements.
3413 By default `ddof` is zero.
3414 keepdims : bool, optional
3415 If this is set to True, the axes which are reduced are left
3416 in the result as dimensions with size one. With this option,
3417 the result will broadcast correctly against the input array.
3419 If the default value is passed, then `keepdims` will not be
3420 passed through to the `std` method of sub-classes of
3421 `ndarray`, however any non-default value will be. If the
3422 sub-class' method does not implement `keepdims` any
3423 exceptions will be raised.
3425 Returns
3426 -------
3427 standard_deviation : ndarray, see dtype parameter above.
3428 If `out` is None, return a new array containing the standard deviation,
3429 otherwise return a reference to the output array.
3431 See Also
3432 --------
3433 var, mean, nanmean, nanstd, nanvar
3434 ufuncs-output-type
3436 Notes
3437 -----
3438 The standard deviation is the square root of the average of the squared
3439 deviations from the mean, i.e., ``std = sqrt(mean(abs(x - x.mean())**2))``.
3441 The average squared deviation is normally calculated as
3442 ``x.sum() / N``, where ``N = len(x)``. If, however, `ddof` is specified,
3443 the divisor ``N - ddof`` is used instead. In standard statistical
3444 practice, ``ddof=1`` provides an unbiased estimator of the variance
3445 of the infinite population. ``ddof=0`` provides a maximum likelihood
3446 estimate of the variance for normally distributed variables. The
3447 standard deviation computed in this function is the square root of
3448 the estimated variance, so even with ``ddof=1``, it will not be an
3449 unbiased estimate of the standard deviation per se.
3451 Note that, for complex numbers, `std` takes the absolute
3452 value before squaring, so that the result is always real and nonnegative.
3454 For floating-point input, the *std* is computed using the same
3455 precision the input has. Depending on the input data, this can cause
3456 the results to be inaccurate, especially for float32 (see example below).
3457 Specifying a higher-accuracy accumulator using the `dtype` keyword can
3458 alleviate this issue.
3460 Examples
3461 --------
3462 >>> a = np.array([[1, 2], [3, 4]])
3463 >>> np.std(a)
3464 1.1180339887498949 # may vary
3465 >>> np.std(a, axis=0)
3466 array([1., 1.])
3467 >>> np.std(a, axis=1)
3468 array([0.5, 0.5])
3470 In single precision, std() can be inaccurate:
3472 >>> a = np.zeros((2, 512*512), dtype=np.float32)
3473 >>> a[0, :] = 1.0
3474 >>> a[1, :] = 0.1
3475 >>> np.std(a)
3476 0.45000005
3478 Computing the standard deviation in float64 is more accurate:
3480 >>> np.std(a, dtype=np.float64)
3481 0.44999999925494177 # may vary
3483 """
3484 kwargs = {}
3485 if keepdims is not np._NoValue:
3486 kwargs['keepdims'] = keepdims
3488 if type(a) is not mu.ndarray:
3489 try:
3490 std = a.std
3491 except AttributeError:
3492 pass
3493 else:
3494 return std(axis=axis, dtype=dtype, out=out, ddof=ddof, **kwargs)
3496 return _methods._std(a, axis=axis, dtype=dtype, out=out, ddof=ddof,
3497 **kwargs)
3500def _var_dispatcher(
3501 a, axis=None, dtype=None, out=None, ddof=None, keepdims=None):
3502 return (a, out)
3505@array_function_dispatch(_var_dispatcher)
3506def var(a, axis=None, dtype=None, out=None, ddof=0, keepdims=np._NoValue):
3507 """
3508 Compute the variance along the specified axis.
3510 Returns the variance of the array elements, a measure of the spread of a
3511 distribution. The variance is computed for the flattened array by
3512 default, otherwise over the specified axis.
3514 Parameters
3515 ----------
3516 a : array_like
3517 Array containing numbers whose variance is desired. If `a` is not an
3518 array, a conversion is attempted.
3519 axis : None or int or tuple of ints, optional
3520 Axis or axes along which the variance is computed. The default is to
3521 compute the variance of the flattened array.
3523 .. versionadded:: 1.7.0
3525 If this is a tuple of ints, a variance is performed over multiple axes,
3526 instead of a single axis or all the axes as before.
3527 dtype : data-type, optional
3528 Type to use in computing the variance. For arrays of integer type
3529 the default is `float64`; for arrays of float types it is the same as
3530 the array type.
3531 out : ndarray, optional
3532 Alternate output array in which to place the result. It must have
3533 the same shape as the expected output, but the type is cast if
3534 necessary.
3535 ddof : int, optional
3536 "Delta Degrees of Freedom": the divisor used in the calculation is
3537 ``N - ddof``, where ``N`` represents the number of elements. By
3538 default `ddof` is zero.
3539 keepdims : bool, optional
3540 If this is set to True, the axes which are reduced are left
3541 in the result as dimensions with size one. With this option,
3542 the result will broadcast correctly against the input array.
3544 If the default value is passed, then `keepdims` will not be
3545 passed through to the `var` method of sub-classes of
3546 `ndarray`, however any non-default value will be. If the
3547 sub-class' method does not implement `keepdims` any
3548 exceptions will be raised.
3550 Returns
3551 -------
3552 variance : ndarray, see dtype parameter above
3553 If ``out=None``, returns a new array containing the variance;
3554 otherwise, a reference to the output array is returned.
3556 See Also
3557 --------
3558 std, mean, nanmean, nanstd, nanvar
3559 ufuncs-output-type
3561 Notes
3562 -----
3563 The variance is the average of the squared deviations from the mean,
3564 i.e., ``var = mean(abs(x - x.mean())**2)``.
3566 The mean is normally calculated as ``x.sum() / N``, where ``N = len(x)``.
3567 If, however, `ddof` is specified, the divisor ``N - ddof`` is used
3568 instead. In standard statistical practice, ``ddof=1`` provides an
3569 unbiased estimator of the variance of a hypothetical infinite population.
3570 ``ddof=0`` provides a maximum likelihood estimate of the variance for
3571 normally distributed variables.
3573 Note that for complex numbers, the absolute value is taken before
3574 squaring, so that the result is always real and nonnegative.
3576 For floating-point input, the variance is computed using the same
3577 precision the input has. Depending on the input data, this can cause
3578 the results to be inaccurate, especially for `float32` (see example
3579 below). Specifying a higher-accuracy accumulator using the ``dtype``
3580 keyword can alleviate this issue.
3582 Examples
3583 --------
3584 >>> a = np.array([[1, 2], [3, 4]])
3585 >>> np.var(a)
3586 1.25
3587 >>> np.var(a, axis=0)
3588 array([1., 1.])
3589 >>> np.var(a, axis=1)
3590 array([0.25, 0.25])
3592 In single precision, var() can be inaccurate:
3594 >>> a = np.zeros((2, 512*512), dtype=np.float32)
3595 >>> a[0, :] = 1.0
3596 >>> a[1, :] = 0.1
3597 >>> np.var(a)
3598 0.20250003
3600 Computing the variance in float64 is more accurate:
3602 >>> np.var(a, dtype=np.float64)
3603 0.20249999932944759 # may vary
3604 >>> ((1-0.55)**2 + (0.1-0.55)**2)/2
3605 0.2025
3607 """
3608 kwargs = {}
3609 if keepdims is not np._NoValue:
3610 kwargs['keepdims'] = keepdims
3612 if type(a) is not mu.ndarray:
3613 try:
3614 var = a.var
3616 except AttributeError:
3617 pass
3618 else:
3619 return var(axis=axis, dtype=dtype, out=out, ddof=ddof, **kwargs)
3621 return _methods._var(a, axis=axis, dtype=dtype, out=out, ddof=ddof,
3622 **kwargs)
3625# Aliases of other functions. These have their own definitions only so that
3626# they can have unique docstrings.
3628@array_function_dispatch(_around_dispatcher)
3629def round_(a, decimals=0, out=None):
3630 """
3631 Round an array to the given number of decimals.
3633 See Also
3634 --------
3635 around : equivalent function; see for details.
3636 """
3637 return around(a, decimals=decimals, out=out)
3640@array_function_dispatch(_prod_dispatcher, verify=False)
3641def product(*args, **kwargs):
3642 """
3643 Return the product of array elements over a given axis.
3645 See Also
3646 --------
3647 prod : equivalent function; see for details.
3648 """
3649 return prod(*args, **kwargs)
3652@array_function_dispatch(_cumprod_dispatcher, verify=False)
3653def cumproduct(*args, **kwargs):
3654 """
3655 Return the cumulative product over the given axis.
3657 See Also
3658 --------
3659 cumprod : equivalent function; see for details.
3660 """
3661 return cumprod(*args, **kwargs)
3664@array_function_dispatch(_any_dispatcher, verify=False)
3665def sometrue(*args, **kwargs):
3666 """
3667 Check whether some values are true.
3669 Refer to `any` for full documentation.
3671 See Also
3672 --------
3673 any : equivalent function; see for details.
3674 """
3675 return any(*args, **kwargs)
3678@array_function_dispatch(_all_dispatcher, verify=False)
3679def alltrue(*args, **kwargs):
3680 """
3681 Check if all elements of input array are true.
3683 See Also
3684 --------
3685 numpy.all : Equivalent function; see for details.
3686 """
3687 return all(*args, **kwargs)