m2m模型翻译
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

3789 lines
120 KiB

6 months ago
  1. """Module containing non-deprecated functions borrowed from Numeric.
  2. """
  3. import functools
  4. import types
  5. import warnings
  6. import numpy as np
  7. from . import multiarray as mu
  8. from . import overrides
  9. from . import umath as um
  10. from . import numerictypes as nt
  11. from .multiarray import asarray, array, asanyarray, concatenate
  12. from . import _methods
  13. _dt_ = nt.sctype2char
  14. # functions that are methods
  15. __all__ = [
  16. 'alen', 'all', 'alltrue', 'amax', 'amin', 'any', 'argmax',
  17. 'argmin', 'argpartition', 'argsort', 'around', 'choose', 'clip',
  18. 'compress', 'cumprod', 'cumproduct', 'cumsum', 'diagonal', 'mean',
  19. 'ndim', 'nonzero', 'partition', 'prod', 'product', 'ptp', 'put',
  20. 'ravel', 'repeat', 'reshape', 'resize', 'round_',
  21. 'searchsorted', 'shape', 'size', 'sometrue', 'sort', 'squeeze',
  22. 'std', 'sum', 'swapaxes', 'take', 'trace', 'transpose', 'var',
  23. ]
  24. _gentype = types.GeneratorType
  25. # save away Python sum
  26. _sum_ = sum
  27. array_function_dispatch = functools.partial(
  28. overrides.array_function_dispatch, module='numpy')
  29. # functions that are now methods
  30. def _wrapit(obj, method, *args, **kwds):
  31. try:
  32. wrap = obj.__array_wrap__
  33. except AttributeError:
  34. wrap = None
  35. result = getattr(asarray(obj), method)(*args, **kwds)
  36. if wrap:
  37. if not isinstance(result, mu.ndarray):
  38. result = asarray(result)
  39. result = wrap(result)
  40. return result
  41. def _wrapfunc(obj, method, *args, **kwds):
  42. bound = getattr(obj, method, None)
  43. if bound is None:
  44. return _wrapit(obj, method, *args, **kwds)
  45. try:
  46. return bound(*args, **kwds)
  47. except TypeError:
  48. # A TypeError occurs if the object does have such a method in its
  49. # class, but its signature is not identical to that of NumPy's. This
  50. # situation has occurred in the case of a downstream library like
  51. # 'pandas'.
  52. #
  53. # Call _wrapit from within the except clause to ensure a potential
  54. # exception has a traceback chain.
  55. return _wrapit(obj, method, *args, **kwds)
  56. def _wrapreduction(obj, ufunc, method, axis, dtype, out, **kwargs):
  57. passkwargs = {k: v for k, v in kwargs.items()
  58. if v is not np._NoValue}
  59. if type(obj) is not mu.ndarray:
  60. try:
  61. reduction = getattr(obj, method)
  62. except AttributeError:
  63. pass
  64. else:
  65. # This branch is needed for reductions like any which don't
  66. # support a dtype.
  67. if dtype is not None:
  68. return reduction(axis=axis, dtype=dtype, out=out, **passkwargs)
  69. else:
  70. return reduction(axis=axis, out=out, **passkwargs)
  71. return ufunc.reduce(obj, axis, dtype, out, **passkwargs)
  72. def _take_dispatcher(a, indices, axis=None, out=None, mode=None):
  73. return (a, out)
  74. @array_function_dispatch(_take_dispatcher)
  75. def take(a, indices, axis=None, out=None, mode='raise'):
  76. """
  77. Take elements from an array along an axis.
  78. When axis is not None, this function does the same thing as "fancy"
  79. indexing (indexing arrays using arrays); however, it can be easier to use
  80. if you need elements along a given axis. A call such as
  81. ``np.take(arr, indices, axis=3)`` is equivalent to
  82. ``arr[:,:,:,indices,...]``.
  83. Explained without fancy indexing, this is equivalent to the following use
  84. of `ndindex`, which sets each of ``ii``, ``jj``, and ``kk`` to a tuple of
  85. indices::
  86. Ni, Nk = a.shape[:axis], a.shape[axis+1:]
  87. Nj = indices.shape
  88. for ii in ndindex(Ni):
  89. for jj in ndindex(Nj):
  90. for kk in ndindex(Nk):
  91. out[ii + jj + kk] = a[ii + (indices[jj],) + kk]
  92. Parameters
  93. ----------
  94. a : array_like (Ni..., M, Nk...)
  95. The source array.
  96. indices : array_like (Nj...)
  97. The indices of the values to extract.
  98. .. versionadded:: 1.8.0
  99. Also allow scalars for indices.
  100. axis : int, optional
  101. The axis over which to select values. By default, the flattened
  102. input array is used.
  103. out : ndarray, optional (Ni..., Nj..., Nk...)
  104. If provided, the result will be placed in this array. It should
  105. be of the appropriate shape and dtype. Note that `out` is always
  106. buffered if `mode='raise'`; use other modes for better performance.
  107. mode : {'raise', 'wrap', 'clip'}, optional
  108. Specifies how out-of-bounds indices will behave.
  109. * 'raise' -- raise an error (default)
  110. * 'wrap' -- wrap around
  111. * 'clip' -- clip to the range
  112. 'clip' mode means that all indices that are too large are replaced
  113. by the index that addresses the last element along that axis. Note
  114. that this disables indexing with negative numbers.
  115. Returns
  116. -------
  117. out : ndarray (Ni..., Nj..., Nk...)
  118. The returned array has the same type as `a`.
  119. See Also
  120. --------
  121. compress : Take elements using a boolean mask
  122. ndarray.take : equivalent method
  123. take_along_axis : Take elements by matching the array and the index arrays
  124. Notes
  125. -----
  126. By eliminating the inner loop in the description above, and using `s_` to
  127. build simple slice objects, `take` can be expressed in terms of applying
  128. fancy indexing to each 1-d slice::
  129. Ni, Nk = a.shape[:axis], a.shape[axis+1:]
  130. for ii in ndindex(Ni):
  131. for kk in ndindex(Nj):
  132. out[ii + s_[...,] + kk] = a[ii + s_[:,] + kk][indices]
  133. For this reason, it is equivalent to (but faster than) the following use
  134. of `apply_along_axis`::
  135. out = np.apply_along_axis(lambda a_1d: a_1d[indices], axis, a)
  136. Examples
  137. --------
  138. >>> a = [4, 3, 5, 7, 6, 8]
  139. >>> indices = [0, 1, 4]
  140. >>> np.take(a, indices)
  141. array([4, 3, 6])
  142. In this example if `a` is an ndarray, "fancy" indexing can be used.
  143. >>> a = np.array(a)
  144. >>> a[indices]
  145. array([4, 3, 6])
  146. If `indices` is not one dimensional, the output also has these dimensions.
  147. >>> np.take(a, [[0, 1], [2, 3]])
  148. array([[4, 3],
  149. [5, 7]])
  150. """
  151. return _wrapfunc(a, 'take', indices, axis=axis, out=out, mode=mode)
  152. def _reshape_dispatcher(a, newshape, order=None):
  153. return (a,)
  154. # not deprecated --- copy if necessary, view otherwise
  155. @array_function_dispatch(_reshape_dispatcher)
  156. def reshape(a, newshape, order='C'):
  157. """
  158. Gives a new shape to an array without changing its data.
  159. Parameters
  160. ----------
  161. a : array_like
  162. Array to be reshaped.
  163. newshape : int or tuple of ints
  164. The new shape should be compatible with the original shape. If
  165. an integer, then the result will be a 1-D array of that length.
  166. One shape dimension can be -1. In this case, the value is
  167. inferred from the length of the array and remaining dimensions.
  168. order : {'C', 'F', 'A'}, optional
  169. Read the elements of `a` using this index order, and place the
  170. elements into the reshaped array using this index order. 'C'
  171. means to read / write the elements using C-like index order,
  172. with the last axis index changing fastest, back to the first
  173. axis index changing slowest. 'F' means to read / write the
  174. elements using Fortran-like index order, with the first index
  175. changing fastest, and the last index changing slowest. Note that
  176. the 'C' and 'F' options take no account of the memory layout of
  177. the underlying array, and only refer to the order of indexing.
  178. 'A' means to read / write the elements in Fortran-like index
  179. order if `a` is Fortran *contiguous* in memory, C-like order
  180. otherwise.
  181. Returns
  182. -------
  183. reshaped_array : ndarray
  184. This will be a new view object if possible; otherwise, it will
  185. be a copy. Note there is no guarantee of the *memory layout* (C- or
  186. Fortran- contiguous) of the returned array.
  187. See Also
  188. --------
  189. ndarray.reshape : Equivalent method.
  190. Notes
  191. -----
  192. It is not always possible to change the shape of an array without
  193. copying the data. If you want an error to be raised when the data is copied,
  194. you should assign the new shape to the shape attribute of the array::
  195. >>> a = np.zeros((10, 2))
  196. # A transpose makes the array non-contiguous
  197. >>> b = a.T
  198. # Taking a view makes it possible to modify the shape without modifying
  199. # the initial object.
  200. >>> c = b.view()
  201. >>> c.shape = (20)
  202. Traceback (most recent call last):
  203. ...
  204. AttributeError: Incompatible shape for in-place modification. Use
  205. `.reshape()` to make a copy with the desired shape.
  206. The `order` keyword gives the index ordering both for *fetching* the values
  207. from `a`, and then *placing* the values into the output array.
  208. For example, let's say you have an array:
  209. >>> a = np.arange(6).reshape((3, 2))
  210. >>> a
  211. array([[0, 1],
  212. [2, 3],
  213. [4, 5]])
  214. You can think of reshaping as first raveling the array (using the given
  215. index order), then inserting the elements from the raveled array into the
  216. new array using the same kind of index ordering as was used for the
  217. raveling.
  218. >>> np.reshape(a, (2, 3)) # C-like index ordering
  219. array([[0, 1, 2],
  220. [3, 4, 5]])
  221. >>> np.reshape(np.ravel(a), (2, 3)) # equivalent to C ravel then C reshape
  222. array([[0, 1, 2],
  223. [3, 4, 5]])
  224. >>> np.reshape(a, (2, 3), order='F') # Fortran-like index ordering
  225. array([[0, 4, 3],
  226. [2, 1, 5]])
  227. >>> np.reshape(np.ravel(a, order='F'), (2, 3), order='F')
  228. array([[0, 4, 3],
  229. [2, 1, 5]])
  230. Examples
  231. --------
  232. >>> a = np.array([[1,2,3], [4,5,6]])
  233. >>> np.reshape(a, 6)
  234. array([1, 2, 3, 4, 5, 6])
  235. >>> np.reshape(a, 6, order='F')
  236. array([1, 4, 2, 5, 3, 6])
  237. >>> np.reshape(a, (3,-1)) # the unspecified value is inferred to be 2
  238. array([[1, 2],
  239. [3, 4],
  240. [5, 6]])
  241. """
  242. return _wrapfunc(a, 'reshape', newshape, order=order)
  243. def _choose_dispatcher(a, choices, out=None, mode=None):
  244. yield a
  245. yield from choices
  246. yield out
  247. @array_function_dispatch(_choose_dispatcher)
  248. def choose(a, choices, out=None, mode='raise'):
  249. """
  250. Construct an array from an index array and a list of arrays to choose from.
  251. First of all, if confused or uncertain, definitely look at the Examples -
  252. in its full generality, this function is less simple than it might
  253. seem from the following code description (below ndi =
  254. `numpy.lib.index_tricks`):
  255. ``np.choose(a,c) == np.array([c[a[I]][I] for I in ndi.ndindex(a.shape)])``.
  256. But this omits some subtleties. Here is a fully general summary:
  257. Given an "index" array (`a`) of integers and a sequence of ``n`` arrays
  258. (`choices`), `a` and each choice array are first broadcast, as necessary,
  259. to arrays of a common shape; calling these *Ba* and *Bchoices[i], i =
  260. 0,...,n-1* we have that, necessarily, ``Ba.shape == Bchoices[i].shape``
  261. for each ``i``. Then, a new array with shape ``Ba.shape`` is created as
  262. follows:
  263. * if ``mode='raise'`` (the default), then, first of all, each element of
  264. ``a`` (and thus ``Ba``) must be in the range ``[0, n-1]``; now, suppose
  265. that ``i`` (in that range) is the value at the ``(j0, j1, ..., jm)``
  266. position in ``Ba`` - then the value at the same position in the new array
  267. is the value in ``Bchoices[i]`` at that same position;
  268. * if ``mode='wrap'``, values in `a` (and thus `Ba`) may be any (signed)
  269. integer; modular arithmetic is used to map integers outside the range
  270. `[0, n-1]` back into that range; and then the new array is constructed
  271. as above;
  272. * if ``mode='clip'``, values in `a` (and thus ``Ba``) may be any (signed)
  273. integer; negative integers are mapped to 0; values greater than ``n-1``
  274. are mapped to ``n-1``; and then the new array is constructed as above.
  275. Parameters
  276. ----------
  277. a : int array
  278. This array must contain integers in ``[0, n-1]``, where ``n`` is the
  279. number of choices, unless ``mode=wrap`` or ``mode=clip``, in which
  280. cases any integers are permissible.
  281. choices : sequence of arrays
  282. Choice arrays. `a` and all of the choices must be broadcastable to the
  283. same shape. If `choices` is itself an array (not recommended), then
  284. its outermost dimension (i.e., the one corresponding to
  285. ``choices.shape[0]``) is taken as defining the "sequence".
  286. out : array, optional
  287. If provided, the result will be inserted into this array. It should
  288. be of the appropriate shape and dtype. Note that `out` is always
  289. buffered if ``mode='raise'``; use other modes for better performance.
  290. mode : {'raise' (default), 'wrap', 'clip'}, optional
  291. Specifies how indices outside ``[0, n-1]`` will be treated:
  292. * 'raise' : an exception is raised
  293. * 'wrap' : value becomes value mod ``n``
  294. * 'clip' : values < 0 are mapped to 0, values > n-1 are mapped to n-1
  295. Returns
  296. -------
  297. merged_array : array
  298. The merged result.
  299. Raises
  300. ------
  301. ValueError: shape mismatch
  302. If `a` and each choice array are not all broadcastable to the same
  303. shape.
  304. See Also
  305. --------
  306. ndarray.choose : equivalent method
  307. numpy.take_along_axis : Preferable if `choices` is an array
  308. Notes
  309. -----
  310. To reduce the chance of misinterpretation, even though the following
  311. "abuse" is nominally supported, `choices` should neither be, nor be
  312. thought of as, a single array, i.e., the outermost sequence-like container
  313. should be either a list or a tuple.
  314. Examples
  315. --------
  316. >>> choices = [[0, 1, 2, 3], [10, 11, 12, 13],
  317. ... [20, 21, 22, 23], [30, 31, 32, 33]]
  318. >>> np.choose([2, 3, 1, 0], choices
  319. ... # the first element of the result will be the first element of the
  320. ... # third (2+1) "array" in choices, namely, 20; the second element
  321. ... # will be the second element of the fourth (3+1) choice array, i.e.,
  322. ... # 31, etc.
  323. ... )
  324. array([20, 31, 12, 3])
  325. >>> np.choose([2, 4, 1, 0], choices, mode='clip') # 4 goes to 3 (4-1)
  326. array([20, 31, 12, 3])
  327. >>> # because there are 4 choice arrays
  328. >>> np.choose([2, 4, 1, 0], choices, mode='wrap') # 4 goes to (4 mod 4)
  329. array([20, 1, 12, 3])
  330. >>> # i.e., 0
  331. A couple examples illustrating how choose broadcasts:
  332. >>> a = [[1, 0, 1], [0, 1, 0], [1, 0, 1]]
  333. >>> choices = [-10, 10]
  334. >>> np.choose(a, choices)
  335. array([[ 10, -10, 10],
  336. [-10, 10, -10],
  337. [ 10, -10, 10]])
  338. >>> # With thanks to Anne Archibald
  339. >>> a = np.array([0, 1]).reshape((2,1,1))
  340. >>> c1 = np.array([1, 2, 3]).reshape((1,3,1))
  341. >>> c2 = np.array([-1, -2, -3, -4, -5]).reshape((1,1,5))
  342. >>> np.choose(a, (c1, c2)) # result is 2x3x5, res[0,:,:]=c1, res[1,:,:]=c2
  343. array([[[ 1, 1, 1, 1, 1],
  344. [ 2, 2, 2, 2, 2],
  345. [ 3, 3, 3, 3, 3]],
  346. [[-1, -2, -3, -4, -5],
  347. [-1, -2, -3, -4, -5],
  348. [-1, -2, -3, -4, -5]]])
  349. """
  350. return _wrapfunc(a, 'choose', choices, out=out, mode=mode)
  351. def _repeat_dispatcher(a, repeats, axis=None):
  352. return (a,)
  353. @array_function_dispatch(_repeat_dispatcher)
  354. def repeat(a, repeats, axis=None):
  355. """
  356. Repeat elements of an array.
  357. Parameters
  358. ----------
  359. a : array_like
  360. Input array.
  361. repeats : int or array of ints
  362. The number of repetitions for each element. `repeats` is broadcasted
  363. to fit the shape of the given axis.
  364. axis : int, optional
  365. The axis along which to repeat values. By default, use the
  366. flattened input array, and return a flat output array.
  367. Returns
  368. -------
  369. repeated_array : ndarray
  370. Output array which has the same shape as `a`, except along
  371. the given axis.
  372. See Also
  373. --------
  374. tile : Tile an array.
  375. unique : Find the unique elements of an array.
  376. Examples
  377. --------
  378. >>> np.repeat(3, 4)
  379. array([3, 3, 3, 3])
  380. >>> x = np.array([[1,2],[3,4]])
  381. >>> np.repeat(x, 2)
  382. array([1, 1, 2, 2, 3, 3, 4, 4])
  383. >>> np.repeat(x, 3, axis=1)
  384. array([[1, 1, 1, 2, 2, 2],
  385. [3, 3, 3, 4, 4, 4]])
  386. >>> np.repeat(x, [1, 2], axis=0)
  387. array([[1, 2],
  388. [3, 4],
  389. [3, 4]])
  390. """
  391. return _wrapfunc(a, 'repeat', repeats, axis=axis)
  392. def _put_dispatcher(a, ind, v, mode=None):
  393. return (a, ind, v)
  394. @array_function_dispatch(_put_dispatcher)
  395. def put(a, ind, v, mode='raise'):
  396. """
  397. Replaces specified elements of an array with given values.
  398. The indexing works on the flattened target array. `put` is roughly
  399. equivalent to:
  400. ::
  401. a.flat[ind] = v
  402. Parameters
  403. ----------
  404. a : ndarray
  405. Target array.
  406. ind : array_like
  407. Target indices, interpreted as integers.
  408. v : array_like
  409. Values to place in `a` at target indices. If `v` is shorter than
  410. `ind` it will be repeated as necessary.
  411. mode : {'raise', 'wrap', 'clip'}, optional
  412. Specifies how out-of-bounds indices will behave.
  413. * 'raise' -- raise an error (default)
  414. * 'wrap' -- wrap around
  415. * 'clip' -- clip to the range
  416. 'clip' mode means that all indices that are too large are replaced
  417. by the index that addresses the last element along that axis. Note
  418. that this disables indexing with negative numbers. In 'raise' mode,
  419. if an exception occurs the target array may still be modified.
  420. See Also
  421. --------
  422. putmask, place
  423. put_along_axis : Put elements by matching the array and the index arrays
  424. Examples
  425. --------
  426. >>> a = np.arange(5)
  427. >>> np.put(a, [0, 2], [-44, -55])
  428. >>> a
  429. array([-44, 1, -55, 3, 4])
  430. >>> a = np.arange(5)
  431. >>> np.put(a, 22, -5, mode='clip')
  432. >>> a
  433. array([ 0, 1, 2, 3, -5])
  434. """
  435. try:
  436. put = a.put
  437. except AttributeError as e:
  438. raise TypeError("argument 1 must be numpy.ndarray, "
  439. "not {name}".format(name=type(a).__name__)) from e
  440. return put(ind, v, mode=mode)
  441. def _swapaxes_dispatcher(a, axis1, axis2):
  442. return (a,)
  443. @array_function_dispatch(_swapaxes_dispatcher)
  444. def swapaxes(a, axis1, axis2):
  445. """
  446. Interchange two axes of an array.
  447. Parameters
  448. ----------
  449. a : array_like
  450. Input array.
  451. axis1 : int
  452. First axis.
  453. axis2 : int
  454. Second axis.
  455. Returns
  456. -------
  457. a_swapped : ndarray
  458. For NumPy >= 1.10.0, if `a` is an ndarray, then a view of `a` is
  459. returned; otherwise a new array is created. For earlier NumPy
  460. versions a view of `a` is returned only if the order of the
  461. axes is changed, otherwise the input array is returned.
  462. Examples
  463. --------
  464. >>> x = np.array([[1,2,3]])
  465. >>> np.swapaxes(x,0,1)
  466. array([[1],
  467. [2],
  468. [3]])
  469. >>> x = np.array([[[0,1],[2,3]],[[4,5],[6,7]]])
  470. >>> x
  471. array([[[0, 1],
  472. [2, 3]],
  473. [[4, 5],
  474. [6, 7]]])
  475. >>> np.swapaxes(x,0,2)
  476. array([[[0, 4],
  477. [2, 6]],
  478. [[1, 5],
  479. [3, 7]]])
  480. """
  481. return _wrapfunc(a, 'swapaxes', axis1, axis2)
  482. def _transpose_dispatcher(a, axes=None):
  483. return (a,)
  484. @array_function_dispatch(_transpose_dispatcher)
  485. def transpose(a, axes=None):
  486. """
  487. Reverse or permute the axes of an array; returns the modified array.
  488. For an array a with two axes, transpose(a) gives the matrix transpose.
  489. Refer to `numpy.ndarray.transpose` for full documentation.
  490. Parameters
  491. ----------
  492. a : array_like
  493. Input array.
  494. axes : tuple or list of ints, optional
  495. If specified, it must be a tuple or list which contains a permutation of
  496. [0,1,..,N-1] where N is the number of axes of a. The i'th axis of the
  497. returned array will correspond to the axis numbered ``axes[i]`` of the
  498. input. If not specified, defaults to ``range(a.ndim)[::-1]``, which
  499. reverses the order of the axes.
  500. Returns
  501. -------
  502. p : ndarray
  503. `a` with its axes permuted. A view is returned whenever
  504. possible.
  505. See Also
  506. --------
  507. ndarray.transpose : Equivalent method
  508. moveaxis
  509. argsort
  510. Notes
  511. -----
  512. Use `transpose(a, argsort(axes))` to invert the transposition of tensors
  513. when using the `axes` keyword argument.
  514. Transposing a 1-D array returns an unchanged view of the original array.
  515. Examples
  516. --------
  517. >>> x = np.arange(4).reshape((2,2))
  518. >>> x
  519. array([[0, 1],
  520. [2, 3]])
  521. >>> np.transpose(x)
  522. array([[0, 2],
  523. [1, 3]])
  524. >>> x = np.ones((1, 2, 3))
  525. >>> np.transpose(x, (1, 0, 2)).shape
  526. (2, 1, 3)
  527. >>> x = np.ones((2, 3, 4, 5))
  528. >>> np.transpose(x).shape
  529. (5, 4, 3, 2)
  530. """
  531. return _wrapfunc(a, 'transpose', axes)
  532. def _partition_dispatcher(a, kth, axis=None, kind=None, order=None):
  533. return (a,)
  534. @array_function_dispatch(_partition_dispatcher)
  535. def partition(a, kth, axis=-1, kind='introselect', order=None):
  536. """
  537. Return a partitioned copy of an array.
  538. Creates a copy of the array with its elements rearranged in such a
  539. way that the value of the element in k-th position is in the
  540. position it would be in a sorted array. All elements smaller than
  541. the k-th element are moved before this element and all equal or
  542. greater are moved behind it. The ordering of the elements in the two
  543. partitions is undefined.
  544. .. versionadded:: 1.8.0
  545. Parameters
  546. ----------
  547. a : array_like
  548. Array to be sorted.
  549. kth : int or sequence of ints
  550. Element index to partition by. The k-th value of the element
  551. will be in its final sorted position and all smaller elements
  552. will be moved before it and all equal or greater elements behind
  553. it. The order of all elements in the partitions is undefined. If
  554. provided with a sequence of k-th it will partition all elements
  555. indexed by k-th of them into their sorted position at once.
  556. axis : int or None, optional
  557. Axis along which to sort. If None, the array is flattened before
  558. sorting. The default is -1, which sorts along the last axis.
  559. kind : {'introselect'}, optional
  560. Selection algorithm. Default is 'introselect'.
  561. order : str or list of str, optional
  562. When `a` is an array with fields defined, this argument
  563. specifies which fields to compare first, second, etc. A single
  564. field can be specified as a string. Not all fields need be
  565. specified, but unspecified fields will still be used, in the
  566. order in which they come up in the dtype, to break ties.
  567. Returns
  568. -------
  569. partitioned_array : ndarray
  570. Array of the same type and shape as `a`.
  571. See Also
  572. --------
  573. ndarray.partition : Method to sort an array in-place.
  574. argpartition : Indirect partition.
  575. sort : Full sorting
  576. Notes
  577. -----
  578. The various selection algorithms are characterized by their average
  579. speed, worst case performance, work space size, and whether they are
  580. stable. A stable sort keeps items with the same key in the same
  581. relative order. The available algorithms have the following
  582. properties:
  583. ================= ======= ============= ============ =======
  584. kind speed worst case work space stable
  585. ================= ======= ============= ============ =======
  586. 'introselect' 1 O(n) 0 no
  587. ================= ======= ============= ============ =======
  588. All the partition algorithms make temporary copies of the data when
  589. partitioning along any but the last axis. Consequently,
  590. partitioning along the last axis is faster and uses less space than
  591. partitioning along any other axis.
  592. The sort order for complex numbers is lexicographic. If both the
  593. real and imaginary parts are non-nan then the order is determined by
  594. the real parts except when they are equal, in which case the order
  595. is determined by the imaginary parts.
  596. Examples
  597. --------
  598. >>> a = np.array([3, 4, 2, 1])
  599. >>> np.partition(a, 3)
  600. array([2, 1, 3, 4])
  601. >>> np.partition(a, (1, 3))
  602. array([1, 2, 3, 4])
  603. """
  604. if axis is None:
  605. # flatten returns (1, N) for np.matrix, so always use the last axis
  606. a = asanyarray(a).flatten()
  607. axis = -1
  608. else:
  609. a = asanyarray(a).copy(order="K")
  610. a.partition(kth, axis=axis, kind=kind, order=order)
  611. return a
  612. def _argpartition_dispatcher(a, kth, axis=None, kind=None, order=None):
  613. return (a,)
  614. @array_function_dispatch(_argpartition_dispatcher)
  615. def argpartition(a, kth, axis=-1, kind='introselect', order=None):
  616. """
  617. Perform an indirect partition along the given axis using the
  618. algorithm specified by the `kind` keyword. It returns an array of
  619. indices of the same shape as `a` that index data along the given
  620. axis in partitioned order.
  621. .. versionadded:: 1.8.0
  622. Parameters
  623. ----------
  624. a : array_like
  625. Array to sort.
  626. kth : int or sequence of ints
  627. Element index to partition by. The k-th element will be in its
  628. final sorted position and all smaller elements will be moved
  629. before it and all larger elements behind it. The order all
  630. elements in the partitions is undefined. If provided with a
  631. sequence of k-th it will partition all of them into their sorted
  632. position at once.
  633. axis : int or None, optional
  634. Axis along which to sort. The default is -1 (the last axis). If
  635. None, the flattened array is used.
  636. kind : {'introselect'}, optional
  637. Selection algorithm. Default is 'introselect'
  638. order : str or list of str, optional
  639. When `a` is an array with fields defined, this argument
  640. specifies which fields to compare first, second, etc. A single
  641. field can be specified as a string, and not all fields need be
  642. specified, but unspecified fields will still be used, in the
  643. order in which they come up in the dtype, to break ties.
  644. Returns
  645. -------
  646. index_array : ndarray, int
  647. Array of indices that partition `a` along the specified axis.
  648. If `a` is one-dimensional, ``a[index_array]`` yields a partitioned `a`.
  649. More generally, ``np.take_along_axis(a, index_array, axis=a)`` always
  650. yields the partitioned `a`, irrespective of dimensionality.
  651. See Also
  652. --------
  653. partition : Describes partition algorithms used.
  654. ndarray.partition : Inplace partition.
  655. argsort : Full indirect sort.
  656. take_along_axis : Apply ``index_array`` from argpartition
  657. to an array as if by calling partition.
  658. Notes
  659. -----
  660. See `partition` for notes on the different selection algorithms.
  661. Examples
  662. --------
  663. One dimensional array:
  664. >>> x = np.array([3, 4, 2, 1])
  665. >>> x[np.argpartition(x, 3)]
  666. array([2, 1, 3, 4])
  667. >>> x[np.argpartition(x, (1, 3))]
  668. array([1, 2, 3, 4])
  669. >>> x = [3, 4, 2, 1]
  670. >>> np.array(x)[np.argpartition(x, 3)]
  671. array([2, 1, 3, 4])
  672. Multi-dimensional array:
  673. >>> x = np.array([[3, 4, 2], [1, 3, 1]])
  674. >>> index_array = np.argpartition(x, kth=1, axis=-1)
  675. >>> np.take_along_axis(x, index_array, axis=-1) # same as np.partition(x, kth=1)
  676. array([[2, 3, 4],
  677. [1, 1, 3]])
  678. """
  679. return _wrapfunc(a, 'argpartition', kth, axis=axis, kind=kind, order=order)
  680. def _sort_dispatcher(a, axis=None, kind=None, order=None):
  681. return (a,)
  682. @array_function_dispatch(_sort_dispatcher)
  683. def sort(a, axis=-1, kind=None, order=None):
  684. """
  685. Return a sorted copy of an array.
  686. Parameters
  687. ----------
  688. a : array_like
  689. Array to be sorted.
  690. axis : int or None, optional
  691. Axis along which to sort. If None, the array is flattened before
  692. sorting. The default is -1, which sorts along the last axis.
  693. kind : {'quicksort', 'mergesort', 'heapsort', 'stable'}, optional
  694. Sorting algorithm. The default is 'quicksort'. Note that both 'stable'
  695. and 'mergesort' use timsort or radix sort under the covers and, in general,
  696. the actual implementation will vary with data type. The 'mergesort' option
  697. is retained for backwards compatibility.
  698. .. versionchanged:: 1.15.0.
  699. The 'stable' option was added.
  700. order : str or list of str, optional
  701. When `a` is an array with fields defined, this argument specifies
  702. which fields to compare first, second, etc. A single field can
  703. be specified as a string, and not all fields need be specified,
  704. but unspecified fields will still be used, in the order in which
  705. they come up in the dtype, to break ties.
  706. Returns
  707. -------
  708. sorted_array : ndarray
  709. Array of the same type and shape as `a`.
  710. See Also
  711. --------
  712. ndarray.sort : Method to sort an array in-place.
  713. argsort : Indirect sort.
  714. lexsort : Indirect stable sort on multiple keys.
  715. searchsorted : Find elements in a sorted array.
  716. partition : Partial sort.
  717. Notes
  718. -----
  719. The various sorting algorithms are characterized by their average speed,
  720. worst case performance, work space size, and whether they are stable. A
  721. stable sort keeps items with the same key in the same relative
  722. order. The four algorithms implemented in NumPy have the following
  723. properties:
  724. =========== ======= ============= ============ ========
  725. kind speed worst case work space stable
  726. =========== ======= ============= ============ ========
  727. 'quicksort' 1 O(n^2) 0 no
  728. 'heapsort' 3 O(n*log(n)) 0 no
  729. 'mergesort' 2 O(n*log(n)) ~n/2 yes
  730. 'timsort' 2 O(n*log(n)) ~n/2 yes
  731. =========== ======= ============= ============ ========
  732. .. note:: The datatype determines which of 'mergesort' or 'timsort'
  733. is actually used, even if 'mergesort' is specified. User selection
  734. at a finer scale is not currently available.
  735. All the sort algorithms make temporary copies of the data when
  736. sorting along any but the last axis. Consequently, sorting along
  737. the last axis is faster and uses less space than sorting along
  738. any other axis.
  739. The sort order for complex numbers is lexicographic. If both the real
  740. and imaginary parts are non-nan then the order is determined by the
  741. real parts except when they are equal, in which case the order is
  742. determined by the imaginary parts.
  743. Previous to numpy 1.4.0 sorting real and complex arrays containing nan
  744. values led to undefined behaviour. In numpy versions >= 1.4.0 nan
  745. values are sorted to the end. The extended sort order is:
  746. * Real: [R, nan]
  747. * Complex: [R + Rj, R + nanj, nan + Rj, nan + nanj]
  748. where R is a non-nan real value. Complex values with the same nan
  749. placements are sorted according to the non-nan part if it exists.
  750. Non-nan values are sorted as before.
  751. .. versionadded:: 1.12.0
  752. quicksort has been changed to `introsort <https://en.wikipedia.org/wiki/Introsort>`_.
  753. When sorting does not make enough progress it switches to
  754. `heapsort <https://en.wikipedia.org/wiki/Heapsort>`_.
  755. This implementation makes quicksort O(n*log(n)) in the worst case.
  756. 'stable' automatically chooses the best stable sorting algorithm
  757. for the data type being sorted.
  758. It, along with 'mergesort' is currently mapped to
  759. `timsort <https://en.wikipedia.org/wiki/Timsort>`_
  760. or `radix sort <https://en.wikipedia.org/wiki/Radix_sort>`_
  761. depending on the data type.
  762. API forward compatibility currently limits the
  763. ability to select the implementation and it is hardwired for the different
  764. data types.
  765. .. versionadded:: 1.17.0
  766. Timsort is added for better performance on already or nearly
  767. sorted data. On random data timsort is almost identical to
  768. mergesort. It is now used for stable sort while quicksort is still the
  769. default sort if none is chosen. For timsort details, refer to
  770. `CPython listsort.txt <https://github.com/python/cpython/blob/3.7/Objects/listsort.txt>`_.
  771. 'mergesort' and 'stable' are mapped to radix sort for integer data types. Radix sort is an
  772. O(n) sort instead of O(n log n).
  773. .. versionchanged:: 1.18.0
  774. NaT now sorts to the end of arrays for consistency with NaN.
  775. Examples
  776. --------
  777. >>> a = np.array([[1,4],[3,1]])
  778. >>> np.sort(a) # sort along the last axis
  779. array([[1, 4],
  780. [1, 3]])
  781. >>> np.sort(a, axis=None) # sort the flattened array
  782. array([1, 1, 3, 4])
  783. >>> np.sort(a, axis=0) # sort along the first axis
  784. array([[1, 1],
  785. [3, 4]])
  786. Use the `order` keyword to specify a field to use when sorting a
  787. structured array:
  788. >>> dtype = [('name', 'S10'), ('height', float), ('age', int)]
  789. >>> values = [('Arthur', 1.8, 41), ('Lancelot', 1.9, 38),
  790. ... ('Galahad', 1.7, 38)]
  791. >>> a = np.array(values, dtype=dtype) # create a structured array
  792. >>> np.sort(a, order='height') # doctest: +SKIP
  793. array([('Galahad', 1.7, 38), ('Arthur', 1.8, 41),
  794. ('Lancelot', 1.8999999999999999, 38)],
  795. dtype=[('name', '|S10'), ('height', '<f8'), ('age', '<i4')])
  796. Sort by age, then height if ages are equal:
  797. >>> np.sort(a, order=['age', 'height']) # doctest: +SKIP
  798. array([('Galahad', 1.7, 38), ('Lancelot', 1.8999999999999999, 38),
  799. ('Arthur', 1.8, 41)],
  800. dtype=[('name', '|S10'), ('height', '<f8'), ('age', '<i4')])
  801. """
  802. if axis is None:
  803. # flatten returns (1, N) for np.matrix, so always use the last axis
  804. a = asanyarray(a).flatten()
  805. axis = -1
  806. else:
  807. a = asanyarray(a).copy(order="K")
  808. a.sort(axis=axis, kind=kind, order=order)
  809. return a
  810. def _argsort_dispatcher(a, axis=None, kind=None, order=None):
  811. return (a,)
  812. @array_function_dispatch(_argsort_dispatcher)
  813. def argsort(a, axis=-1, kind=None, order=None):
  814. """
  815. Returns the indices that would sort an array.
  816. Perform an indirect sort along the given axis using the algorithm specified
  817. by the `kind` keyword. It returns an array of indices of the same shape as
  818. `a` that index data along the given axis in sorted order.
  819. Parameters
  820. ----------
  821. a : array_like
  822. Array to sort.
  823. axis : int or None, optional
  824. Axis along which to sort. The default is -1 (the last axis). If None,
  825. the flattened array is used.
  826. kind : {'quicksort', 'mergesort', 'heapsort', 'stable'}, optional
  827. Sorting algorithm. The default is 'quicksort'. Note that both 'stable'
  828. and 'mergesort' use timsort under the covers and, in general, the
  829. actual implementation will vary with data type. The 'mergesort' option
  830. is retained for backwards compatibility.
  831. .. versionchanged:: 1.15.0.
  832. The 'stable' option was added.
  833. order : str or list of str, optional
  834. When `a` is an array with fields defined, this argument specifies
  835. which fields to compare first, second, etc. A single field can
  836. be specified as a string, and not all fields need be specified,
  837. but unspecified fields will still be used, in the order in which
  838. they come up in the dtype, to break ties.
  839. Returns
  840. -------
  841. index_array : ndarray, int
  842. Array of indices that sort `a` along the specified `axis`.
  843. If `a` is one-dimensional, ``a[index_array]`` yields a sorted `a`.
  844. More generally, ``np.take_along_axis(a, index_array, axis=axis)``
  845. always yields the sorted `a`, irrespective of dimensionality.
  846. See Also
  847. --------
  848. sort : Describes sorting algorithms used.
  849. lexsort : Indirect stable sort with multiple keys.
  850. ndarray.sort : Inplace sort.
  851. argpartition : Indirect partial sort.
  852. take_along_axis : Apply ``index_array`` from argsort
  853. to an array as if by calling sort.
  854. Notes
  855. -----
  856. See `sort` for notes on the different sorting algorithms.
  857. As of NumPy 1.4.0 `argsort` works with real/complex arrays containing
  858. nan values. The enhanced sort order is documented in `sort`.
  859. Examples
  860. --------
  861. One dimensional array:
  862. >>> x = np.array([3, 1, 2])
  863. >>> np.argsort(x)
  864. array([1, 2, 0])
  865. Two-dimensional array:
  866. >>> x = np.array([[0, 3], [2, 2]])
  867. >>> x
  868. array([[0, 3],
  869. [2, 2]])
  870. >>> ind = np.argsort(x, axis=0) # sorts along first axis (down)
  871. >>> ind
  872. array([[0, 1],
  873. [1, 0]])
  874. >>> np.take_along_axis(x, ind, axis=0) # same as np.sort(x, axis=0)
  875. array([[0, 2],
  876. [2, 3]])
  877. >>> ind = np.argsort(x, axis=1) # sorts along last axis (across)
  878. >>> ind
  879. array([[0, 1],
  880. [0, 1]])
  881. >>> np.take_along_axis(x, ind, axis=1) # same as np.sort(x, axis=1)
  882. array([[0, 3],
  883. [2, 2]])
  884. Indices of the sorted elements of a N-dimensional array:
  885. >>> ind = np.unravel_index(np.argsort(x, axis=None), x.shape)
  886. >>> ind
  887. (array([0, 1, 1, 0]), array([0, 0, 1, 1]))
  888. >>> x[ind] # same as np.sort(x, axis=None)
  889. array([0, 2, 2, 3])
  890. Sorting with keys:
  891. >>> x = np.array([(1, 0), (0, 1)], dtype=[('x', '<i4'), ('y', '<i4')])
  892. >>> x
  893. array([(1, 0), (0, 1)],
  894. dtype=[('x', '<i4'), ('y', '<i4')])
  895. >>> np.argsort(x, order=('x','y'))
  896. array([1, 0])
  897. >>> np.argsort(x, order=('y','x'))
  898. array([0, 1])
  899. """
  900. return _wrapfunc(a, 'argsort', axis=axis, kind=kind, order=order)
  901. def _argmax_dispatcher(a, axis=None, out=None):
  902. return (a, out)
  903. @array_function_dispatch(_argmax_dispatcher)
  904. def argmax(a, axis=None, out=None):
  905. """
  906. Returns the indices of the maximum values along an axis.
  907. Parameters
  908. ----------
  909. a : array_like
  910. Input array.
  911. axis : int, optional
  912. By default, the index is into the flattened array, otherwise
  913. along the specified axis.
  914. out : array, optional
  915. If provided, the result will be inserted into this array. It should
  916. be of the appropriate shape and dtype.
  917. Returns
  918. -------
  919. index_array : ndarray of ints
  920. Array of indices into the array. It has the same shape as `a.shape`
  921. with the dimension along `axis` removed.
  922. See Also
  923. --------
  924. ndarray.argmax, argmin
  925. amax : The maximum value along a given axis.
  926. unravel_index : Convert a flat index into an index tuple.
  927. take_along_axis : Apply ``np.expand_dims(index_array, axis)``
  928. from argmax to an array as if by calling max.
  929. Notes
  930. -----
  931. In case of multiple occurrences of the maximum values, the indices
  932. corresponding to the first occurrence are returned.
  933. Examples
  934. --------
  935. >>> a = np.arange(6).reshape(2,3) + 10
  936. >>> a
  937. array([[10, 11, 12],
  938. [13, 14, 15]])
  939. >>> np.argmax(a)
  940. 5
  941. >>> np.argmax(a, axis=0)
  942. array([1, 1, 1])
  943. >>> np.argmax(a, axis=1)
  944. array([2, 2])
  945. Indexes of the maximal elements of a N-dimensional array:
  946. >>> ind = np.unravel_index(np.argmax(a, axis=None), a.shape)
  947. >>> ind
  948. (1, 2)
  949. >>> a[ind]
  950. 15
  951. >>> b = np.arange(6)
  952. >>> b[1] = 5
  953. >>> b
  954. array([0, 5, 2, 3, 4, 5])
  955. >>> np.argmax(b) # Only the first occurrence is returned.
  956. 1
  957. >>> x = np.array([[4,2,3], [1,0,3]])
  958. >>> index_array = np.argmax(x, axis=-1)
  959. >>> # Same as np.max(x, axis=-1, keepdims=True)
  960. >>> np.take_along_axis(x, np.expand_dims(index_array, axis=-1), axis=-1)
  961. array([[4],
  962. [3]])
  963. >>> # Same as np.max(x, axis=-1)
  964. >>> np.take_along_axis(x, np.expand_dims(index_array, axis=-1), axis=-1).squeeze(axis=-1)
  965. array([4, 3])
  966. """
  967. return _wrapfunc(a, 'argmax', axis=axis, out=out)
  968. def _argmin_dispatcher(a, axis=None, out=None):
  969. return (a, out)
  970. @array_function_dispatch(_argmin_dispatcher)
  971. def argmin(a, axis=None, out=None):
  972. """
  973. Returns the indices of the minimum values along an axis.
  974. Parameters
  975. ----------
  976. a : array_like
  977. Input array.
  978. axis : int, optional
  979. By default, the index is into the flattened array, otherwise
  980. along the specified axis.
  981. out : array, optional
  982. If provided, the result will be inserted into this array. It should
  983. be of the appropriate shape and dtype.
  984. Returns
  985. -------
  986. index_array : ndarray of ints
  987. Array of indices into the array. It has the same shape as `a.shape`
  988. with the dimension along `axis` removed.
  989. See Also
  990. --------
  991. ndarray.argmin, argmax
  992. amin : The minimum value along a given axis.
  993. unravel_index : Convert a flat index into an index tuple.
  994. take_along_axis : Apply ``np.expand_dims(index_array, axis)``
  995. from argmin to an array as if by calling min.
  996. Notes
  997. -----
  998. In case of multiple occurrences of the minimum values, the indices
  999. corresponding to the first occurrence are returned.
  1000. Examples
  1001. --------
  1002. >>> a = np.arange(6).reshape(2,3) + 10
  1003. >>> a
  1004. array([[10, 11, 12],
  1005. [13, 14, 15]])
  1006. >>> np.argmin(a)
  1007. 0
  1008. >>> np.argmin(a, axis=0)
  1009. array([0, 0, 0])
  1010. >>> np.argmin(a, axis=1)
  1011. array([0, 0])
  1012. Indices of the minimum elements of a N-dimensional array:
  1013. >>> ind = np.unravel_index(np.argmin(a, axis=None), a.shape)
  1014. >>> ind
  1015. (0, 0)
  1016. >>> a[ind]
  1017. 10
  1018. >>> b = np.arange(6) + 10
  1019. >>> b[4] = 10
  1020. >>> b
  1021. array([10, 11, 12, 13, 10, 15])
  1022. >>> np.argmin(b) # Only the first occurrence is returned.
  1023. 0
  1024. >>> x = np.array([[4,2,3], [1,0,3]])
  1025. >>> index_array = np.argmin(x, axis=-1)
  1026. >>> # Same as np.min(x, axis=-1, keepdims=True)
  1027. >>> np.take_along_axis(x, np.expand_dims(index_array, axis=-1), axis=-1)
  1028. array([[2],
  1029. [0]])
  1030. >>> # Same as np.max(x, axis=-1)
  1031. >>> np.take_along_axis(x, np.expand_dims(index_array, axis=-1), axis=-1).squeeze(axis=-1)
  1032. array([2, 0])
  1033. """
  1034. return _wrapfunc(a, 'argmin', axis=axis, out=out)
  1035. def _searchsorted_dispatcher(a, v, side=None, sorter=None):
  1036. return (a, v, sorter)
  1037. @array_function_dispatch(_searchsorted_dispatcher)
  1038. def searchsorted(a, v, side='left', sorter=None):
  1039. """
  1040. Find indices where elements should be inserted to maintain order.
  1041. Find the indices into a sorted array `a` such that, if the
  1042. corresponding elements in `v` were inserted before the indices, the
  1043. order of `a` would be preserved.
  1044. Assuming that `a` is sorted:
  1045. ====== ============================
  1046. `side` returned index `i` satisfies
  1047. ====== ============================
  1048. left ``a[i-1] < v <= a[i]``
  1049. right ``a[i-1] <= v < a[i]``
  1050. ====== ============================
  1051. Parameters
  1052. ----------
  1053. a : 1-D array_like
  1054. Input array. If `sorter` is None, then it must be sorted in
  1055. ascending order, otherwise `sorter` must be an array of indices
  1056. that sort it.
  1057. v : array_like
  1058. Values to insert into `a`.
  1059. side : {'left', 'right'}, optional
  1060. If 'left', the index of the first suitable location found is given.
  1061. If 'right', return the last such index. If there is no suitable
  1062. index, return either 0 or N (where N is the length of `a`).
  1063. sorter : 1-D array_like, optional
  1064. Optional array of integer indices that sort array a into ascending
  1065. order. They are typically the result of argsort.
  1066. .. versionadded:: 1.7.0
  1067. Returns
  1068. -------
  1069. indices : array of ints
  1070. Array of insertion points with the same shape as `v`.
  1071. See Also
  1072. --------
  1073. sort : Return a sorted copy of an array.
  1074. histogram : Produce histogram from 1-D data.
  1075. Notes
  1076. -----
  1077. Binary search is used to find the required insertion points.
  1078. As of NumPy 1.4.0 `searchsorted` works with real/complex arrays containing
  1079. `nan` values. The enhanced sort order is documented in `sort`.
  1080. This function uses the same algorithm as the builtin python `bisect.bisect_left`
  1081. (``side='left'``) and `bisect.bisect_right` (``side='right'``) functions,
  1082. which is also vectorized in the `v` argument.
  1083. Examples
  1084. --------
  1085. >>> np.searchsorted([1,2,3,4,5], 3)
  1086. 2
  1087. >>> np.searchsorted([1,2,3,4,5], 3, side='right')
  1088. 3
  1089. >>> np.searchsorted([1,2,3,4,5], [-10, 10, 2, 3])
  1090. array([0, 5, 1, 2])
  1091. """
  1092. return _wrapfunc(a, 'searchsorted', v, side=side, sorter=sorter)
  1093. def _resize_dispatcher(a, new_shape):
  1094. return (a,)
  1095. @array_function_dispatch(_resize_dispatcher)
  1096. def resize(a, new_shape):
  1097. """
  1098. Return a new array with the specified shape.
  1099. If the new array is larger than the original array, then the new
  1100. array is filled with repeated copies of `a`. Note that this behavior
  1101. is different from a.resize(new_shape) which fills with zeros instead
  1102. of repeated copies of `a`.
  1103. Parameters
  1104. ----------
  1105. a : array_like
  1106. Array to be resized.
  1107. new_shape : int or tuple of int
  1108. Shape of resized array.
  1109. Returns
  1110. -------
  1111. reshaped_array : ndarray
  1112. The new array is formed from the data in the old array, repeated
  1113. if necessary to fill out the required number of elements. The
  1114. data are repeated iterating over the array in C-order.
  1115. See Also
  1116. --------
  1117. np.reshape : Reshape an array without changing the total size.
  1118. np.pad : Enlarge and pad an array.
  1119. np.repeat : Repeat elements of an array.
  1120. ndarray.resize : resize an array in-place.
  1121. Notes
  1122. -----
  1123. When the total size of the array does not change `~numpy.reshape` should
  1124. be used. In most other cases either indexing (to reduce the size)
  1125. or padding (to increase the size) may be a more appropriate solution.
  1126. Warning: This functionality does **not** consider axes separately,
  1127. i.e. it does not apply interpolation/extrapolation.
  1128. It fills the return array with the required number of elements, iterating
  1129. over `a` in C-order, disregarding axes (and cycling back from the start if
  1130. the new shape is larger). This functionality is therefore not suitable to
  1131. resize images, or data where each axis represents a separate and distinct
  1132. entity.
  1133. Examples
  1134. --------
  1135. >>> a=np.array([[0,1],[2,3]])
  1136. >>> np.resize(a,(2,3))
  1137. array([[0, 1, 2],
  1138. [3, 0, 1]])
  1139. >>> np.resize(a,(1,4))
  1140. array([[0, 1, 2, 3]])
  1141. >>> np.resize(a,(2,4))
  1142. array([[0, 1, 2, 3],
  1143. [0, 1, 2, 3]])
  1144. """
  1145. if isinstance(new_shape, (int, nt.integer)):
  1146. new_shape = (new_shape,)
  1147. a = ravel(a)
  1148. new_size = 1
  1149. for dim_length in new_shape:
  1150. new_size *= dim_length
  1151. if dim_length < 0:
  1152. raise ValueError('all elements of `new_shape` must be non-negative')
  1153. if a.size == 0 or new_size == 0:
  1154. # First case must zero fill. The second would have repeats == 0.
  1155. return np.zeros_like(a, shape=new_shape)
  1156. repeats = -(-new_size // a.size) # ceil division
  1157. a = concatenate((a,) * repeats)[:new_size]
  1158. return reshape(a, new_shape)
  1159. def _squeeze_dispatcher(a, axis=None):
  1160. return (a,)
  1161. @array_function_dispatch(_squeeze_dispatcher)
  1162. def squeeze(a, axis=None):
  1163. """
  1164. Remove axes of length one from `a`.
  1165. Parameters
  1166. ----------
  1167. a : array_like
  1168. Input data.
  1169. axis : None or int or tuple of ints, optional
  1170. .. versionadded:: 1.7.0
  1171. Selects a subset of the entries of length one in the
  1172. shape. If an axis is selected with shape entry greater than
  1173. one, an error is raised.
  1174. Returns
  1175. -------
  1176. squeezed : ndarray
  1177. The input array, but with all or a subset of the
  1178. dimensions of length 1 removed. This is always `a` itself
  1179. or a view into `a`. Note that if all axes are squeezed,
  1180. the result is a 0d array and not a scalar.
  1181. Raises
  1182. ------
  1183. ValueError
  1184. If `axis` is not None, and an axis being squeezed is not of length 1
  1185. See Also
  1186. --------
  1187. expand_dims : The inverse operation, adding entries of length one
  1188. reshape : Insert, remove, and combine dimensions, and resize existing ones
  1189. Examples
  1190. --------
  1191. >>> x = np.array([[[0], [1], [2]]])
  1192. >>> x.shape
  1193. (1, 3, 1)
  1194. >>> np.squeeze(x).shape
  1195. (3,)
  1196. >>> np.squeeze(x, axis=0).shape
  1197. (3, 1)
  1198. >>> np.squeeze(x, axis=1).shape
  1199. Traceback (most recent call last):
  1200. ...
  1201. ValueError: cannot select an axis to squeeze out which has size not equal to one
  1202. >>> np.squeeze(x, axis=2).shape
  1203. (1, 3)
  1204. >>> x = np.array([[1234]])
  1205. >>> x.shape
  1206. (1, 1)
  1207. >>> np.squeeze(x)
  1208. array(1234) # 0d array
  1209. >>> np.squeeze(x).shape
  1210. ()
  1211. >>> np.squeeze(x)[()]
  1212. 1234
  1213. """
  1214. try:
  1215. squeeze = a.squeeze
  1216. except AttributeError:
  1217. return _wrapit(a, 'squeeze', axis=axis)
  1218. if axis is None:
  1219. return squeeze()
  1220. else:
  1221. return squeeze(axis=axis)
  1222. def _diagonal_dispatcher(a, offset=None, axis1=None, axis2=None):
  1223. return (a,)
  1224. @array_function_dispatch(_diagonal_dispatcher)
  1225. def diagonal(a, offset=0, axis1=0, axis2=1):
  1226. """
  1227. Return specified diagonals.
  1228. If `a` is 2-D, returns the diagonal of `a` with the given offset,
  1229. i.e., the collection of elements of the form ``a[i, i+offset]``. If
  1230. `a` has more than two dimensions, then the axes specified by `axis1`
  1231. and `axis2` are used to determine the 2-D sub-array whose diagonal is
  1232. returned. The shape of the resulting array can be determined by
  1233. removing `axis1` and `axis2` and appending an index to the right equal
  1234. to the size of the resulting diagonals.
  1235. In versions of NumPy prior to 1.7, this function always returned a new,
  1236. independent array containing a copy of the values in the diagonal.
  1237. In NumPy 1.7 and 1.8, it continues to return a copy of the diagonal,
  1238. but depending on this fact is deprecated. Writing to the resulting
  1239. array continues to work as it used to, but a FutureWarning is issued.
  1240. Starting in NumPy 1.9 it returns a read-only view on the original array.
  1241. Attempting to write to the resulting array will produce an error.
  1242. In some future release, it will return a read/write view and writing to
  1243. the returned array will alter your original array. The returned array
  1244. will have the same type as the input array.
  1245. If you don't write to the array returned by this function, then you can
  1246. just ignore all of the above.
  1247. If you depend on the current behavior, then we suggest copying the
  1248. returned array explicitly, i.e., use ``np.diagonal(a).copy()`` instead
  1249. of just ``np.diagonal(a)``. This will work with both past and future
  1250. versions of NumPy.
  1251. Parameters
  1252. ----------
  1253. a : array_like
  1254. Array from which the diagonals are taken.
  1255. offset : int, optional
  1256. Offset of the diagonal from the main diagonal. Can be positive or
  1257. negative. Defaults to main diagonal (0).
  1258. axis1 : int, optional
  1259. Axis to be used as the first axis of the 2-D sub-arrays from which
  1260. the diagonals should be taken. Defaults to first axis (0).
  1261. axis2 : int, optional
  1262. Axis to be used as the second axis of the 2-D sub-arrays from
  1263. which the diagonals should be taken. Defaults to second axis (1).
  1264. Returns
  1265. -------
  1266. array_of_diagonals : ndarray
  1267. If `a` is 2-D, then a 1-D array containing the diagonal and of the
  1268. same type as `a` is returned unless `a` is a `matrix`, in which case
  1269. a 1-D array rather than a (2-D) `matrix` is returned in order to
  1270. maintain backward compatibility.
  1271. If ``a.ndim > 2``, then the dimensions specified by `axis1` and `axis2`
  1272. are removed, and a new axis inserted at the end corresponding to the
  1273. diagonal.
  1274. Raises
  1275. ------
  1276. ValueError
  1277. If the dimension of `a` is less than 2.
  1278. See Also
  1279. --------
  1280. diag : MATLAB work-a-like for 1-D and 2-D arrays.
  1281. diagflat : Create diagonal arrays.
  1282. trace : Sum along diagonals.
  1283. Examples
  1284. --------
  1285. >>> a = np.arange(4).reshape(2,2)
  1286. >>> a
  1287. array([[0, 1],
  1288. [2, 3]])
  1289. >>> a.diagonal()
  1290. array([0, 3])
  1291. >>> a.diagonal(1)
  1292. array([1])
  1293. A 3-D example:
  1294. >>> a = np.arange(8).reshape(2,2,2); a
  1295. array([[[0, 1],
  1296. [2, 3]],
  1297. [[4, 5],
  1298. [6, 7]]])
  1299. >>> a.diagonal(0, # Main diagonals of two arrays created by skipping
  1300. ... 0, # across the outer(left)-most axis last and
  1301. ... 1) # the "middle" (row) axis first.
  1302. array([[0, 6],
  1303. [1, 7]])
  1304. The sub-arrays whose main diagonals we just obtained; note that each
  1305. corresponds to fixing the right-most (column) axis, and that the
  1306. diagonals are "packed" in rows.
  1307. >>> a[:,:,0] # main diagonal is [0 6]
  1308. array([[0, 2],
  1309. [4, 6]])
  1310. >>> a[:,:,1] # main diagonal is [1 7]
  1311. array([[1, 3],
  1312. [5, 7]])
  1313. The anti-diagonal can be obtained by reversing the order of elements
  1314. using either `numpy.flipud` or `numpy.fliplr`.
  1315. >>> a = np.arange(9).reshape(3, 3)
  1316. >>> a
  1317. array([[0, 1, 2],
  1318. [3, 4, 5],
  1319. [6, 7, 8]])
  1320. >>> np.fliplr(a).diagonal() # Horizontal flip
  1321. array([2, 4, 6])
  1322. >>> np.flipud(a).diagonal() # Vertical flip
  1323. array([6, 4, 2])
  1324. Note that the order in which the diagonal is retrieved varies depending
  1325. on the flip function.
  1326. """
  1327. if isinstance(a, np.matrix):
  1328. # Make diagonal of matrix 1-D to preserve backward compatibility.
  1329. return asarray(a).diagonal(offset=offset, axis1=axis1, axis2=axis2)
  1330. else:
  1331. return asanyarray(a).diagonal(offset=offset, axis1=axis1, axis2=axis2)
  1332. def _trace_dispatcher(
  1333. a, offset=None, axis1=None, axis2=None, dtype=None, out=None):
  1334. return (a, out)
  1335. @array_function_dispatch(_trace_dispatcher)
  1336. def trace(a, offset=0, axis1=0, axis2=1, dtype=None, out=None):
  1337. """
  1338. Return the sum along diagonals of the array.
  1339. If `a` is 2-D, the sum along its diagonal with the given offset
  1340. is returned, i.e., the sum of elements ``a[i,i+offset]`` for all i.
  1341. If `a` has more than two dimensions, then the axes specified by axis1 and
  1342. axis2 are used to determine the 2-D sub-arrays whose traces are returned.
  1343. The shape of the resulting array is the same as that of `a` with `axis1`
  1344. and `axis2` removed.
  1345. Parameters
  1346. ----------
  1347. a : array_like
  1348. Input array, from which the diagonals are taken.
  1349. offset : int, optional
  1350. Offset of the diagonal from the main diagonal. Can be both positive
  1351. and negative. Defaults to 0.
  1352. axis1, axis2 : int, optional
  1353. Axes to be used as the first and second axis of the 2-D sub-arrays
  1354. from which the diagonals should be taken. Defaults are the first two
  1355. axes of `a`.
  1356. dtype : dtype, optional
  1357. Determines the data-type of the returned array and of the accumulator
  1358. where the elements are summed. If dtype has the value None and `a` is
  1359. of integer type of precision less than the default integer
  1360. precision, then the default integer precision is used. Otherwise,
  1361. the precision is the same as that of `a`.
  1362. out : ndarray, optional
  1363. Array into which the output is placed. Its type is preserved and
  1364. it must be of the right shape to hold the output.
  1365. Returns
  1366. -------
  1367. sum_along_diagonals : ndarray
  1368. If `a` is 2-D, the sum along the diagonal is returned. If `a` has
  1369. larger dimensions, then an array of sums along diagonals is returned.
  1370. See Also
  1371. --------
  1372. diag, diagonal, diagflat
  1373. Examples
  1374. --------
  1375. >>> np.trace(np.eye(3))
  1376. 3.0
  1377. >>> a = np.arange(8).reshape((2,2,2))
  1378. >>> np.trace(a)
  1379. array([6, 8])
  1380. >>> a = np.arange(24).reshape((2,2,2,3))
  1381. >>> np.trace(a).shape
  1382. (2, 3)
  1383. """
  1384. if isinstance(a, np.matrix):
  1385. # Get trace of matrix via an array to preserve backward compatibility.
  1386. return asarray(a).trace(offset=offset, axis1=axis1, axis2=axis2, dtype=dtype, out=out)
  1387. else:
  1388. return asanyarray(a).trace(offset=offset, axis1=axis1, axis2=axis2, dtype=dtype, out=out)
  1389. def _ravel_dispatcher(a, order=None):
  1390. return (a,)
  1391. @array_function_dispatch(_ravel_dispatcher)
  1392. def ravel(a, order='C'):
  1393. """Return a contiguous flattened array.
  1394. A 1-D array, containing the elements of the input, is returned. A copy is
  1395. made only if needed.
  1396. As of NumPy 1.10, the returned array will have the same type as the input
  1397. array. (for example, a masked array will be returned for a masked array
  1398. input)
  1399. Parameters
  1400. ----------
  1401. a : array_like
  1402. Input array. The elements in `a` are read in the order specified by
  1403. `order`, and packed as a 1-D array.
  1404. order : {'C','F', 'A', 'K'}, optional
  1405. The elements of `a` are read using this index order. 'C' means
  1406. to index the elements in row-major, C-style order,
  1407. with the last axis index changing fastest, back to the first
  1408. axis index changing slowest. 'F' means to index the elements
  1409. in column-major, Fortran-style order, with the
  1410. first index changing fastest, and the last index changing
  1411. slowest. Note that the 'C' and 'F' options take no account of
  1412. the memory layout of the underlying array, and only refer to
  1413. the order of axis indexing. 'A' means to read the elements in
  1414. Fortran-like index order if `a` is Fortran *contiguous* in
  1415. memory, C-like order otherwise. 'K' means to read the
  1416. elements in the order they occur in memory, except for
  1417. reversing the data when strides are negative. By default, 'C'
  1418. index order is used.
  1419. Returns
  1420. -------
  1421. y : array_like
  1422. y is an array of the same subtype as `a`, with shape ``(a.size,)``.
  1423. Note that matrices are special cased for backward compatibility, if `a`
  1424. is a matrix, then y is a 1-D ndarray.
  1425. See Also
  1426. --------
  1427. ndarray.flat : 1-D iterator over an array.
  1428. ndarray.flatten : 1-D array copy of the elements of an array
  1429. in row-major order.
  1430. ndarray.reshape : Change the shape of an array without changing its data.
  1431. Notes
  1432. -----
  1433. In row-major, C-style order, in two dimensions, the row index
  1434. varies the slowest, and the column index the quickest. This can
  1435. be generalized to multiple dimensions, where row-major order
  1436. implies that the index along the first axis varies slowest, and
  1437. the index along the last quickest. The opposite holds for
  1438. column-major, Fortran-style index ordering.
  1439. When a view is desired in as many cases as possible, ``arr.reshape(-1)``
  1440. may be preferable.
  1441. Examples
  1442. --------
  1443. It is equivalent to ``reshape(-1, order=order)``.
  1444. >>> x = np.array([[1, 2, 3], [4, 5, 6]])
  1445. >>> np.ravel(x)
  1446. array([1, 2, 3, 4, 5, 6])
  1447. >>> x.reshape(-1)
  1448. array([1, 2, 3, 4, 5, 6])
  1449. >>> np.ravel(x, order='F')
  1450. array([1, 4, 2, 5, 3, 6])
  1451. When ``order`` is 'A', it will preserve the array's 'C' or 'F' ordering:
  1452. >>> np.ravel(x.T)
  1453. array([1, 4, 2, 5, 3, 6])
  1454. >>> np.ravel(x.T, order='A')
  1455. array([1, 2, 3, 4, 5, 6])
  1456. When ``order`` is 'K', it will preserve orderings that are neither 'C'
  1457. nor 'F', but won't reverse axes:
  1458. >>> a = np.arange(3)[::-1]; a
  1459. array([2, 1, 0])
  1460. >>> a.ravel(order='C')
  1461. array([2, 1, 0])
  1462. >>> a.ravel(order='K')
  1463. array([2, 1, 0])
  1464. >>> a = np.arange(12).reshape(2,3,2).swapaxes(1,2); a
  1465. array([[[ 0, 2, 4],
  1466. [ 1, 3, 5]],
  1467. [[ 6, 8, 10],
  1468. [ 7, 9, 11]]])
  1469. >>> a.ravel(order='C')
  1470. array([ 0, 2, 4, 1, 3, 5, 6, 8, 10, 7, 9, 11])
  1471. >>> a.ravel(order='K')
  1472. array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
  1473. """
  1474. if isinstance(a, np.matrix):
  1475. return asarray(a).ravel(order=order)
  1476. else:
  1477. return asanyarray(a).ravel(order=order)
  1478. def _nonzero_dispatcher(a):
  1479. return (a,)
  1480. @array_function_dispatch(_nonzero_dispatcher)
  1481. def nonzero(a):
  1482. """
  1483. Return the indices of the elements that are non-zero.
  1484. Returns a tuple of arrays, one for each dimension of `a`,
  1485. containing the indices of the non-zero elements in that
  1486. dimension. The values in `a` are always tested and returned in
  1487. row-major, C-style order.
  1488. To group the indices by element, rather than dimension, use `argwhere`,
  1489. which returns a row for each non-zero element.
  1490. .. note::
  1491. When called on a zero-d array or scalar, ``nonzero(a)`` is treated
  1492. as ``nonzero(atleast_1d(a))``.
  1493. .. deprecated:: 1.17.0
  1494. Use `atleast_1d` explicitly if this behavior is deliberate.
  1495. Parameters
  1496. ----------
  1497. a : array_like
  1498. Input array.
  1499. Returns
  1500. -------
  1501. tuple_of_arrays : tuple
  1502. Indices of elements that are non-zero.
  1503. See Also
  1504. --------
  1505. flatnonzero :
  1506. Return indices that are non-zero in the flattened version of the input
  1507. array.
  1508. ndarray.nonzero :
  1509. Equivalent ndarray method.
  1510. count_nonzero :
  1511. Counts the number of non-zero elements in the input array.
  1512. Notes
  1513. -----
  1514. While the nonzero values can be obtained with ``a[nonzero(a)]``, it is
  1515. recommended to use ``x[x.astype(bool)]`` or ``x[x != 0]`` instead, which
  1516. will correctly handle 0-d arrays.
  1517. Examples
  1518. --------
  1519. >>> x = np.array([[3, 0, 0], [0, 4, 0], [5, 6, 0]])
  1520. >>> x
  1521. array([[3, 0, 0],
  1522. [0, 4, 0],
  1523. [5, 6, 0]])
  1524. >>> np.nonzero(x)
  1525. (array([0, 1, 2, 2]), array([0, 1, 0, 1]))
  1526. >>> x[np.nonzero(x)]
  1527. array([3, 4, 5, 6])
  1528. >>> np.transpose(np.nonzero(x))
  1529. array([[0, 0],
  1530. [1, 1],
  1531. [2, 0],
  1532. [2, 1]])
  1533. A common use for ``nonzero`` is to find the indices of an array, where
  1534. a condition is True. Given an array `a`, the condition `a` > 3 is a
  1535. boolean array and since False is interpreted as 0, np.nonzero(a > 3)
  1536. yields the indices of the `a` where the condition is true.
  1537. >>> a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
  1538. >>> a > 3
  1539. array([[False, False, False],
  1540. [ True, True, True],
  1541. [ True, True, True]])
  1542. >>> np.nonzero(a > 3)
  1543. (array([1, 1, 1, 2, 2, 2]), array([0, 1, 2, 0, 1, 2]))
  1544. Using this result to index `a` is equivalent to using the mask directly:
  1545. >>> a[np.nonzero(a > 3)]
  1546. array([4, 5, 6, 7, 8, 9])
  1547. >>> a[a > 3] # prefer this spelling
  1548. array([4, 5, 6, 7, 8, 9])
  1549. ``nonzero`` can also be called as a method of the array.
  1550. >>> (a > 3).nonzero()
  1551. (array([1, 1, 1, 2, 2, 2]), array([0, 1, 2, 0, 1, 2]))
  1552. """
  1553. return _wrapfunc(a, 'nonzero')
  1554. def _shape_dispatcher(a):
  1555. return (a,)
  1556. @array_function_dispatch(_shape_dispatcher)
  1557. def shape(a):
  1558. """
  1559. Return the shape of an array.
  1560. Parameters
  1561. ----------
  1562. a : array_like
  1563. Input array.
  1564. Returns
  1565. -------
  1566. shape : tuple of ints
  1567. The elements of the shape tuple give the lengths of the
  1568. corresponding array dimensions.
  1569. See Also
  1570. --------
  1571. len
  1572. ndarray.shape : Equivalent array method.
  1573. Examples
  1574. --------
  1575. >>> np.shape(np.eye(3))
  1576. (3, 3)
  1577. >>> np.shape([[1, 2]])
  1578. (1, 2)
  1579. >>> np.shape([0])
  1580. (1,)
  1581. >>> np.shape(0)
  1582. ()
  1583. >>> a = np.array([(1, 2), (3, 4)], dtype=[('x', 'i4'), ('y', 'i4')])
  1584. >>> np.shape(a)
  1585. (2,)
  1586. >>> a.shape
  1587. (2,)
  1588. """
  1589. try:
  1590. result = a.shape
  1591. except AttributeError:
  1592. result = asarray(a).shape
  1593. return result
  1594. def _compress_dispatcher(condition, a, axis=None, out=None):
  1595. return (condition, a, out)
  1596. @array_function_dispatch(_compress_dispatcher)
  1597. def compress(condition, a, axis=None, out=None):
  1598. """
  1599. Return selected slices of an array along given axis.
  1600. When working along a given axis, a slice along that axis is returned in
  1601. `output` for each index where `condition` evaluates to True. When
  1602. working on a 1-D array, `compress` is equivalent to `extract`.
  1603. Parameters
  1604. ----------
  1605. condition : 1-D array of bools
  1606. Array that selects which entries to return. If len(condition)
  1607. is less than the size of `a` along the given axis, then output is
  1608. truncated to the length of the condition array.
  1609. a : array_like
  1610. Array from which to extract a part.
  1611. axis : int, optional
  1612. Axis along which to take slices. If None (default), work on the
  1613. flattened array.
  1614. out : ndarray, optional
  1615. Output array. Its type is preserved and it must be of the right
  1616. shape to hold the output.
  1617. Returns
  1618. -------
  1619. compressed_array : ndarray
  1620. A copy of `a` without the slices along axis for which `condition`
  1621. is false.
  1622. See Also
  1623. --------
  1624. take, choose, diag, diagonal, select
  1625. ndarray.compress : Equivalent method in ndarray
  1626. extract : Equivalent method when working on 1-D arrays
  1627. :ref:`ufuncs-output-type`
  1628. Examples
  1629. --------
  1630. >>> a = np.array([[1, 2], [3, 4], [5, 6]])
  1631. >>> a
  1632. array([[1, 2],
  1633. [3, 4],
  1634. [5, 6]])
  1635. >>> np.compress([0, 1], a, axis=0)
  1636. array([[3, 4]])
  1637. >>> np.compress([False, True, True], a, axis=0)
  1638. array([[3, 4],
  1639. [5, 6]])
  1640. >>> np.compress([False, True], a, axis=1)
  1641. array([[2],
  1642. [4],
  1643. [6]])
  1644. Working on the flattened array does not return slices along an axis but
  1645. selects elements.
  1646. >>> np.compress([False, True], a)
  1647. array([2])
  1648. """
  1649. return _wrapfunc(a, 'compress', condition, axis=axis, out=out)
  1650. def _clip_dispatcher(a, a_min, a_max, out=None, **kwargs):
  1651. return (a, a_min, a_max)
  1652. @array_function_dispatch(_clip_dispatcher)
  1653. def clip(a, a_min, a_max, out=None, **kwargs):
  1654. """
  1655. Clip (limit) the values in an array.
  1656. Given an interval, values outside the interval are clipped to
  1657. the interval edges. For example, if an interval of ``[0, 1]``
  1658. is specified, values smaller than 0 become 0, and values larger
  1659. than 1 become 1.
  1660. Equivalent to but faster than ``np.minimum(a_max, np.maximum(a, a_min))``.
  1661. No check is performed to ensure ``a_min < a_max``.
  1662. Parameters
  1663. ----------
  1664. a : array_like
  1665. Array containing elements to clip.
  1666. a_min, a_max : array_like or None
  1667. Minimum and maximum value. If ``None``, clipping is not performed on
  1668. the corresponding edge. Only one of `a_min` and `a_max` may be
  1669. ``None``. Both are broadcast against `a`.
  1670. out : ndarray, optional
  1671. The results will be placed in this array. It may be the input
  1672. array for in-place clipping. `out` must be of the right shape
  1673. to hold the output. Its type is preserved.
  1674. **kwargs
  1675. For other keyword-only arguments, see the
  1676. :ref:`ufunc docs <ufuncs.kwargs>`.
  1677. .. versionadded:: 1.17.0
  1678. Returns
  1679. -------
  1680. clipped_array : ndarray
  1681. An array with the elements of `a`, but where values
  1682. < `a_min` are replaced with `a_min`, and those > `a_max`
  1683. with `a_max`.
  1684. See Also
  1685. --------
  1686. :ref:`ufuncs-output-type`
  1687. Notes
  1688. -----
  1689. When `a_min` is greater than `a_max`, `clip` returns an
  1690. array in which all values are equal to `a_max`,
  1691. as shown in the second example.
  1692. Examples
  1693. --------
  1694. >>> a = np.arange(10)
  1695. >>> a
  1696. array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
  1697. >>> np.clip(a, 1, 8)
  1698. array([1, 1, 2, 3, 4, 5, 6, 7, 8, 8])
  1699. >>> np.clip(a, 8, 1)
  1700. array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1])
  1701. >>> np.clip(a, 3, 6, out=a)
  1702. array([3, 3, 3, 3, 4, 5, 6, 6, 6, 6])
  1703. >>> a
  1704. array([3, 3, 3, 3, 4, 5, 6, 6, 6, 6])
  1705. >>> a = np.arange(10)
  1706. >>> a
  1707. array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
  1708. >>> np.clip(a, [3, 4, 1, 1, 1, 4, 4, 4, 4, 4], 8)
  1709. array([3, 4, 2, 3, 4, 5, 6, 7, 8, 8])
  1710. """
  1711. return _wrapfunc(a, 'clip', a_min, a_max, out=out, **kwargs)
  1712. def _sum_dispatcher(a, axis=None, dtype=None, out=None, keepdims=None,
  1713. initial=None, where=None):
  1714. return (a, out)
  1715. @array_function_dispatch(_sum_dispatcher)
  1716. def sum(a, axis=None, dtype=None, out=None, keepdims=np._NoValue,
  1717. initial=np._NoValue, where=np._NoValue):
  1718. """
  1719. Sum of array elements over a given axis.
  1720. Parameters
  1721. ----------
  1722. a : array_like
  1723. Elements to sum.
  1724. axis : None or int or tuple of ints, optional
  1725. Axis or axes along which a sum is performed. The default,
  1726. axis=None, will sum all of the elements of the input array. If
  1727. axis is negative it counts from the last to the first axis.
  1728. .. versionadded:: 1.7.0
  1729. If axis is a tuple of ints, a sum is performed on all of the axes
  1730. specified in the tuple instead of a single axis or all the axes as
  1731. before.
  1732. dtype : dtype, optional
  1733. The type of the returned array and of the accumulator in which the
  1734. elements are summed. The dtype of `a` is used by default unless `a`
  1735. has an integer dtype of less precision than the default platform
  1736. integer. In that case, if `a` is signed then the platform integer
  1737. is used while if `a` is unsigned then an unsigned integer of the
  1738. same precision as the platform integer is used.
  1739. out : ndarray, optional
  1740. Alternative output array in which to place the result. It must have
  1741. the same shape as the expected output, but the type of the output
  1742. values will be cast if necessary.
  1743. keepdims : bool, optional
  1744. If this is set to True, the axes which are reduced are left
  1745. in the result as dimensions with size one. With this option,
  1746. the result will broadcast correctly against the input array.
  1747. If the default value is passed, then `keepdims` will not be
  1748. passed through to the `sum` method of sub-classes of
  1749. `ndarray`, however any non-default value will be. If the
  1750. sub-class' method does not implement `keepdims` any
  1751. exceptions will be raised.
  1752. initial : scalar, optional
  1753. Starting value for the sum. See `~numpy.ufunc.reduce` for details.
  1754. .. versionadded:: 1.15.0
  1755. where : array_like of bool, optional
  1756. Elements to include in the sum. See `~numpy.ufunc.reduce` for details.
  1757. .. versionadded:: 1.17.0
  1758. Returns
  1759. -------
  1760. sum_along_axis : ndarray
  1761. An array with the same shape as `a`, with the specified
  1762. axis removed. If `a` is a 0-d array, or if `axis` is None, a scalar
  1763. is returned. If an output array is specified, a reference to
  1764. `out` is returned.
  1765. See Also
  1766. --------
  1767. ndarray.sum : Equivalent method.
  1768. add.reduce : Equivalent functionality of `add`.
  1769. cumsum : Cumulative sum of array elements.
  1770. trapz : Integration of array values using the composite trapezoidal rule.
  1771. mean, average
  1772. Notes
  1773. -----
  1774. Arithmetic is modular when using integer types, and no error is
  1775. raised on overflow.
  1776. The sum of an empty array is the neutral element 0:
  1777. >>> np.sum([])
  1778. 0.0
  1779. For floating point numbers the numerical precision of sum (and
  1780. ``np.add.reduce``) is in general limited by directly adding each number
  1781. individually to the result causing rounding errors in every step.
  1782. However, often numpy will use a numerically better approach (partial
  1783. pairwise summation) leading to improved precision in many use-cases.
  1784. This improved precision is always provided when no ``axis`` is given.
  1785. When ``axis`` is given, it will depend on which axis is summed.
  1786. Technically, to provide the best speed possible, the improved precision
  1787. is only used when the summation is along the fast axis in memory.
  1788. Note that the exact precision may vary depending on other parameters.
  1789. In contrast to NumPy, Python's ``math.fsum`` function uses a slower but
  1790. more precise approach to summation.
  1791. Especially when summing a large number of lower precision floating point
  1792. numbers, such as ``float32``, numerical errors can become significant.
  1793. In such cases it can be advisable to use `dtype="float64"` to use a higher
  1794. precision for the output.
  1795. Examples
  1796. --------
  1797. >>> np.sum([0.5, 1.5])
  1798. 2.0
  1799. >>> np.sum([0.5, 0.7, 0.2, 1.5], dtype=np.int32)
  1800. 1
  1801. >>> np.sum([[0, 1], [0, 5]])
  1802. 6
  1803. >>> np.sum([[0, 1], [0, 5]], axis=0)
  1804. array([0, 6])
  1805. >>> np.sum([[0, 1], [0, 5]], axis=1)
  1806. array([1, 5])
  1807. >>> np.sum([[0, 1], [np.nan, 5]], where=[False, True], axis=1)
  1808. array([1., 5.])
  1809. If the accumulator is too small, overflow occurs:
  1810. >>> np.ones(128, dtype=np.int8).sum(dtype=np.int8)
  1811. -128
  1812. You can also start the sum with a value other than zero:
  1813. >>> np.sum([10], initial=5)
  1814. 15
  1815. """
  1816. if isinstance(a, _gentype):
  1817. # 2018-02-25, 1.15.0
  1818. warnings.warn(
  1819. "Calling np.sum(generator) is deprecated, and in the future will give a different result. "
  1820. "Use np.sum(np.fromiter(generator)) or the python sum builtin instead.",
  1821. DeprecationWarning, stacklevel=3)
  1822. res = _sum_(a)
  1823. if out is not None:
  1824. out[...] = res
  1825. return out
  1826. return res
  1827. return _wrapreduction(a, np.add, 'sum', axis, dtype, out, keepdims=keepdims,
  1828. initial=initial, where=where)
  1829. def _any_dispatcher(a, axis=None, out=None, keepdims=None, *,
  1830. where=np._NoValue):
  1831. return (a, where, out)
  1832. @array_function_dispatch(_any_dispatcher)
  1833. def any(a, axis=None, out=None, keepdims=np._NoValue, *, where=np._NoValue):
  1834. """
  1835. Test whether any array element along a given axis evaluates to True.
  1836. Returns single boolean unless `axis` is not ``None``
  1837. Parameters
  1838. ----------
  1839. a : array_like
  1840. Input array or object that can be converted to an array.
  1841. axis : None or int or tuple of ints, optional
  1842. Axis or axes along which a logical OR reduction is performed.
  1843. The default (``axis=None``) is to perform a logical OR over all
  1844. the dimensions of the input array. `axis` may be negative, in
  1845. which case it counts from the last to the first axis.
  1846. .. versionadded:: 1.7.0
  1847. If this is a tuple of ints, a reduction is performed on multiple
  1848. axes, instead of a single axis or all the axes as before.
  1849. out : ndarray, optional
  1850. Alternate output array in which to place the result. It must have
  1851. the same shape as the expected output and its type is preserved
  1852. (e.g., if it is of type float, then it will remain so, returning
  1853. 1.0 for True and 0.0 for False, regardless of the type of `a`).
  1854. See :ref:`ufuncs-output-type` for more details.
  1855. keepdims : bool, optional
  1856. If this is set to True, the axes which are reduced are left
  1857. in the result as dimensions with size one. With this option,
  1858. the result will broadcast correctly against the input array.
  1859. If the default value is passed, then `keepdims` will not be
  1860. passed through to the `any` method of sub-classes of
  1861. `ndarray`, however any non-default value will be. If the
  1862. sub-class' method does not implement `keepdims` any
  1863. exceptions will be raised.
  1864. where : array_like of bool, optional
  1865. Elements to include in checking for any `True` values.
  1866. See `~numpy.ufunc.reduce` for details.
  1867. .. versionadded:: 1.20.0
  1868. Returns
  1869. -------
  1870. any : bool or ndarray
  1871. A new boolean or `ndarray` is returned unless `out` is specified,
  1872. in which case a reference to `out` is returned.
  1873. See Also
  1874. --------
  1875. ndarray.any : equivalent method
  1876. all : Test whether all elements along a given axis evaluate to True.
  1877. Notes
  1878. -----
  1879. Not a Number (NaN), positive infinity and negative infinity evaluate
  1880. to `True` because these are not equal to zero.
  1881. Examples
  1882. --------
  1883. >>> np.any([[True, False], [True, True]])
  1884. True
  1885. >>> np.any([[True, False], [False, False]], axis=0)
  1886. array([ True, False])
  1887. >>> np.any([-1, 0, 5])
  1888. True
  1889. >>> np.any(np.nan)
  1890. True
  1891. >>> np.any([[True, False], [False, False]], where=[[False], [True]])
  1892. False
  1893. >>> o=np.array(False)
  1894. >>> z=np.any([-1, 4, 5], out=o)
  1895. >>> z, o
  1896. (array(True), array(True))
  1897. >>> # Check now that z is a reference to o
  1898. >>> z is o
  1899. True
  1900. >>> id(z), id(o) # identity of z and o # doctest: +SKIP
  1901. (191614240, 191614240)
  1902. """
  1903. return _wrapreduction(a, np.logical_or, 'any', axis, None, out,
  1904. keepdims=keepdims, where=where)
  1905. def _all_dispatcher(a, axis=None, out=None, keepdims=None, *,
  1906. where=None):
  1907. return (a, where, out)
  1908. @array_function_dispatch(_all_dispatcher)
  1909. def all(a, axis=None, out=None, keepdims=np._NoValue, *, where=np._NoValue):
  1910. """
  1911. Test whether all array elements along a given axis evaluate to True.
  1912. Parameters
  1913. ----------
  1914. a : array_like
  1915. Input array or object that can be converted to an array.
  1916. axis : None or int or tuple of ints, optional
  1917. Axis or axes along which a logical AND reduction is performed.
  1918. The default (``axis=None``) is to perform a logical AND over all
  1919. the dimensions of the input array. `axis` may be negative, in
  1920. which case it counts from the last to the first axis.
  1921. .. versionadded:: 1.7.0
  1922. If this is a tuple of ints, a reduction is performed on multiple
  1923. axes, instead of a single axis or all the axes as before.
  1924. out : ndarray, optional
  1925. Alternate output array in which to place the result.
  1926. It must have the same shape as the expected output and its
  1927. type is preserved (e.g., if ``dtype(out)`` is float, the result
  1928. will consist of 0.0's and 1.0's). See :ref:`ufuncs-output-type` for more
  1929. details.
  1930. keepdims : bool, optional
  1931. If this is set to True, the axes which are reduced are left
  1932. in the result as dimensions with size one. With this option,
  1933. the result will broadcast correctly against the input array.
  1934. If the default value is passed, then `keepdims` will not be
  1935. passed through to the `all` method of sub-classes of
  1936. `ndarray`, however any non-default value will be. If the
  1937. sub-class' method does not implement `keepdims` any
  1938. exceptions will be raised.
  1939. where : array_like of bool, optional
  1940. Elements to include in checking for all `True` values.
  1941. See `~numpy.ufunc.reduce` for details.
  1942. .. versionadded:: 1.20.0
  1943. Returns
  1944. -------
  1945. all : ndarray, bool
  1946. A new boolean or array is returned unless `out` is specified,
  1947. in which case a reference to `out` is returned.
  1948. See Also
  1949. --------
  1950. ndarray.all : equivalent method
  1951. any : Test whether any element along a given axis evaluates to True.
  1952. Notes
  1953. -----
  1954. Not a Number (NaN), positive infinity and negative infinity
  1955. evaluate to `True` because these are not equal to zero.
  1956. Examples
  1957. --------
  1958. >>> np.all([[True,False],[True,True]])
  1959. False
  1960. >>> np.all([[True,False],[True,True]], axis=0)
  1961. array([ True, False])
  1962. >>> np.all([-1, 4, 5])
  1963. True
  1964. >>> np.all([1.0, np.nan])
  1965. True
  1966. >>> np.all([[True, True], [False, True]], where=[[True], [False]])
  1967. True
  1968. >>> o=np.array(False)
  1969. >>> z=np.all([-1, 4, 5], out=o)
  1970. >>> id(z), id(o), z
  1971. (28293632, 28293632, array(True)) # may vary
  1972. """
  1973. return _wrapreduction(a, np.logical_and, 'all', axis, None, out,
  1974. keepdims=keepdims, where=where)
  1975. def _cumsum_dispatcher(a, axis=None, dtype=None, out=None):
  1976. return (a, out)
  1977. @array_function_dispatch(_cumsum_dispatcher)
  1978. def cumsum(a, axis=None, dtype=None, out=None):
  1979. """
  1980. Return the cumulative sum of the elements along a given axis.
  1981. Parameters
  1982. ----------
  1983. a : array_like
  1984. Input array.
  1985. axis : int, optional
  1986. Axis along which the cumulative sum is computed. The default
  1987. (None) is to compute the cumsum over the flattened array.
  1988. dtype : dtype, optional
  1989. Type of the returned array and of the accumulator in which the
  1990. elements are summed. If `dtype` is not specified, it defaults
  1991. to the dtype of `a`, unless `a` has an integer dtype with a
  1992. precision less than that of the default platform integer. In
  1993. that case, the default platform integer is used.
  1994. out : ndarray, optional
  1995. Alternative output array in which to place the result. It must
  1996. have the same shape and buffer length as the expected output
  1997. but the type will be cast if necessary. See :ref:`ufuncs-output-type` for
  1998. more details.
  1999. Returns
  2000. -------
  2001. cumsum_along_axis : ndarray.
  2002. A new array holding the result is returned unless `out` is
  2003. specified, in which case a reference to `out` is returned. The
  2004. result has the same size as `a`, and the same shape as `a` if
  2005. `axis` is not None or `a` is a 1-d array.
  2006. See Also
  2007. --------
  2008. sum : Sum array elements.
  2009. trapz : Integration of array values using the composite trapezoidal rule.
  2010. diff : Calculate the n-th discrete difference along given axis.
  2011. Notes
  2012. -----
  2013. Arithmetic is modular when using integer types, and no error is
  2014. raised on overflow.
  2015. ``cumsum(a)[-1]`` may not be equal to ``sum(a)`` for floating-point
  2016. values since ``sum`` may use a pairwise summation routine, reducing
  2017. the roundoff-error. See `sum` for more information.
  2018. Examples
  2019. --------
  2020. >>> a = np.array([[1,2,3], [4,5,6]])
  2021. >>> a
  2022. array([[1, 2, 3],
  2023. [4, 5, 6]])
  2024. >>> np.cumsum(a)
  2025. array([ 1, 3, 6, 10, 15, 21])
  2026. >>> np.cumsum(a, dtype=float) # specifies type of output value(s)
  2027. array([ 1., 3., 6., 10., 15., 21.])
  2028. >>> np.cumsum(a,axis=0) # sum over rows for each of the 3 columns
  2029. array([[1, 2, 3],
  2030. [5, 7, 9]])
  2031. >>> np.cumsum(a,axis=1) # sum over columns for each of the 2 rows
  2032. array([[ 1, 3, 6],
  2033. [ 4, 9, 15]])
  2034. ``cumsum(b)[-1]`` may not be equal to ``sum(b)``
  2035. >>> b = np.array([1, 2e-9, 3e-9] * 1000000)
  2036. >>> b.cumsum()[-1]
  2037. 1000000.0050045159
  2038. >>> b.sum()
  2039. 1000000.0050000029
  2040. """
  2041. return _wrapfunc(a, 'cumsum', axis=axis, dtype=dtype, out=out)
  2042. def _ptp_dispatcher(a, axis=None, out=None, keepdims=None):
  2043. return (a, out)
  2044. @array_function_dispatch(_ptp_dispatcher)
  2045. def ptp(a, axis=None, out=None, keepdims=np._NoValue):
  2046. """
  2047. Range of values (maximum - minimum) along an axis.
  2048. The name of the function comes from the acronym for 'peak to peak'.
  2049. .. warning::
  2050. `ptp` preserves the data type of the array. This means the
  2051. return value for an input of signed integers with n bits
  2052. (e.g. `np.int8`, `np.int16`, etc) is also a signed integer
  2053. with n bits. In that case, peak-to-peak values greater than
  2054. ``2**(n-1)-1`` will be returned as negative values. An example
  2055. with a work-around is shown below.
  2056. Parameters
  2057. ----------
  2058. a : array_like
  2059. Input values.
  2060. axis : None or int or tuple of ints, optional
  2061. Axis along which to find the peaks. By default, flatten the
  2062. array. `axis` may be negative, in
  2063. which case it counts from the last to the first axis.
  2064. .. versionadded:: 1.15.0
  2065. If this is a tuple of ints, a reduction is performed on multiple
  2066. axes, instead of a single axis or all the axes as before.
  2067. out : array_like
  2068. Alternative output array in which to place the result. It must
  2069. have the same shape and buffer length as the expected output,
  2070. but the type of the output values will be cast if necessary.
  2071. keepdims : bool, optional
  2072. If this is set to True, the axes which are reduced are left
  2073. in the result as dimensions with size one. With this option,
  2074. the result will broadcast correctly against the input array.
  2075. If the default value is passed, then `keepdims` will not be
  2076. passed through to the `ptp` method of sub-classes of
  2077. `ndarray`, however any non-default value will be. If the
  2078. sub-class' method does not implement `keepdims` any
  2079. exceptions will be raised.
  2080. Returns
  2081. -------
  2082. ptp : ndarray
  2083. A new array holding the result, unless `out` was
  2084. specified, in which case a reference to `out` is returned.
  2085. Examples
  2086. --------
  2087. >>> x = np.array([[4, 9, 2, 10],
  2088. ... [6, 9, 7, 12]])
  2089. >>> np.ptp(x, axis=1)
  2090. array([8, 6])
  2091. >>> np.ptp(x, axis=0)
  2092. array([2, 0, 5, 2])
  2093. >>> np.ptp(x)
  2094. 10
  2095. This example shows that a negative value can be returned when
  2096. the input is an array of signed integers.
  2097. >>> y = np.array([[1, 127],
  2098. ... [0, 127],
  2099. ... [-1, 127],
  2100. ... [-2, 127]], dtype=np.int8)
  2101. >>> np.ptp(y, axis=1)
  2102. array([ 126, 127, -128, -127], dtype=int8)
  2103. A work-around is to use the `view()` method to view the result as
  2104. unsigned integers with the same bit width:
  2105. >>> np.ptp(y, axis=1).view(np.uint8)
  2106. array([126, 127, 128, 129], dtype=uint8)
  2107. """
  2108. kwargs = {}
  2109. if keepdims is not np._NoValue:
  2110. kwargs['keepdims'] = keepdims
  2111. if type(a) is not mu.ndarray:
  2112. try:
  2113. ptp = a.ptp
  2114. except AttributeError:
  2115. pass
  2116. else:
  2117. return ptp(axis=axis, out=out, **kwargs)
  2118. return _methods._ptp(a, axis=axis, out=out, **kwargs)
  2119. def _amax_dispatcher(a, axis=None, out=None, keepdims=None, initial=None,
  2120. where=None):
  2121. return (a, out)
  2122. @array_function_dispatch(_amax_dispatcher)
  2123. def amax(a, axis=None, out=None, keepdims=np._NoValue, initial=np._NoValue,
  2124. where=np._NoValue):
  2125. """
  2126. Return the maximum of an array or maximum along an axis.
  2127. Parameters
  2128. ----------
  2129. a : array_like
  2130. Input data.
  2131. axis : None or int or tuple of ints, optional
  2132. Axis or axes along which to operate. By default, flattened input is
  2133. used.
  2134. .. versionadded:: 1.7.0
  2135. If this is a tuple of ints, the maximum is selected over multiple axes,
  2136. instead of a single axis or all the axes as before.
  2137. out : ndarray, optional
  2138. Alternative output array in which to place the result. Must
  2139. be of the same shape and buffer length as the expected output.
  2140. See :ref:`ufuncs-output-type` for more details.
  2141. keepdims : bool, optional
  2142. If this is set to True, the axes which are reduced are left
  2143. in the result as dimensions with size one. With this option,
  2144. the result will broadcast correctly against the input array.
  2145. If the default value is passed, then `keepdims` will not be
  2146. passed through to the `amax` method of sub-classes of
  2147. `ndarray`, however any non-default value will be. If the
  2148. sub-class' method does not implement `keepdims` any
  2149. exceptions will be raised.
  2150. initial : scalar, optional
  2151. The minimum value of an output element. Must be present to allow
  2152. computation on empty slice. See `~numpy.ufunc.reduce` for details.
  2153. .. versionadded:: 1.15.0
  2154. where : array_like of bool, optional
  2155. Elements to compare for the maximum. See `~numpy.ufunc.reduce`
  2156. for details.
  2157. .. versionadded:: 1.17.0
  2158. Returns
  2159. -------
  2160. amax : ndarray or scalar
  2161. Maximum of `a`. If `axis` is None, the result is a scalar value.
  2162. If `axis` is given, the result is an array of dimension
  2163. ``a.ndim - 1``.
  2164. See Also
  2165. --------
  2166. amin :
  2167. The minimum value of an array along a given axis, propagating any NaNs.
  2168. nanmax :
  2169. The maximum value of an array along a given axis, ignoring any NaNs.
  2170. maximum :
  2171. Element-wise maximum of two arrays, propagating any NaNs.
  2172. fmax :
  2173. Element-wise maximum of two arrays, ignoring any NaNs.
  2174. argmax :
  2175. Return the indices of the maximum values.
  2176. nanmin, minimum, fmin
  2177. Notes
  2178. -----
  2179. NaN values are propagated, that is if at least one item is NaN, the
  2180. corresponding max value will be NaN as well. To ignore NaN values
  2181. (MATLAB behavior), please use nanmax.
  2182. Don't use `amax` for element-wise comparison of 2 arrays; when
  2183. ``a.shape[0]`` is 2, ``maximum(a[0], a[1])`` is faster than
  2184. ``amax(a, axis=0)``.
  2185. Examples
  2186. --------
  2187. >>> a = np.arange(4).reshape((2,2))
  2188. >>> a
  2189. array([[0, 1],
  2190. [2, 3]])
  2191. >>> np.amax(a) # Maximum of the flattened array
  2192. 3
  2193. >>> np.amax(a, axis=0) # Maxima along the first axis
  2194. array([2, 3])
  2195. >>> np.amax(a, axis=1) # Maxima along the second axis
  2196. array([1, 3])
  2197. >>> np.amax(a, where=[False, True], initial=-1, axis=0)
  2198. array([-1, 3])
  2199. >>> b = np.arange(5, dtype=float)
  2200. >>> b[2] = np.NaN
  2201. >>> np.amax(b)
  2202. nan
  2203. >>> np.amax(b, where=~np.isnan(b), initial=-1)
  2204. 4.0
  2205. >>> np.nanmax(b)
  2206. 4.0
  2207. You can use an initial value to compute the maximum of an empty slice, or
  2208. to initialize it to a different value:
  2209. >>> np.max([[-50], [10]], axis=-1, initial=0)
  2210. array([ 0, 10])
  2211. Notice that the initial value is used as one of the elements for which the
  2212. maximum is determined, unlike for the default argument Python's max
  2213. function, which is only used for empty iterables.
  2214. >>> np.max([5], initial=6)
  2215. 6
  2216. >>> max([5], default=6)
  2217. 5
  2218. """
  2219. return _wrapreduction(a, np.maximum, 'max', axis, None, out,
  2220. keepdims=keepdims, initial=initial, where=where)
  2221. def _amin_dispatcher(a, axis=None, out=None, keepdims=None, initial=None,
  2222. where=None):
  2223. return (a, out)
  2224. @array_function_dispatch(_amin_dispatcher)
  2225. def amin(a, axis=None, out=None, keepdims=np._NoValue, initial=np._NoValue,
  2226. where=np._NoValue):
  2227. """
  2228. Return the minimum of an array or minimum along an axis.
  2229. Parameters
  2230. ----------
  2231. a : array_like
  2232. Input data.
  2233. axis : None or int or tuple of ints, optional
  2234. Axis or axes along which to operate. By default, flattened input is
  2235. used.
  2236. .. versionadded:: 1.7.0
  2237. If this is a tuple of ints, the minimum is selected over multiple axes,
  2238. instead of a single axis or all the axes as before.
  2239. out : ndarray, optional
  2240. Alternative output array in which to place the result. Must
  2241. be of the same shape and buffer length as the expected output.
  2242. See :ref:`ufuncs-output-type` for more details.
  2243. keepdims : bool, optional
  2244. If this is set to True, the axes which are reduced are left
  2245. in the result as dimensions with size one. With this option,
  2246. the result will broadcast correctly against the input array.
  2247. If the default value is passed, then `keepdims` will not be
  2248. passed through to the `amin` method of sub-classes of
  2249. `ndarray`, however any non-default value will be. If the
  2250. sub-class' method does not implement `keepdims` any
  2251. exceptions will be raised.
  2252. initial : scalar, optional
  2253. The maximum value of an output element. Must be present to allow
  2254. computation on empty slice. See `~numpy.ufunc.reduce` for details.
  2255. .. versionadded:: 1.15.0
  2256. where : array_like of bool, optional
  2257. Elements to compare for the minimum. See `~numpy.ufunc.reduce`
  2258. for details.
  2259. .. versionadded:: 1.17.0
  2260. Returns
  2261. -------
  2262. amin : ndarray or scalar
  2263. Minimum of `a`. If `axis` is None, the result is a scalar value.
  2264. If `axis` is given, the result is an array of dimension
  2265. ``a.ndim - 1``.
  2266. See Also
  2267. --------
  2268. amax :
  2269. The maximum value of an array along a given axis, propagating any NaNs.
  2270. nanmin :
  2271. The minimum value of an array along a given axis, ignoring any NaNs.
  2272. minimum :
  2273. Element-wise minimum of two arrays, propagating any NaNs.
  2274. fmin :
  2275. Element-wise minimum of two arrays, ignoring any NaNs.
  2276. argmin :
  2277. Return the indices of the minimum values.
  2278. nanmax, maximum, fmax
  2279. Notes
  2280. -----
  2281. NaN values are propagated, that is if at least one item is NaN, the
  2282. corresponding min value will be NaN as well. To ignore NaN values
  2283. (MATLAB behavior), please use nanmin.
  2284. Don't use `amin` for element-wise comparison of 2 arrays; when
  2285. ``a.shape[0]`` is 2, ``minimum(a[0], a[1])`` is faster than
  2286. ``amin(a, axis=0)``.
  2287. Examples
  2288. --------
  2289. >>> a = np.arange(4).reshape((2,2))
  2290. >>> a
  2291. array([[0, 1],
  2292. [2, 3]])
  2293. >>> np.amin(a) # Minimum of the flattened array
  2294. 0
  2295. >>> np.amin(a, axis=0) # Minima along the first axis
  2296. array([0, 1])
  2297. >>> np.amin(a, axis=1) # Minima along the second axis
  2298. array([0, 2])
  2299. >>> np.amin(a, where=[False, True], initial=10, axis=0)
  2300. array([10, 1])
  2301. >>> b = np.arange(5, dtype=float)
  2302. >>> b[2] = np.NaN
  2303. >>> np.amin(b)
  2304. nan
  2305. >>> np.amin(b, where=~np.isnan(b), initial=10)
  2306. 0.0
  2307. >>> np.nanmin(b)
  2308. 0.0
  2309. >>> np.min([[-50], [10]], axis=-1, initial=0)
  2310. array([-50, 0])
  2311. Notice that the initial value is used as one of the elements for which the
  2312. minimum is determined, unlike for the default argument Python's max
  2313. function, which is only used for empty iterables.
  2314. Notice that this isn't the same as Python's ``default`` argument.
  2315. >>> np.min([6], initial=5)
  2316. 5
  2317. >>> min([6], default=5)
  2318. 6
  2319. """
  2320. return _wrapreduction(a, np.minimum, 'min', axis, None, out,
  2321. keepdims=keepdims, initial=initial, where=where)
  2322. def _alen_dispathcer(a):
  2323. return (a,)
  2324. @array_function_dispatch(_alen_dispathcer)
  2325. def alen(a):
  2326. """
  2327. Return the length of the first dimension of the input array.
  2328. .. deprecated:: 1.18
  2329. `numpy.alen` is deprecated, use `len` instead.
  2330. Parameters
  2331. ----------
  2332. a : array_like
  2333. Input array.
  2334. Returns
  2335. -------
  2336. alen : int
  2337. Length of the first dimension of `a`.
  2338. See Also
  2339. --------
  2340. shape, size
  2341. Examples
  2342. --------
  2343. >>> a = np.zeros((7,4,5))
  2344. >>> a.shape[0]
  2345. 7
  2346. >>> np.alen(a)
  2347. 7
  2348. """
  2349. # NumPy 1.18.0, 2019-08-02
  2350. warnings.warn(
  2351. "`np.alen` is deprecated, use `len` instead",
  2352. DeprecationWarning, stacklevel=2)
  2353. try:
  2354. return len(a)
  2355. except TypeError:
  2356. return len(array(a, ndmin=1))
  2357. def _prod_dispatcher(a, axis=None, dtype=None, out=None, keepdims=None,
  2358. initial=None, where=None):
  2359. return (a, out)
  2360. @array_function_dispatch(_prod_dispatcher)
  2361. def prod(a, axis=None, dtype=None, out=None, keepdims=np._NoValue,
  2362. initial=np._NoValue, where=np._NoValue):
  2363. """
  2364. Return the product of array elements over a given axis.
  2365. Parameters
  2366. ----------
  2367. a : array_like
  2368. Input data.
  2369. axis : None or int or tuple of ints, optional
  2370. Axis or axes along which a product is performed. The default,
  2371. axis=None, will calculate the product of all the elements in the
  2372. input array. If axis is negative it counts from the last to the
  2373. first axis.
  2374. .. versionadded:: 1.7.0
  2375. If axis is a tuple of ints, a product is performed on all of the
  2376. axes specified in the tuple instead of a single axis or all the
  2377. axes as before.
  2378. dtype : dtype, optional
  2379. The type of the returned array, as well as of the accumulator in
  2380. which the elements are multiplied. The dtype of `a` is used by
  2381. default unless `a` has an integer dtype of less precision than the
  2382. default platform integer. In that case, if `a` is signed then the
  2383. platform integer is used while if `a` is unsigned then an unsigned
  2384. integer of the same precision as the platform integer is used.
  2385. out : ndarray, optional
  2386. Alternative output array in which to place the result. It must have
  2387. the same shape as the expected output, but the type of the output
  2388. values will be cast if necessary.
  2389. keepdims : bool, optional
  2390. If this is set to True, the axes which are reduced are left in the
  2391. result as dimensions with size one. With this option, the result
  2392. will broadcast correctly against the input array.
  2393. If the default value is passed, then `keepdims` will not be
  2394. passed through to the `prod` method of sub-classes of
  2395. `ndarray`, however any non-default value will be. If the
  2396. sub-class' method does not implement `keepdims` any
  2397. exceptions will be raised.
  2398. initial : scalar, optional
  2399. The starting value for this product. See `~numpy.ufunc.reduce` for details.
  2400. .. versionadded:: 1.15.0
  2401. where : array_like of bool, optional
  2402. Elements to include in the product. See `~numpy.ufunc.reduce` for details.
  2403. .. versionadded:: 1.17.0
  2404. Returns
  2405. -------
  2406. product_along_axis : ndarray, see `dtype` parameter above.
  2407. An array shaped as `a` but with the specified axis removed.
  2408. Returns a reference to `out` if specified.
  2409. See Also
  2410. --------
  2411. ndarray.prod : equivalent method
  2412. :ref:`ufuncs-output-type`
  2413. Notes
  2414. -----
  2415. Arithmetic is modular when using integer types, and no error is
  2416. raised on overflow. That means that, on a 32-bit platform:
  2417. >>> x = np.array([536870910, 536870910, 536870910, 536870910])
  2418. >>> np.prod(x)
  2419. 16 # may vary
  2420. The product of an empty array is the neutral element 1:
  2421. >>> np.prod([])
  2422. 1.0
  2423. Examples
  2424. --------
  2425. By default, calculate the product of all elements:
  2426. >>> np.prod([1.,2.])
  2427. 2.0
  2428. Even when the input array is two-dimensional:
  2429. >>> np.prod([[1.,2.],[3.,4.]])
  2430. 24.0
  2431. But we can also specify the axis over which to multiply:
  2432. >>> np.prod([[1.,2.],[3.,4.]], axis=1)
  2433. array([ 2., 12.])
  2434. Or select specific elements to include:
  2435. >>> np.prod([1., np.nan, 3.], where=[True, False, True])
  2436. 3.0
  2437. If the type of `x` is unsigned, then the output type is
  2438. the unsigned platform integer:
  2439. >>> x = np.array([1, 2, 3], dtype=np.uint8)
  2440. >>> np.prod(x).dtype == np.uint
  2441. True
  2442. If `x` is of a signed integer type, then the output type
  2443. is the default platform integer:
  2444. >>> x = np.array([1, 2, 3], dtype=np.int8)
  2445. >>> np.prod(x).dtype == int
  2446. True
  2447. You can also start the product with a value other than one:
  2448. >>> np.prod([1, 2], initial=5)
  2449. 10
  2450. """
  2451. return _wrapreduction(a, np.multiply, 'prod', axis, dtype, out,
  2452. keepdims=keepdims, initial=initial, where=where)
  2453. def _cumprod_dispatcher(a, axis=None, dtype=None, out=None):
  2454. return (a, out)
  2455. @array_function_dispatch(_cumprod_dispatcher)
  2456. def cumprod(a, axis=None, dtype=None, out=None):
  2457. """
  2458. Return the cumulative product of elements along a given axis.
  2459. Parameters
  2460. ----------
  2461. a : array_like
  2462. Input array.
  2463. axis : int, optional
  2464. Axis along which the cumulative product is computed. By default
  2465. the input is flattened.
  2466. dtype : dtype, optional
  2467. Type of the returned array, as well as of the accumulator in which
  2468. the elements are multiplied. If *dtype* is not specified, it
  2469. defaults to the dtype of `a`, unless `a` has an integer dtype with
  2470. a precision less than that of the default platform integer. In
  2471. that case, the default platform integer is used instead.
  2472. out : ndarray, optional
  2473. Alternative output array in which to place the result. It must
  2474. have the same shape and buffer length as the expected output
  2475. but the type of the resulting values will be cast if necessary.
  2476. Returns
  2477. -------
  2478. cumprod : ndarray
  2479. A new array holding the result is returned unless `out` is
  2480. specified, in which case a reference to out is returned.
  2481. See Also
  2482. --------
  2483. :ref:`ufuncs-output-type`
  2484. Notes
  2485. -----
  2486. Arithmetic is modular when using integer types, and no error is
  2487. raised on overflow.
  2488. Examples
  2489. --------
  2490. >>> a = np.array([1,2,3])
  2491. >>> np.cumprod(a) # intermediate results 1, 1*2
  2492. ... # total product 1*2*3 = 6
  2493. array([1, 2, 6])
  2494. >>> a = np.array([[1, 2, 3], [4, 5, 6]])
  2495. >>> np.cumprod(a, dtype=float) # specify type of output
  2496. array([ 1., 2., 6., 24., 120., 720.])
  2497. The cumulative product for each column (i.e., over the rows) of `a`:
  2498. >>> np.cumprod(a, axis=0)
  2499. array([[ 1, 2, 3],
  2500. [ 4, 10, 18]])
  2501. The cumulative product for each row (i.e. over the columns) of `a`:
  2502. >>> np.cumprod(a,axis=1)
  2503. array([[ 1, 2, 6],
  2504. [ 4, 20, 120]])
  2505. """
  2506. return _wrapfunc(a, 'cumprod', axis=axis, dtype=dtype, out=out)
  2507. def _ndim_dispatcher(a):
  2508. return (a,)
  2509. @array_function_dispatch(_ndim_dispatcher)
  2510. def ndim(a):
  2511. """
  2512. Return the number of dimensions of an array.
  2513. Parameters
  2514. ----------
  2515. a : array_like
  2516. Input array. If it is not already an ndarray, a conversion is
  2517. attempted.
  2518. Returns
  2519. -------
  2520. number_of_dimensions : int
  2521. The number of dimensions in `a`. Scalars are zero-dimensional.
  2522. See Also
  2523. --------
  2524. ndarray.ndim : equivalent method
  2525. shape : dimensions of array
  2526. ndarray.shape : dimensions of array
  2527. Examples
  2528. --------
  2529. >>> np.ndim([[1,2,3],[4,5,6]])
  2530. 2
  2531. >>> np.ndim(np.array([[1,2,3],[4,5,6]]))
  2532. 2
  2533. >>> np.ndim(1)
  2534. 0
  2535. """
  2536. try:
  2537. return a.ndim
  2538. except AttributeError:
  2539. return asarray(a).ndim
  2540. def _size_dispatcher(a, axis=None):
  2541. return (a,)
  2542. @array_function_dispatch(_size_dispatcher)
  2543. def size(a, axis=None):
  2544. """
  2545. Return the number of elements along a given axis.
  2546. Parameters
  2547. ----------
  2548. a : array_like
  2549. Input data.
  2550. axis : int, optional
  2551. Axis along which the elements are counted. By default, give
  2552. the total number of elements.
  2553. Returns
  2554. -------
  2555. element_count : int
  2556. Number of elements along the specified axis.
  2557. See Also
  2558. --------
  2559. shape : dimensions of array
  2560. ndarray.shape : dimensions of array
  2561. ndarray.size : number of elements in array
  2562. Examples
  2563. --------
  2564. >>> a = np.array([[1,2,3],[4,5,6]])
  2565. >>> np.size(a)
  2566. 6
  2567. >>> np.size(a,1)
  2568. 3
  2569. >>> np.size(a,0)
  2570. 2
  2571. """
  2572. if axis is None:
  2573. try:
  2574. return a.size
  2575. except AttributeError:
  2576. return asarray(a).size
  2577. else:
  2578. try:
  2579. return a.shape[axis]
  2580. except AttributeError:
  2581. return asarray(a).shape[axis]
  2582. def _around_dispatcher(a, decimals=None, out=None):
  2583. return (a, out)
  2584. @array_function_dispatch(_around_dispatcher)
  2585. def around(a, decimals=0, out=None):
  2586. """
  2587. Evenly round to the given number of decimals.
  2588. Parameters
  2589. ----------
  2590. a : array_like
  2591. Input data.
  2592. decimals : int, optional
  2593. Number of decimal places to round to (default: 0). If
  2594. decimals is negative, it specifies the number of positions to
  2595. the left of the decimal point.
  2596. out : ndarray, optional
  2597. Alternative output array in which to place the result. It must have
  2598. the same shape as the expected output, but the type of the output
  2599. values will be cast if necessary. See :ref:`ufuncs-output-type` for more
  2600. details.
  2601. Returns
  2602. -------
  2603. rounded_array : ndarray
  2604. An array of the same type as `a`, containing the rounded values.
  2605. Unless `out` was specified, a new array is created. A reference to
  2606. the result is returned.
  2607. The real and imaginary parts of complex numbers are rounded
  2608. separately. The result of rounding a float is a float.
  2609. See Also
  2610. --------
  2611. ndarray.round : equivalent method
  2612. ceil, fix, floor, rint, trunc
  2613. Notes
  2614. -----
  2615. For values exactly halfway between rounded decimal values, NumPy
  2616. rounds to the nearest even value. Thus 1.5 and 2.5 round to 2.0,
  2617. -0.5 and 0.5 round to 0.0, etc.
  2618. ``np.around`` uses a fast but sometimes inexact algorithm to round
  2619. floating-point datatypes. For positive `decimals` it is equivalent to
  2620. ``np.true_divide(np.rint(a * 10**decimals), 10**decimals)``, which has
  2621. error due to the inexact representation of decimal fractions in the IEEE
  2622. floating point standard [1]_ and errors introduced when scaling by powers
  2623. of ten. For instance, note the extra "1" in the following:
  2624. >>> np.round(56294995342131.5, 3)
  2625. 56294995342131.51
  2626. If your goal is to print such values with a fixed number of decimals, it is
  2627. preferable to use numpy's float printing routines to limit the number of
  2628. printed decimals:
  2629. >>> np.format_float_positional(56294995342131.5, precision=3)
  2630. '56294995342131.5'
  2631. The float printing routines use an accurate but much more computationally
  2632. demanding algorithm to compute the number of digits after the decimal
  2633. point.
  2634. Alternatively, Python's builtin `round` function uses a more accurate
  2635. but slower algorithm for 64-bit floating point values:
  2636. >>> round(56294995342131.5, 3)
  2637. 56294995342131.5
  2638. >>> np.round(16.055, 2), round(16.055, 2) # equals 16.0549999999999997
  2639. (16.06, 16.05)
  2640. References
  2641. ----------
  2642. .. [1] "Lecture Notes on the Status of IEEE 754", William Kahan,
  2643. https://people.eecs.berkeley.edu/~wkahan/ieee754status/IEEE754.PDF
  2644. .. [2] "How Futile are Mindless Assessments of
  2645. Roundoff in Floating-Point Computation?", William Kahan,
  2646. https://people.eecs.berkeley.edu/~wkahan/Mindless.pdf
  2647. Examples
  2648. --------
  2649. >>> np.around([0.37, 1.64])
  2650. array([0., 2.])
  2651. >>> np.around([0.37, 1.64], decimals=1)
  2652. array([0.4, 1.6])
  2653. >>> np.around([.5, 1.5, 2.5, 3.5, 4.5]) # rounds to nearest even value
  2654. array([0., 2., 2., 4., 4.])
  2655. >>> np.around([1,2,3,11], decimals=1) # ndarray of ints is returned
  2656. array([ 1, 2, 3, 11])
  2657. >>> np.around([1,2,3,11], decimals=-1)
  2658. array([ 0, 0, 0, 10])
  2659. """
  2660. return _wrapfunc(a, 'round', decimals=decimals, out=out)
  2661. def _mean_dispatcher(a, axis=None, dtype=None, out=None, keepdims=None, *,
  2662. where=None):
  2663. return (a, where, out)
  2664. @array_function_dispatch(_mean_dispatcher)
  2665. def mean(a, axis=None, dtype=None, out=None, keepdims=np._NoValue, *,
  2666. where=np._NoValue):
  2667. """
  2668. Compute the arithmetic mean along the specified axis.
  2669. Returns the average of the array elements. The average is taken over
  2670. the flattened array by default, otherwise over the specified axis.
  2671. `float64` intermediate and return values are used for integer inputs.
  2672. Parameters
  2673. ----------
  2674. a : array_like
  2675. Array containing numbers whose mean is desired. If `a` is not an
  2676. array, a conversion is attempted.
  2677. axis : None or int or tuple of ints, optional
  2678. Axis or axes along which the means are computed. The default is to
  2679. compute the mean of the flattened array.
  2680. .. versionadded:: 1.7.0
  2681. If this is a tuple of ints, a mean is performed over multiple axes,
  2682. instead of a single axis or all the axes as before.
  2683. dtype : data-type, optional
  2684. Type to use in computing the mean. For integer inputs, the default
  2685. is `float64`; for floating point inputs, it is the same as the
  2686. input dtype.
  2687. out : ndarray, optional
  2688. Alternate output array in which to place the result. The default
  2689. is ``None``; if provided, it must have the same shape as the
  2690. expected output, but the type will be cast if necessary.
  2691. See :ref:`ufuncs-output-type` for more details.
  2692. keepdims : bool, optional
  2693. If this is set to True, the axes which are reduced are left
  2694. in the result as dimensions with size one. With this option,
  2695. the result will broadcast correctly against the input array.
  2696. If the default value is passed, then `keepdims` will not be
  2697. passed through to the `mean` method of sub-classes of
  2698. `ndarray`, however any non-default value will be. If the
  2699. sub-class' method does not implement `keepdims` any
  2700. exceptions will be raised.
  2701. where : array_like of bool, optional
  2702. Elements to include in the mean. See `~numpy.ufunc.reduce` for details.
  2703. .. versionadded:: 1.20.0
  2704. Returns
  2705. -------
  2706. m : ndarray, see dtype parameter above
  2707. If `out=None`, returns a new array containing the mean values,
  2708. otherwise a reference to the output array is returned.
  2709. See Also
  2710. --------
  2711. average : Weighted average
  2712. std, var, nanmean, nanstd, nanvar
  2713. Notes
  2714. -----
  2715. The arithmetic mean is the sum of the elements along the axis divided
  2716. by the number of elements.
  2717. Note that for floating-point input, the mean is computed using the
  2718. same precision the input has. Depending on the input data, this can
  2719. cause the results to be inaccurate, especially for `float32` (see
  2720. example below). Specifying a higher-precision accumulator using the
  2721. `dtype` keyword can alleviate this issue.
  2722. By default, `float16` results are computed using `float32` intermediates
  2723. for extra precision.
  2724. Examples
  2725. --------
  2726. >>> a = np.array([[1, 2], [3, 4]])
  2727. >>> np.mean(a)
  2728. 2.5
  2729. >>> np.mean(a, axis=0)
  2730. array([2., 3.])
  2731. >>> np.mean(a, axis=1)
  2732. array([1.5, 3.5])
  2733. In single precision, `mean` can be inaccurate:
  2734. >>> a = np.zeros((2, 512*512), dtype=np.float32)
  2735. >>> a[0, :] = 1.0
  2736. >>> a[1, :] = 0.1
  2737. >>> np.mean(a)
  2738. 0.54999924
  2739. Computing the mean in float64 is more accurate:
  2740. >>> np.mean(a, dtype=np.float64)
  2741. 0.55000000074505806 # may vary
  2742. Specifying a where argument:
  2743. >>> a = np.array([[5, 9, 13], [14, 10, 12], [11, 15, 19]])
  2744. >>> np.mean(a)
  2745. 12.0
  2746. >>> np.mean(a, where=[[True], [False], [False]])
  2747. 9.0
  2748. """
  2749. kwargs = {}
  2750. if keepdims is not np._NoValue:
  2751. kwargs['keepdims'] = keepdims
  2752. if where is not np._NoValue:
  2753. kwargs['where'] = where
  2754. if type(a) is not mu.ndarray:
  2755. try:
  2756. mean = a.mean
  2757. except AttributeError:
  2758. pass
  2759. else:
  2760. return mean(axis=axis, dtype=dtype, out=out, **kwargs)
  2761. return _methods._mean(a, axis=axis, dtype=dtype,
  2762. out=out, **kwargs)
  2763. def _std_dispatcher(a, axis=None, dtype=None, out=None, ddof=None,
  2764. keepdims=None, *, where=None):
  2765. return (a, where, out)
  2766. @array_function_dispatch(_std_dispatcher)
  2767. def std(a, axis=None, dtype=None, out=None, ddof=0, keepdims=np._NoValue, *,
  2768. where=np._NoValue):
  2769. """
  2770. Compute the standard deviation along the specified axis.
  2771. Returns the standard deviation, a measure of the spread of a distribution,
  2772. of the array elements. The standard deviation is computed for the
  2773. flattened array by default, otherwise over the specified axis.
  2774. Parameters
  2775. ----------
  2776. a : array_like
  2777. Calculate the standard deviation of these values.
  2778. axis : None or int or tuple of ints, optional
  2779. Axis or axes along which the standard deviation is computed. The
  2780. default is to compute the standard deviation of the flattened array.
  2781. .. versionadded:: 1.7.0
  2782. If this is a tuple of ints, a standard deviation is performed over
  2783. multiple axes, instead of a single axis or all the axes as before.
  2784. dtype : dtype, optional
  2785. Type to use in computing the standard deviation. For arrays of
  2786. integer type the default is float64, for arrays of float types it is
  2787. the same as the array type.
  2788. out : ndarray, optional
  2789. Alternative output array in which to place the result. It must have
  2790. the same shape as the expected output but the type (of the calculated
  2791. values) will be cast if necessary.
  2792. ddof : int, optional
  2793. Means Delta Degrees of Freedom. The divisor used in calculations
  2794. is ``N - ddof``, where ``N`` represents the number of elements.
  2795. By default `ddof` is zero.
  2796. keepdims : bool, optional
  2797. If this is set to True, the axes which are reduced are left
  2798. in the result as dimensions with size one. With this option,
  2799. the result will broadcast correctly against the input array.
  2800. If the default value is passed, then `keepdims` will not be
  2801. passed through to the `std` method of sub-classes of
  2802. `ndarray`, however any non-default value will be. If the
  2803. sub-class' method does not implement `keepdims` any
  2804. exceptions will be raised.
  2805. where : array_like of bool, optional
  2806. Elements to include in the standard deviation.
  2807. See `~numpy.ufunc.reduce` for details.
  2808. .. versionadded:: 1.20.0
  2809. Returns
  2810. -------
  2811. standard_deviation : ndarray, see dtype parameter above.
  2812. If `out` is None, return a new array containing the standard deviation,
  2813. otherwise return a reference to the output array.
  2814. See Also
  2815. --------
  2816. var, mean, nanmean, nanstd, nanvar
  2817. :ref:`ufuncs-output-type`
  2818. Notes
  2819. -----
  2820. The standard deviation is the square root of the average of the squared
  2821. deviations from the mean, i.e., ``std = sqrt(mean(x))``, where
  2822. ``x = abs(a - a.mean())**2``.
  2823. The average squared deviation is typically calculated as ``x.sum() / N``,
  2824. where ``N = len(x)``. If, however, `ddof` is specified, the divisor
  2825. ``N - ddof`` is used instead. In standard statistical practice, ``ddof=1``
  2826. provides an unbiased estimator of the variance of the infinite population.
  2827. ``ddof=0`` provides a maximum likelihood estimate of the variance for
  2828. normally distributed variables. The standard deviation computed in this
  2829. function is the square root of the estimated variance, so even with
  2830. ``ddof=1``, it will not be an unbiased estimate of the standard deviation
  2831. per se.
  2832. Note that, for complex numbers, `std` takes the absolute
  2833. value before squaring, so that the result is always real and nonnegative.
  2834. For floating-point input, the *std* is computed using the same
  2835. precision the input has. Depending on the input data, this can cause
  2836. the results to be inaccurate, especially for float32 (see example below).
  2837. Specifying a higher-accuracy accumulator using the `dtype` keyword can
  2838. alleviate this issue.
  2839. Examples
  2840. --------
  2841. >>> a = np.array([[1, 2], [3, 4]])
  2842. >>> np.std(a)
  2843. 1.1180339887498949 # may vary
  2844. >>> np.std(a, axis=0)
  2845. array([1., 1.])
  2846. >>> np.std(a, axis=1)
  2847. array([0.5, 0.5])
  2848. In single precision, std() can be inaccurate:
  2849. >>> a = np.zeros((2, 512*512), dtype=np.float32)
  2850. >>> a[0, :] = 1.0
  2851. >>> a[1, :] = 0.1
  2852. >>> np.std(a)
  2853. 0.45000005
  2854. Computing the standard deviation in float64 is more accurate:
  2855. >>> np.std(a, dtype=np.float64)
  2856. 0.44999999925494177 # may vary
  2857. Specifying a where argument:
  2858. >>> a = np.array([[14, 8, 11, 10], [7, 9, 10, 11], [10, 15, 5, 10]])
  2859. >>> np.std(a)
  2860. 2.614064523559687 # may vary
  2861. >>> np.std(a, where=[[True], [True], [False]])
  2862. 2.0
  2863. """
  2864. kwargs = {}
  2865. if keepdims is not np._NoValue:
  2866. kwargs['keepdims'] = keepdims
  2867. if where is not np._NoValue:
  2868. kwargs['where'] = where
  2869. if type(a) is not mu.ndarray:
  2870. try:
  2871. std = a.std
  2872. except AttributeError:
  2873. pass
  2874. else:
  2875. return std(axis=axis, dtype=dtype, out=out, ddof=ddof, **kwargs)
  2876. return _methods._std(a, axis=axis, dtype=dtype, out=out, ddof=ddof,
  2877. **kwargs)
  2878. def _var_dispatcher(a, axis=None, dtype=None, out=None, ddof=None,
  2879. keepdims=None, *, where=None):
  2880. return (a, where, out)
  2881. @array_function_dispatch(_var_dispatcher)
  2882. def var(a, axis=None, dtype=None, out=None, ddof=0, keepdims=np._NoValue, *,
  2883. where=np._NoValue):
  2884. """
  2885. Compute the variance along the specified axis.
  2886. Returns the variance of the array elements, a measure of the spread of a
  2887. distribution. The variance is computed for the flattened array by
  2888. default, otherwise over the specified axis.
  2889. Parameters
  2890. ----------
  2891. a : array_like
  2892. Array containing numbers whose variance is desired. If `a` is not an
  2893. array, a conversion is attempted.
  2894. axis : None or int or tuple of ints, optional
  2895. Axis or axes along which the variance is computed. The default is to
  2896. compute the variance of the flattened array.
  2897. .. versionadded:: 1.7.0
  2898. If this is a tuple of ints, a variance is performed over multiple axes,
  2899. instead of a single axis or all the axes as before.
  2900. dtype : data-type, optional
  2901. Type to use in computing the variance. For arrays of integer type
  2902. the default is `float64`; for arrays of float types it is the same as
  2903. the array type.
  2904. out : ndarray, optional
  2905. Alternate output array in which to place the result. It must have
  2906. the same shape as the expected output, but the type is cast if
  2907. necessary.
  2908. ddof : int, optional
  2909. "Delta Degrees of Freedom": the divisor used in the calculation is
  2910. ``N - ddof``, where ``N`` represents the number of elements. By
  2911. default `ddof` is zero.
  2912. keepdims : bool, optional
  2913. If this is set to True, the axes which are reduced are left
  2914. in the result as dimensions with size one. With this option,
  2915. the result will broadcast correctly against the input array.
  2916. If the default value is passed, then `keepdims` will not be
  2917. passed through to the `var` method of sub-classes of
  2918. `ndarray`, however any non-default value will be. If the
  2919. sub-class' method does not implement `keepdims` any
  2920. exceptions will be raised.
  2921. where : array_like of bool, optional
  2922. Elements to include in the variance. See `~numpy.ufunc.reduce` for
  2923. details.
  2924. .. versionadded:: 1.20.0
  2925. Returns
  2926. -------
  2927. variance : ndarray, see dtype parameter above
  2928. If ``out=None``, returns a new array containing the variance;
  2929. otherwise, a reference to the output array is returned.
  2930. See Also
  2931. --------
  2932. std, mean, nanmean, nanstd, nanvar
  2933. :ref:`ufuncs-output-type`
  2934. Notes
  2935. -----
  2936. The variance is the average of the squared deviations from the mean,
  2937. i.e., ``var = mean(x)``, where ``x = abs(a - a.mean())**2``.
  2938. The mean is typically calculated as ``x.sum() / N``, where ``N = len(x)``.
  2939. If, however, `ddof` is specified, the divisor ``N - ddof`` is used
  2940. instead. In standard statistical practice, ``ddof=1`` provides an
  2941. unbiased estimator of the variance of a hypothetical infinite population.
  2942. ``ddof=0`` provides a maximum likelihood estimate of the variance for
  2943. normally distributed variables.
  2944. Note that for complex numbers, the absolute value is taken before
  2945. squaring, so that the result is always real and nonnegative.
  2946. For floating-point input, the variance is computed using the same
  2947. precision the input has. Depending on the input data, this can cause
  2948. the results to be inaccurate, especially for `float32` (see example
  2949. below). Specifying a higher-accuracy accumulator using the ``dtype``
  2950. keyword can alleviate this issue.
  2951. Examples
  2952. --------
  2953. >>> a = np.array([[1, 2], [3, 4]])
  2954. >>> np.var(a)
  2955. 1.25
  2956. >>> np.var(a, axis=0)
  2957. array([1., 1.])
  2958. >>> np.var(a, axis=1)
  2959. array([0.25, 0.25])
  2960. In single precision, var() can be inaccurate:
  2961. >>> a = np.zeros((2, 512*512), dtype=np.float32)
  2962. >>> a[0, :] = 1.0
  2963. >>> a[1, :] = 0.1
  2964. >>> np.var(a)
  2965. 0.20250003
  2966. Computing the variance in float64 is more accurate:
  2967. >>> np.var(a, dtype=np.float64)
  2968. 0.20249999932944759 # may vary
  2969. >>> ((1-0.55)**2 + (0.1-0.55)**2)/2
  2970. 0.2025
  2971. Specifying a where argument:
  2972. >>> a = np.array([[14, 8, 11, 10], [7, 9, 10, 11], [10, 15, 5, 10]])
  2973. >>> np.var(a)
  2974. 6.833333333333333 # may vary
  2975. >>> np.var(a, where=[[True], [True], [False]])
  2976. 4.0
  2977. """
  2978. kwargs = {}
  2979. if keepdims is not np._NoValue:
  2980. kwargs['keepdims'] = keepdims
  2981. if where is not np._NoValue:
  2982. kwargs['where'] = where
  2983. if type(a) is not mu.ndarray:
  2984. try:
  2985. var = a.var
  2986. except AttributeError:
  2987. pass
  2988. else:
  2989. return var(axis=axis, dtype=dtype, out=out, ddof=ddof, **kwargs)
  2990. return _methods._var(a, axis=axis, dtype=dtype, out=out, ddof=ddof,
  2991. **kwargs)
  2992. # Aliases of other functions. These have their own definitions only so that
  2993. # they can have unique docstrings.
  2994. @array_function_dispatch(_around_dispatcher)
  2995. def round_(a, decimals=0, out=None):
  2996. """
  2997. Round an array to the given number of decimals.
  2998. See Also
  2999. --------
  3000. around : equivalent function; see for details.
  3001. """
  3002. return around(a, decimals=decimals, out=out)
  3003. @array_function_dispatch(_prod_dispatcher, verify=False)
  3004. def product(*args, **kwargs):
  3005. """
  3006. Return the product of array elements over a given axis.
  3007. See Also
  3008. --------
  3009. prod : equivalent function; see for details.
  3010. """
  3011. return prod(*args, **kwargs)
  3012. @array_function_dispatch(_cumprod_dispatcher, verify=False)
  3013. def cumproduct(*args, **kwargs):
  3014. """
  3015. Return the cumulative product over the given axis.
  3016. See Also
  3017. --------
  3018. cumprod : equivalent function; see for details.
  3019. """
  3020. return cumprod(*args, **kwargs)
  3021. @array_function_dispatch(_any_dispatcher, verify=False)
  3022. def sometrue(*args, **kwargs):
  3023. """
  3024. Check whether some values are true.
  3025. Refer to `any` for full documentation.
  3026. See Also
  3027. --------
  3028. any : equivalent function; see for details.
  3029. """
  3030. return any(*args, **kwargs)
  3031. @array_function_dispatch(_all_dispatcher, verify=False)
  3032. def alltrue(*args, **kwargs):
  3033. """
  3034. Check if all elements of input array are true.
  3035. See Also
  3036. --------
  3037. numpy.all : Equivalent function; see for details.
  3038. """
  3039. return all(*args, **kwargs)