PageRenderTime 60ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 0ms

/lib_pypy/numpypy/core/fromnumeric.py

https://bitbucket.org/dac_io/pypy
Python | 2430 lines | 2405 code | 4 blank | 21 comment | 0 complexity | 8e934aa8fc799b8acaadc122af413ee6 MD5 | raw file
  1. ######################################################################
  2. # This is a copy of numpy/core/fromnumeric.py modified for numpypy
  3. ######################################################################
  4. # Each name in __all__ was a function in 'numeric' that is now
  5. # a method in 'numpy'.
  6. # When the corresponding method is added to numpypy BaseArray
  7. # each function should be added as a module function
  8. # at the applevel
  9. # This can be as simple as doing the following
  10. #
  11. # def func(a, ...):
  12. # if not hasattr(a, 'func')
  13. # a = numpypy.array(a)
  14. # return a.func(...)
  15. #
  16. ######################################################################
  17. import numpypy
  18. # Module containing non-deprecated functions borrowed from Numeric.
  19. __docformat__ = "restructuredtext en"
  20. # functions that are now methods
  21. __all__ = ['take', 'reshape', 'choose', 'repeat', 'put',
  22. 'swapaxes', 'transpose', 'sort', 'argsort', 'argmax', 'argmin',
  23. 'searchsorted', 'alen',
  24. 'resize', 'diagonal', 'trace', 'ravel', 'nonzero', 'shape',
  25. 'compress', 'clip', 'sum', 'product', 'prod', 'sometrue', 'alltrue',
  26. 'any', 'all', 'cumsum', 'cumproduct', 'cumprod', 'ptp', 'ndim',
  27. 'rank', 'size', 'around', 'round_', 'mean', 'std', 'var', 'squeeze',
  28. 'amax', 'amin',
  29. ]
  30. def take(a, indices, axis=None, out=None, mode='raise'):
  31. """
  32. Take elements from an array along an axis.
  33. This function does the same thing as "fancy" indexing (indexing arrays
  34. using arrays); however, it can be easier to use if you need elements
  35. along a given axis.
  36. Parameters
  37. ----------
  38. a : array_like
  39. The source array.
  40. indices : array_like
  41. The indices of the values to extract.
  42. axis : int, optional
  43. The axis over which to select values. By default, the flattened
  44. input array is used.
  45. out : ndarray, optional
  46. If provided, the result will be placed in this array. It should
  47. be of the appropriate shape and dtype.
  48. mode : {'raise', 'wrap', 'clip'}, optional
  49. Specifies how out-of-bounds indices will behave.
  50. * 'raise' -- raise an error (default)
  51. * 'wrap' -- wrap around
  52. * 'clip' -- clip to the range
  53. 'clip' mode means that all indices that are too large are replaced
  54. by the index that addresses the last element along that axis. Note
  55. that this disables indexing with negative numbers.
  56. Returns
  57. -------
  58. subarray : ndarray
  59. The returned array has the same type as `a`.
  60. See Also
  61. --------
  62. ndarray.take : equivalent method
  63. Examples
  64. --------
  65. >>> a = [4, 3, 5, 7, 6, 8]
  66. >>> indices = [0, 1, 4]
  67. >>> np.take(a, indices)
  68. array([4, 3, 6])
  69. In this example if `a` is an ndarray, "fancy" indexing can be used.
  70. >>> a = np.array(a)
  71. >>> a[indices]
  72. array([4, 3, 6])
  73. """
  74. raise NotImplementedError('Waiting on interp level method')
  75. # not deprecated --- copy if necessary, view otherwise
  76. def reshape(a, newshape, order='C'):
  77. """
  78. Gives a new shape to an array without changing its data.
  79. Parameters
  80. ----------
  81. a : array_like
  82. Array to be reshaped.
  83. newshape : int or tuple of ints
  84. The new shape should be compatible with the original shape. If
  85. an integer, then the result will be a 1-D array of that length.
  86. One shape dimension can be -1. In this case, the value is inferred
  87. from the length of the array and remaining dimensions.
  88. order : {'C', 'F', 'A'}, optional
  89. Determines whether the array data should be viewed as in C
  90. (row-major) order, FORTRAN (column-major) order, or the C/FORTRAN
  91. order should be preserved.
  92. Returns
  93. -------
  94. reshaped_array : ndarray
  95. This will be a new view object if possible; otherwise, it will
  96. be a copy.
  97. See Also
  98. --------
  99. ndarray.reshape : Equivalent method.
  100. Notes
  101. -----
  102. It is not always possible to change the shape of an array without
  103. copying the data. If you want an error to be raise if the data is copied,
  104. you should assign the new shape to the shape attribute of the array::
  105. >>> a = np.zeros((10, 2))
  106. # A transpose make the array non-contiguous
  107. >>> b = a.T
  108. # Taking a view makes it possible to modify the shape without modiying the
  109. # initial object.
  110. >>> c = b.view()
  111. >>> c.shape = (20)
  112. AttributeError: incompatible shape for a non-contiguous array
  113. Examples
  114. --------
  115. >>> a = np.array([[1,2,3], [4,5,6]])
  116. >>> np.reshape(a, 6)
  117. array([1, 2, 3, 4, 5, 6])
  118. >>> np.reshape(a, 6, order='F')
  119. array([1, 4, 2, 5, 3, 6])
  120. >>> np.reshape(a, (3,-1)) # the unspecified value is inferred to be 2
  121. array([[1, 2],
  122. [3, 4],
  123. [5, 6]])
  124. """
  125. assert order == 'C'
  126. if not hasattr(a, 'reshape'):
  127. a = numpypy.array(a)
  128. return a.reshape(newshape)
  129. def choose(a, choices, out=None, mode='raise'):
  130. """
  131. Construct an array from an index array and a set of arrays to choose from.
  132. First of all, if confused or uncertain, definitely look at the Examples -
  133. in its full generality, this function is less simple than it might
  134. seem from the following code description (below ndi =
  135. `numpy.lib.index_tricks`):
  136. ``np.choose(a,c) == np.array([c[a[I]][I] for I in ndi.ndindex(a.shape)])``.
  137. But this omits some subtleties. Here is a fully general summary:
  138. Given an "index" array (`a`) of integers and a sequence of `n` arrays
  139. (`choices`), `a` and each choice array are first broadcast, as necessary,
  140. to arrays of a common shape; calling these *Ba* and *Bchoices[i], i =
  141. 0,...,n-1* we have that, necessarily, ``Ba.shape == Bchoices[i].shape``
  142. for each `i`. Then, a new array with shape ``Ba.shape`` is created as
  143. follows:
  144. * if ``mode=raise`` (the default), then, first of all, each element of
  145. `a` (and thus `Ba`) must be in the range `[0, n-1]`; now, suppose that
  146. `i` (in that range) is the value at the `(j0, j1, ..., jm)` position
  147. in `Ba` - then the value at the same position in the new array is the
  148. value in `Bchoices[i]` at that same position;
  149. * if ``mode=wrap``, values in `a` (and thus `Ba`) may be any (signed)
  150. integer; modular arithmetic is used to map integers outside the range
  151. `[0, n-1]` back into that range; and then the new array is constructed
  152. as above;
  153. * if ``mode=clip``, values in `a` (and thus `Ba`) may be any (signed)
  154. integer; negative integers are mapped to 0; values greater than `n-1`
  155. are mapped to `n-1`; and then the new array is constructed as above.
  156. Parameters
  157. ----------
  158. a : int array
  159. This array must contain integers in `[0, n-1]`, where `n` is the number
  160. of choices, unless ``mode=wrap`` or ``mode=clip``, in which cases any
  161. integers are permissible.
  162. choices : sequence of arrays
  163. Choice arrays. `a` and all of the choices must be broadcastable to the
  164. same shape. If `choices` is itself an array (not recommended), then
  165. its outermost dimension (i.e., the one corresponding to
  166. ``choices.shape[0]``) is taken as defining the "sequence".
  167. out : array, optional
  168. If provided, the result will be inserted into this array. It should
  169. be of the appropriate shape and dtype.
  170. mode : {'raise' (default), 'wrap', 'clip'}, optional
  171. Specifies how indices outside `[0, n-1]` will be treated:
  172. * 'raise' : an exception is raised
  173. * 'wrap' : value becomes value mod `n`
  174. * 'clip' : values < 0 are mapped to 0, values > n-1 are mapped to n-1
  175. Returns
  176. -------
  177. merged_array : array
  178. The merged result.
  179. Raises
  180. ------
  181. ValueError: shape mismatch
  182. If `a` and each choice array are not all broadcastable to the same
  183. shape.
  184. See Also
  185. --------
  186. ndarray.choose : equivalent method
  187. Notes
  188. -----
  189. To reduce the chance of misinterpretation, even though the following
  190. "abuse" is nominally supported, `choices` should neither be, nor be
  191. thought of as, a single array, i.e., the outermost sequence-like container
  192. should be either a list or a tuple.
  193. Examples
  194. --------
  195. >>> choices = [[0, 1, 2, 3], [10, 11, 12, 13],
  196. ... [20, 21, 22, 23], [30, 31, 32, 33]]
  197. >>> np.choose([2, 3, 1, 0], choices
  198. ... # the first element of the result will be the first element of the
  199. ... # third (2+1) "array" in choices, namely, 20; the second element
  200. ... # will be the second element of the fourth (3+1) choice array, i.e.,
  201. ... # 31, etc.
  202. ... )
  203. array([20, 31, 12, 3])
  204. >>> np.choose([2, 4, 1, 0], choices, mode='clip') # 4 goes to 3 (4-1)
  205. array([20, 31, 12, 3])
  206. >>> # because there are 4 choice arrays
  207. >>> np.choose([2, 4, 1, 0], choices, mode='wrap') # 4 goes to (4 mod 4)
  208. array([20, 1, 12, 3])
  209. >>> # i.e., 0
  210. A couple examples illustrating how choose broadcasts:
  211. >>> a = [[1, 0, 1], [0, 1, 0], [1, 0, 1]]
  212. >>> choices = [-10, 10]
  213. >>> np.choose(a, choices)
  214. array([[ 10, -10, 10],
  215. [-10, 10, -10],
  216. [ 10, -10, 10]])
  217. >>> # With thanks to Anne Archibald
  218. >>> a = np.array([0, 1]).reshape((2,1,1))
  219. >>> c1 = np.array([1, 2, 3]).reshape((1,3,1))
  220. >>> c2 = np.array([-1, -2, -3, -4, -5]).reshape((1,1,5))
  221. >>> np.choose(a, (c1, c2)) # result is 2x3x5, res[0,:,:]=c1, res[1,:,:]=c2
  222. array([[[ 1, 1, 1, 1, 1],
  223. [ 2, 2, 2, 2, 2],
  224. [ 3, 3, 3, 3, 3]],
  225. [[-1, -2, -3, -4, -5],
  226. [-1, -2, -3, -4, -5],
  227. [-1, -2, -3, -4, -5]]])
  228. """
  229. raise NotImplementedError('Waiting on interp level method')
  230. def repeat(a, repeats, axis=None):
  231. """
  232. Repeat elements of an array.
  233. Parameters
  234. ----------
  235. a : array_like
  236. Input array.
  237. repeats : {int, array of ints}
  238. The number of repetitions for each element. `repeats` is broadcasted
  239. to fit the shape of the given axis.
  240. axis : int, optional
  241. The axis along which to repeat values. By default, use the
  242. flattened input array, and return a flat output array.
  243. Returns
  244. -------
  245. repeated_array : ndarray
  246. Output array which has the same shape as `a`, except along
  247. the given axis.
  248. See Also
  249. --------
  250. tile : Tile an array.
  251. Examples
  252. --------
  253. >>> x = np.array([[1,2],[3,4]])
  254. >>> np.repeat(x, 2)
  255. array([1, 1, 2, 2, 3, 3, 4, 4])
  256. >>> np.repeat(x, 3, axis=1)
  257. array([[1, 1, 1, 2, 2, 2],
  258. [3, 3, 3, 4, 4, 4]])
  259. >>> np.repeat(x, [1, 2], axis=0)
  260. array([[1, 2],
  261. [3, 4],
  262. [3, 4]])
  263. """
  264. raise NotImplementedError('Waiting on interp level method')
  265. def put(a, ind, v, mode='raise'):
  266. """
  267. Replaces specified elements of an array with given values.
  268. The indexing works on the flattened target array. `put` is roughly
  269. equivalent to:
  270. ::
  271. a.flat[ind] = v
  272. Parameters
  273. ----------
  274. a : ndarray
  275. Target array.
  276. ind : array_like
  277. Target indices, interpreted as integers.
  278. v : array_like
  279. Values to place in `a` at target indices. If `v` is shorter than
  280. `ind` it will be repeated as necessary.
  281. mode : {'raise', 'wrap', 'clip'}, optional
  282. Specifies how out-of-bounds indices will behave.
  283. * 'raise' -- raise an error (default)
  284. * 'wrap' -- wrap around
  285. * 'clip' -- clip to the range
  286. 'clip' mode means that all indices that are too large are replaced
  287. by the index that addresses the last element along that axis. Note
  288. that this disables indexing with negative numbers.
  289. See Also
  290. --------
  291. putmask, place
  292. Examples
  293. --------
  294. >>> a = np.arange(5)
  295. >>> np.put(a, [0, 2], [-44, -55])
  296. >>> a
  297. array([-44, 1, -55, 3, 4])
  298. >>> a = np.arange(5)
  299. >>> np.put(a, 22, -5, mode='clip')
  300. >>> a
  301. array([ 0, 1, 2, 3, -5])
  302. """
  303. raise NotImplementedError('Waiting on interp level method')
  304. def swapaxes(a, axis1, axis2):
  305. """
  306. Interchange two axes of an array.
  307. Parameters
  308. ----------
  309. a : array_like
  310. Input array.
  311. axis1 : int
  312. First axis.
  313. axis2 : int
  314. Second axis.
  315. Returns
  316. -------
  317. a_swapped : ndarray
  318. If `a` is an ndarray, then a view of `a` is returned; otherwise
  319. a new array is created.
  320. Examples
  321. --------
  322. >>> x = np.array([[1,2,3]])
  323. >>> np.swapaxes(x,0,1)
  324. array([[1],
  325. [2],
  326. [3]])
  327. >>> x = np.array([[[0,1],[2,3]],[[4,5],[6,7]]])
  328. >>> x
  329. array([[[0, 1],
  330. [2, 3]],
  331. [[4, 5],
  332. [6, 7]]])
  333. >>> np.swapaxes(x,0,2)
  334. array([[[0, 4],
  335. [2, 6]],
  336. [[1, 5],
  337. [3, 7]]])
  338. """
  339. swapaxes = a.swapaxes
  340. return swapaxes(axis1, axis2)
  341. def transpose(a, axes=None):
  342. """
  343. Permute the dimensions of an array.
  344. Parameters
  345. ----------
  346. a : array_like
  347. Input array.
  348. axes : list of ints, optional
  349. By default, reverse the dimensions, otherwise permute the axes
  350. according to the values given.
  351. Returns
  352. -------
  353. p : ndarray
  354. `a` with its axes permuted. A view is returned whenever
  355. possible.
  356. See Also
  357. --------
  358. rollaxis
  359. Examples
  360. --------
  361. >>> x = np.arange(4).reshape((2,2))
  362. >>> x
  363. array([[0, 1],
  364. [2, 3]])
  365. >>> np.transpose(x)
  366. array([[0, 2],
  367. [1, 3]])
  368. >>> x = np.ones((1, 2, 3))
  369. >>> np.transpose(x, (1, 0, 2)).shape
  370. (2, 1, 3)
  371. """
  372. if axes is not None:
  373. raise NotImplementedError('No "axes" arg yet.')
  374. if not hasattr(a, 'T'):
  375. a = numpypy.array(a)
  376. return a.T
  377. def sort(a, axis=-1, kind='quicksort', order=None):
  378. """
  379. Return a sorted copy of an array.
  380. Parameters
  381. ----------
  382. a : array_like
  383. Array to be sorted.
  384. axis : int or None, optional
  385. Axis along which to sort. If None, the array is flattened before
  386. sorting. The default is -1, which sorts along the last axis.
  387. kind : {'quicksort', 'mergesort', 'heapsort'}, optional
  388. Sorting algorithm. Default is 'quicksort'.
  389. order : list, optional
  390. When `a` is a structured array, this argument specifies which fields
  391. to compare first, second, and so on. This list does not need to
  392. include all of the fields.
  393. Returns
  394. -------
  395. sorted_array : ndarray
  396. Array of the same type and shape as `a`.
  397. See Also
  398. --------
  399. ndarray.sort : Method to sort an array in-place.
  400. argsort : Indirect sort.
  401. lexsort : Indirect stable sort on multiple keys.
  402. searchsorted : Find elements in a sorted array.
  403. Notes
  404. -----
  405. The various sorting algorithms are characterized by their average speed,
  406. worst case performance, work space size, and whether they are stable. A
  407. stable sort keeps items with the same key in the same relative
  408. order. The three available algorithms have the following
  409. properties:
  410. =========== ======= ============= ============ =======
  411. kind speed worst case work space stable
  412. =========== ======= ============= ============ =======
  413. 'quicksort' 1 O(n^2) 0 no
  414. 'mergesort' 2 O(n*log(n)) ~n/2 yes
  415. 'heapsort' 3 O(n*log(n)) 0 no
  416. =========== ======= ============= ============ =======
  417. All the sort algorithms make temporary copies of the data when
  418. sorting along any but the last axis. Consequently, sorting along
  419. the last axis is faster and uses less space than sorting along
  420. any other axis.
  421. The sort order for complex numbers is lexicographic. If both the real
  422. and imaginary parts are non-nan then the order is determined by the
  423. real parts except when they are equal, in which case the order is
  424. determined by the imaginary parts.
  425. Previous to numpy 1.4.0 sorting real and complex arrays containing nan
  426. values led to undefined behaviour. In numpy versions >= 1.4.0 nan
  427. values are sorted to the end. The extended sort order is:
  428. * Real: [R, nan]
  429. * Complex: [R + Rj, R + nanj, nan + Rj, nan + nanj]
  430. where R is a non-nan real value. Complex values with the same nan
  431. placements are sorted according to the non-nan part if it exists.
  432. Non-nan values are sorted as before.
  433. Examples
  434. --------
  435. >>> a = np.array([[1,4],[3,1]])
  436. >>> np.sort(a) # sort along the last axis
  437. array([[1, 4],
  438. [1, 3]])
  439. >>> np.sort(a, axis=None) # sort the flattened array
  440. array([1, 1, 3, 4])
  441. >>> np.sort(a, axis=0) # sort along the first axis
  442. array([[1, 1],
  443. [3, 4]])
  444. Use the `order` keyword to specify a field to use when sorting a
  445. structured array:
  446. >>> dtype = [('name', 'S10'), ('height', float), ('age', int)]
  447. >>> values = [('Arthur', 1.8, 41), ('Lancelot', 1.9, 38),
  448. ... ('Galahad', 1.7, 38)]
  449. >>> a = np.array(values, dtype=dtype) # create a structured array
  450. >>> np.sort(a, order='height') # doctest: +SKIP
  451. array([('Galahad', 1.7, 38), ('Arthur', 1.8, 41),
  452. ('Lancelot', 1.8999999999999999, 38)],
  453. dtype=[('name', '|S10'), ('height', '<f8'), ('age', '<i4')])
  454. Sort by age, then height if ages are equal:
  455. >>> np.sort(a, order=['age', 'height']) # doctest: +SKIP
  456. array([('Galahad', 1.7, 38), ('Lancelot', 1.8999999999999999, 38),
  457. ('Arthur', 1.8, 41)],
  458. dtype=[('name', '|S10'), ('height', '<f8'), ('age', '<i4')])
  459. """
  460. raise NotImplementedError('Waiting on interp level method')
  461. def argsort(a, axis=-1, kind='quicksort', order=None):
  462. """
  463. Returns the indices that would sort an array.
  464. Perform an indirect sort along the given axis using the algorithm specified
  465. by the `kind` keyword. It returns an array of indices of the same shape as
  466. `a` that index data along the given axis in sorted order.
  467. Parameters
  468. ----------
  469. a : array_like
  470. Array to sort.
  471. axis : int or None, optional
  472. Axis along which to sort. The default is -1 (the last axis). If None,
  473. the flattened array is used.
  474. kind : {'quicksort', 'mergesort', 'heapsort'}, optional
  475. Sorting algorithm.
  476. order : list, optional
  477. When `a` is an array with fields defined, this argument specifies
  478. which fields to compare first, second, etc. Not all fields need be
  479. specified.
  480. Returns
  481. -------
  482. index_array : ndarray, int
  483. Array of indices that sort `a` along the specified axis.
  484. In other words, ``a[index_array]`` yields a sorted `a`.
  485. See Also
  486. --------
  487. sort : Describes sorting algorithms used.
  488. lexsort : Indirect stable sort with multiple keys.
  489. ndarray.sort : Inplace sort.
  490. Notes
  491. -----
  492. See `sort` for notes on the different sorting algorithms.
  493. As of NumPy 1.4.0 `argsort` works with real/complex arrays containing
  494. nan values. The enhanced sort order is documented in `sort`.
  495. Examples
  496. --------
  497. One dimensional array:
  498. >>> x = np.array([3, 1, 2])
  499. >>> np.argsort(x)
  500. array([1, 2, 0])
  501. Two-dimensional array:
  502. >>> x = np.array([[0, 3], [2, 2]])
  503. >>> x
  504. array([[0, 3],
  505. [2, 2]])
  506. >>> np.argsort(x, axis=0)
  507. array([[0, 1],
  508. [1, 0]])
  509. >>> np.argsort(x, axis=1)
  510. array([[0, 1],
  511. [0, 1]])
  512. Sorting with keys:
  513. >>> x = np.array([(1, 0), (0, 1)], dtype=[('x', '<i4'), ('y', '<i4')])
  514. >>> x
  515. array([(1, 0), (0, 1)],
  516. dtype=[('x', '<i4'), ('y', '<i4')])
  517. >>> np.argsort(x, order=('x','y'))
  518. array([1, 0])
  519. >>> np.argsort(x, order=('y','x'))
  520. array([0, 1])
  521. """
  522. raise NotImplementedError('Waiting on interp level method')
  523. def argmax(a, axis=None):
  524. """
  525. Indices of the maximum values along an axis.
  526. Parameters
  527. ----------
  528. a : array_like
  529. Input array.
  530. axis : int, optional
  531. By default, the index is into the flattened array, otherwise
  532. along the specified axis.
  533. Returns
  534. -------
  535. index_array : ndarray of ints
  536. Array of indices into the array. It has the same shape as `a.shape`
  537. with the dimension along `axis` removed.
  538. See Also
  539. --------
  540. ndarray.argmax, argmin
  541. amax : The maximum value along a given axis.
  542. unravel_index : Convert a flat index into an index tuple.
  543. Notes
  544. -----
  545. In case of multiple occurrences of the maximum values, the indices
  546. corresponding to the first occurrence are returned.
  547. Examples
  548. --------
  549. >>> a = np.arange(6).reshape(2,3)
  550. >>> a
  551. array([[0, 1, 2],
  552. [3, 4, 5]])
  553. >>> np.argmax(a)
  554. 5
  555. >>> np.argmax(a, axis=0)
  556. array([1, 1, 1])
  557. >>> np.argmax(a, axis=1)
  558. array([2, 2])
  559. >>> b = np.arange(6)
  560. >>> b[1] = 5
  561. >>> b
  562. array([0, 5, 2, 3, 4, 5])
  563. >>> np.argmax(b) # Only the first occurrence is returned.
  564. 1
  565. """
  566. assert axis is None
  567. if not hasattr(a, 'argmax'):
  568. a = numpypy.array(a)
  569. return a.argmax()
  570. def argmin(a, axis=None):
  571. """
  572. Return the indices of the minimum values along an axis.
  573. See Also
  574. --------
  575. argmax : Similar function. Please refer to `numpy.argmax` for detailed
  576. documentation.
  577. """
  578. assert axis is None
  579. if not hasattr(a, 'argmin'):
  580. a = numpypy.array(a)
  581. return a.argmin()
  582. def searchsorted(a, v, side='left'):
  583. """
  584. Find indices where elements should be inserted to maintain order.
  585. Find the indices into a sorted array `a` such that, if the corresponding
  586. elements in `v` were inserted before the indices, the order of `a` would
  587. be preserved.
  588. Parameters
  589. ----------
  590. a : 1-D array_like
  591. Input array, sorted in ascending order.
  592. v : array_like
  593. Values to insert into `a`.
  594. side : {'left', 'right'}, optional
  595. If 'left', the index of the first suitable location found is given. If
  596. 'right', return the last such index. If there is no suitable
  597. index, return either 0 or N (where N is the length of `a`).
  598. Returns
  599. -------
  600. indices : array of ints
  601. Array of insertion points with the same shape as `v`.
  602. See Also
  603. --------
  604. sort : Return a sorted copy of an array.
  605. histogram : Produce histogram from 1-D data.
  606. Notes
  607. -----
  608. Binary search is used to find the required insertion points.
  609. As of Numpy 1.4.0 `searchsorted` works with real/complex arrays containing
  610. `nan` values. The enhanced sort order is documented in `sort`.
  611. Examples
  612. --------
  613. >>> np.searchsorted([1,2,3,4,5], 3)
  614. 2
  615. >>> np.searchsorted([1,2,3,4,5], 3, side='right')
  616. 3
  617. >>> np.searchsorted([1,2,3,4,5], [-10, 10, 2, 3])
  618. array([0, 5, 1, 2])
  619. """
  620. raise NotImplementedError('Waiting on interp level method')
  621. def resize(a, new_shape):
  622. """
  623. Return a new array with the specified shape.
  624. If the new array is larger than the original array, then the new
  625. array is filled with repeated copies of `a`. Note that this behavior
  626. is different from a.resize(new_shape) which fills with zeros instead
  627. of repeated copies of `a`.
  628. Parameters
  629. ----------
  630. a : array_like
  631. Array to be resized.
  632. new_shape : int or tuple of int
  633. Shape of resized array.
  634. Returns
  635. -------
  636. reshaped_array : ndarray
  637. The new array is formed from the data in the old array, repeated
  638. if necessary to fill out the required number of elements. The
  639. data are repeated in the order that they are stored in memory.
  640. See Also
  641. --------
  642. ndarray.resize : resize an array in-place.
  643. Examples
  644. --------
  645. >>> a=np.array([[0,1],[2,3]])
  646. >>> np.resize(a,(1,4))
  647. array([[0, 1, 2, 3]])
  648. >>> np.resize(a,(2,4))
  649. array([[0, 1, 2, 3],
  650. [0, 1, 2, 3]])
  651. """
  652. raise NotImplementedError('Waiting on interp level method')
  653. def squeeze(a):
  654. """
  655. Remove single-dimensional entries from the shape of an array.
  656. Parameters
  657. ----------
  658. a : array_like
  659. Input data.
  660. Returns
  661. -------
  662. squeezed : ndarray
  663. The input array, but with with all dimensions of length 1
  664. removed. Whenever possible, a view on `a` is returned.
  665. Examples
  666. --------
  667. >>> x = np.array([[[0], [1], [2]]])
  668. >>> x.shape
  669. (1, 3, 1)
  670. >>> np.squeeze(x).shape
  671. (3,)
  672. """
  673. raise NotImplementedError('Waiting on interp level method')
  674. def diagonal(a, offset=0, axis1=0, axis2=1):
  675. """
  676. Return specified diagonals.
  677. If `a` is 2-D, returns the diagonal of `a` with the given offset,
  678. i.e., the collection of elements of the form ``a[i, i+offset]``. If
  679. `a` has more than two dimensions, then the axes specified by `axis1`
  680. and `axis2` are used to determine the 2-D sub-array whose diagonal is
  681. returned. The shape of the resulting array can be determined by
  682. removing `axis1` and `axis2` and appending an index to the right equal
  683. to the size of the resulting diagonals.
  684. Parameters
  685. ----------
  686. a : array_like
  687. Array from which the diagonals are taken.
  688. offset : int, optional
  689. Offset of the diagonal from the main diagonal. Can be positive or
  690. negative. Defaults to main diagonal (0).
  691. axis1 : int, optional
  692. Axis to be used as the first axis of the 2-D sub-arrays from which
  693. the diagonals should be taken. Defaults to first axis (0).
  694. axis2 : int, optional
  695. Axis to be used as the second axis of the 2-D sub-arrays from
  696. which the diagonals should be taken. Defaults to second axis (1).
  697. Returns
  698. -------
  699. array_of_diagonals : ndarray
  700. If `a` is 2-D, a 1-D array containing the diagonal is returned.
  701. If the dimension of `a` is larger, then an array of diagonals is
  702. returned, "packed" from left-most dimension to right-most (e.g.,
  703. if `a` is 3-D, then the diagonals are "packed" along rows).
  704. Raises
  705. ------
  706. ValueError
  707. If the dimension of `a` is less than 2.
  708. See Also
  709. --------
  710. diag : MATLAB work-a-like for 1-D and 2-D arrays.
  711. diagflat : Create diagonal arrays.
  712. trace : Sum along diagonals.
  713. Examples
  714. --------
  715. >>> a = np.arange(4).reshape(2,2)
  716. >>> a
  717. array([[0, 1],
  718. [2, 3]])
  719. >>> a.diagonal()
  720. array([0, 3])
  721. >>> a.diagonal(1)
  722. array([1])
  723. A 3-D example:
  724. >>> a = np.arange(8).reshape(2,2,2); a
  725. array([[[0, 1],
  726. [2, 3]],
  727. [[4, 5],
  728. [6, 7]]])
  729. >>> a.diagonal(0, # Main diagonals of two arrays created by skipping
  730. ... 0, # across the outer(left)-most axis last and
  731. ... 1) # the "middle" (row) axis first.
  732. array([[0, 6],
  733. [1, 7]])
  734. The sub-arrays whose main diagonals we just obtained; note that each
  735. corresponds to fixing the right-most (column) axis, and that the
  736. diagonals are "packed" in rows.
  737. >>> a[:,:,0] # main diagonal is [0 6]
  738. array([[0, 2],
  739. [4, 6]])
  740. >>> a[:,:,1] # main diagonal is [1 7]
  741. array([[1, 3],
  742. [5, 7]])
  743. """
  744. raise NotImplementedError('Waiting on interp level method')
  745. def trace(a, offset=0, axis1=0, axis2=1, dtype=None, out=None):
  746. """
  747. Return the sum along diagonals of the array.
  748. If `a` is 2-D, the sum along its diagonal with the given offset
  749. is returned, i.e., the sum of elements ``a[i,i+offset]`` for all i.
  750. If `a` has more than two dimensions, then the axes specified by axis1 and
  751. axis2 are used to determine the 2-D sub-arrays whose traces are returned.
  752. The shape of the resulting array is the same as that of `a` with `axis1`
  753. and `axis2` removed.
  754. Parameters
  755. ----------
  756. a : array_like
  757. Input array, from which the diagonals are taken.
  758. offset : int, optional
  759. Offset of the diagonal from the main diagonal. Can be both positive
  760. and negative. Defaults to 0.
  761. axis1, axis2 : int, optional
  762. Axes to be used as the first and second axis of the 2-D sub-arrays
  763. from which the diagonals should be taken. Defaults are the first two
  764. axes of `a`.
  765. dtype : dtype, optional
  766. Determines the data-type of the returned array and of the accumulator
  767. where the elements are summed. If dtype has the value None and `a` is
  768. of integer type of precision less than the default integer
  769. precision, then the default integer precision is used. Otherwise,
  770. the precision is the same as that of `a`.
  771. out : ndarray, optional
  772. Array into which the output is placed. Its type is preserved and
  773. it must be of the right shape to hold the output.
  774. Returns
  775. -------
  776. sum_along_diagonals : ndarray
  777. If `a` is 2-D, the sum along the diagonal is returned. If `a` has
  778. larger dimensions, then an array of sums along diagonals is returned.
  779. See Also
  780. --------
  781. diag, diagonal, diagflat
  782. Examples
  783. --------
  784. >>> np.trace(np.eye(3))
  785. 3.0
  786. >>> a = np.arange(8).reshape((2,2,2))
  787. >>> np.trace(a)
  788. array([6, 8])
  789. >>> a = np.arange(24).reshape((2,2,2,3))
  790. >>> np.trace(a).shape
  791. (2, 3)
  792. """
  793. raise NotImplementedError('Waiting on interp level method')
  794. def ravel(a, order='C'):
  795. """
  796. Return a flattened array.
  797. A 1-D array, containing the elements of the input, is returned. A copy is
  798. made only if needed.
  799. Parameters
  800. ----------
  801. a : array_like
  802. Input array. The elements in ``a`` are read in the order specified by
  803. `order`, and packed as a 1-D array.
  804. order : {'C','F', 'A', 'K'}, optional
  805. The elements of ``a`` are read in this order. 'C' means to view
  806. the elements in C (row-major) order. 'F' means to view the elements
  807. in Fortran (column-major) order. 'A' means to view the elements
  808. in 'F' order if a is Fortran contiguous, 'C' order otherwise.
  809. 'K' means to view the elements in the order they occur in memory,
  810. except for reversing the data when strides are negative.
  811. By default, 'C' order is used.
  812. Returns
  813. -------
  814. 1d_array : ndarray
  815. Output of the same dtype as `a`, and of shape ``(a.size(),)``.
  816. See Also
  817. --------
  818. ndarray.flat : 1-D iterator over an array.
  819. ndarray.flatten : 1-D array copy of the elements of an array
  820. in row-major order.
  821. Notes
  822. -----
  823. In row-major order, the row index varies the slowest, and the column
  824. index the quickest. This can be generalized to multiple dimensions,
  825. where row-major order implies that the index along the first axis
  826. varies slowest, and the index along the last quickest. The opposite holds
  827. for Fortran-, or column-major, mode.
  828. Examples
  829. --------
  830. It is equivalent to ``reshape(-1, order=order)``.
  831. >>> x = np.array([[1, 2, 3], [4, 5, 6]])
  832. >>> print np.ravel(x)
  833. [1 2 3 4 5 6]
  834. >>> print x.reshape(-1)
  835. [1 2 3 4 5 6]
  836. >>> print np.ravel(x, order='F')
  837. [1 4 2 5 3 6]
  838. When ``order`` is 'A', it will preserve the array's 'C' or 'F' ordering:
  839. >>> print np.ravel(x.T)
  840. [1 4 2 5 3 6]
  841. >>> print np.ravel(x.T, order='A')
  842. [1 2 3 4 5 6]
  843. When ``order`` is 'K', it will preserve orderings that are neither 'C'
  844. nor 'F', but won't reverse axes:
  845. >>> a = np.arange(3)[::-1]; a
  846. array([2, 1, 0])
  847. >>> a.ravel(order='C')
  848. array([2, 1, 0])
  849. >>> a.ravel(order='K')
  850. array([2, 1, 0])
  851. >>> a = np.arange(12).reshape(2,3,2).swapaxes(1,2); a
  852. array([[[ 0, 2, 4],
  853. [ 1, 3, 5]],
  854. [[ 6, 8, 10],
  855. [ 7, 9, 11]]])
  856. >>> a.ravel(order='C')
  857. array([ 0, 2, 4, 1, 3, 5, 6, 8, 10, 7, 9, 11])
  858. >>> a.ravel(order='K')
  859. array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
  860. """
  861. if not hasattr(a, 'ravel'):
  862. a = numpypy.array(a)
  863. return a.ravel(order=order)
  864. def nonzero(a):
  865. """
  866. Return the indices of the elements that are non-zero.
  867. Returns a tuple of arrays, one for each dimension of `a`, containing
  868. the indices of the non-zero elements in that dimension. The
  869. corresponding non-zero values can be obtained with::
  870. a[nonzero(a)]
  871. To group the indices by element, rather than dimension, use::
  872. transpose(nonzero(a))
  873. The result of this is always a 2-D array, with a row for
  874. each non-zero element.
  875. Parameters
  876. ----------
  877. a : array_like
  878. Input array.
  879. Returns
  880. -------
  881. tuple_of_arrays : tuple
  882. Indices of elements that are non-zero.
  883. See Also
  884. --------
  885. flatnonzero :
  886. Return indices that are non-zero in the flattened version of the input
  887. array.
  888. ndarray.nonzero :
  889. Equivalent ndarray method.
  890. count_nonzero :
  891. Counts the number of non-zero elements in the input array.
  892. Examples
  893. --------
  894. >>> x = np.eye(3)
  895. >>> x
  896. array([[ 1., 0., 0.],
  897. [ 0., 1., 0.],
  898. [ 0., 0., 1.]])
  899. >>> np.nonzero(x)
  900. (array([0, 1, 2]), array([0, 1, 2]))
  901. >>> x[np.nonzero(x)]
  902. array([ 1., 1., 1.])
  903. >>> np.transpose(np.nonzero(x))
  904. array([[0, 0],
  905. [1, 1],
  906. [2, 2]])
  907. A common use for ``nonzero`` is to find the indices of an array, where
  908. a condition is True. Given an array `a`, the condition `a` > 3 is a
  909. boolean array and since False is interpreted as 0, np.nonzero(a > 3)
  910. yields the indices of the `a` where the condition is true.
  911. >>> a = np.array([[1,2,3],[4,5,6],[7,8,9]])
  912. >>> a > 3
  913. array([[False, False, False],
  914. [ True, True, True],
  915. [ True, True, True]], dtype=bool)
  916. >>> np.nonzero(a > 3)
  917. (array([1, 1, 1, 2, 2, 2]), array([0, 1, 2, 0, 1, 2]))
  918. The ``nonzero`` method of the boolean array can also be called.
  919. >>> (a > 3).nonzero()
  920. (array([1, 1, 1, 2, 2, 2]), array([0, 1, 2, 0, 1, 2]))
  921. """
  922. raise NotImplementedError('Waiting on interp level method')
  923. def shape(a):
  924. """
  925. Return the shape of an array.
  926. Parameters
  927. ----------
  928. a : array_like
  929. Input array.
  930. Returns
  931. -------
  932. shape : tuple of ints
  933. The elements of the shape tuple give the lengths of the
  934. corresponding array dimensions.
  935. See Also
  936. --------
  937. alen
  938. ndarray.shape : Equivalent array method.
  939. Examples
  940. --------
  941. >>> np.shape(np.eye(3))
  942. (3, 3)
  943. >>> np.shape([[1, 2]])
  944. (1, 2)
  945. >>> np.shape([0])
  946. (1,)
  947. >>> np.shape(0)
  948. ()
  949. >>> a = np.array([(1, 2), (3, 4)], dtype=[('x', 'i4'), ('y', 'i4')])
  950. >>> np.shape(a)
  951. (2,)
  952. >>> a.shape
  953. (2,)
  954. """
  955. if not hasattr(a, 'shape'):
  956. a = numpypy.array(a)
  957. return a.shape
  958. def compress(condition, a, axis=None, out=None):
  959. """
  960. Return selected slices of an array along given axis.
  961. When working along a given axis, a slice along that axis is returned in
  962. `output` for each index where `condition` evaluates to True. When
  963. working on a 1-D array, `compress` is equivalent to `extract`.
  964. Parameters
  965. ----------
  966. condition : 1-D array of bools
  967. Array that selects which entries to return. If len(condition)
  968. is less than the size of `a` along the given axis, then output is
  969. truncated to the length of the condition array.
  970. a : array_like
  971. Array from which to extract a part.
  972. axis : int, optional
  973. Axis along which to take slices. If None (default), work on the
  974. flattened array.
  975. out : ndarray, optional
  976. Output array. Its type is preserved and it must be of the right
  977. shape to hold the output.
  978. Returns
  979. -------
  980. compressed_array : ndarray
  981. A copy of `a` without the slices along axis for which `condition`
  982. is false.
  983. See Also
  984. --------
  985. take, choose, diag, diagonal, select
  986. ndarray.compress : Equivalent method.
  987. numpy.doc.ufuncs : Section "Output arguments"
  988. Examples
  989. --------
  990. >>> a = np.array([[1, 2], [3, 4], [5, 6]])
  991. >>> a
  992. array([[1, 2],
  993. [3, 4],
  994. [5, 6]])
  995. >>> np.compress([0, 1], a, axis=0)
  996. array([[3, 4]])
  997. >>> np.compress([False, True, True], a, axis=0)
  998. array([[3, 4],
  999. [5, 6]])
  1000. >>> np.compress([False, True], a, axis=1)
  1001. array([[2],
  1002. [4],
  1003. [6]])
  1004. Working on the flattened array does not return slices along an axis but
  1005. selects elements.
  1006. >>> np.compress([False, True], a)
  1007. array([2])
  1008. """
  1009. raise NotImplementedError('Waiting on interp level method')
  1010. def clip(a, a_min, a_max, out=None):
  1011. """
  1012. Clip (limit) the values in an array.
  1013. Given an interval, values outside the interval are clipped to
  1014. the interval edges. For example, if an interval of ``[0, 1]``
  1015. is specified, values smaller than 0 become 0, and values larger
  1016. than 1 become 1.
  1017. Parameters
  1018. ----------
  1019. a : array_like
  1020. Array containing elements to clip.
  1021. a_min : scalar or array_like
  1022. Minimum value.
  1023. a_max : scalar or array_like
  1024. Maximum value. If `a_min` or `a_max` are array_like, then they will
  1025. be broadcasted to the shape of `a`.
  1026. out : ndarray, optional
  1027. The results will be placed in this array. It may be the input
  1028. array for in-place clipping. `out` must be of the right shape
  1029. to hold the output. Its type is preserved.
  1030. Returns
  1031. -------
  1032. clipped_array : ndarray
  1033. An array with the elements of `a`, but where values
  1034. < `a_min` are replaced with `a_min`, and those > `a_max`
  1035. with `a_max`.
  1036. See Also
  1037. --------
  1038. numpy.doc.ufuncs : Section "Output arguments"
  1039. Examples
  1040. --------
  1041. >>> a = np.arange(10)
  1042. >>> np.clip(a, 1, 8)
  1043. array([1, 1, 2, 3, 4, 5, 6, 7, 8, 8])
  1044. >>> a
  1045. array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
  1046. >>> np.clip(a, 3, 6, out=a)
  1047. array([3, 3, 3, 3, 4, 5, 6, 6, 6, 6])
  1048. >>> a = np.arange(10)
  1049. >>> a
  1050. array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
  1051. >>> np.clip(a, [3,4,1,1,1,4,4,4,4,4], 8)
  1052. array([3, 4, 2, 3, 4, 5, 6, 7, 8, 8])
  1053. """
  1054. raise NotImplementedError('Waiting on interp level method')
  1055. def sum(a, axis=None, dtype=None, out=None):
  1056. """
  1057. Sum of array elements over a given axis.
  1058. Parameters
  1059. ----------
  1060. a : array_like
  1061. Elements to sum.
  1062. axis : integer, optional
  1063. Axis over which the sum is taken. By default `axis` is None,
  1064. and all elements are summed.
  1065. dtype : dtype, optional
  1066. The type of the returned array and of the accumulator in which
  1067. the elements are summed. By default, the dtype of `a` is used.
  1068. An exception is when `a` has an integer type with less precision
  1069. than the default platform integer. In that case, the default
  1070. platform integer is used instead.
  1071. out : ndarray, optional
  1072. Array into which the output is placed. By default, a new array is
  1073. created. If `out` is given, it must be of the appropriate shape
  1074. (the shape of `a` with `axis` removed, i.e.,
  1075. ``numpy.delete(a.shape, axis)``). Its type is preserved. See
  1076. `doc.ufuncs` (Section "Output arguments") for more details.
  1077. Returns
  1078. -------
  1079. sum_along_axis : ndarray
  1080. An array with the same shape as `a`, with the specified
  1081. axis removed. If `a` is a 0-d array, or if `axis` is None, a scalar
  1082. is returned. If an output array is specified, a reference to
  1083. `out` is returned.
  1084. See Also
  1085. --------
  1086. ndarray.sum : Equivalent method.
  1087. cumsum : Cumulative sum of array elements.
  1088. trapz : Integration of array values using the composite trapezoidal rule.
  1089. mean, average
  1090. Notes
  1091. -----
  1092. Arithmetic is modular when using integer types, and no error is
  1093. raised on overflow.
  1094. Examples
  1095. --------
  1096. >>> np.sum([0.5, 1.5])
  1097. 2.0
  1098. >>> np.sum([0.5, 0.7, 0.2, 1.5], dtype=np.int32)
  1099. 1
  1100. >>> np.sum([[0, 1], [0, 5]])
  1101. 6
  1102. >>> np.sum([[0, 1], [0, 5]], axis=0)
  1103. array([0, 6])
  1104. >>> np.sum([[0, 1], [0, 5]], axis=1)
  1105. array([1, 5])
  1106. If the accumulator is too small, overflow occurs:
  1107. >>> np.ones(128, dtype=np.int8).sum(dtype=np.int8)
  1108. -128
  1109. """
  1110. assert dtype is None
  1111. assert out is None
  1112. if not hasattr(a, "sum"):
  1113. a = numpypy.array(a)
  1114. return a.sum(axis=axis)
  1115. def product (a, axis=None, dtype=None, out=None):
  1116. """
  1117. Return the product of array elements over a given axis.
  1118. See Also
  1119. --------
  1120. prod : equivalent function; see for details.
  1121. """
  1122. raise NotImplementedError('Waiting on interp level method')
  1123. def sometrue(a, axis=None, out=None):
  1124. """
  1125. Check whether some values are true.
  1126. Refer to `any` for full documentation.
  1127. See Also
  1128. --------
  1129. any : equivalent function
  1130. """
  1131. assert axis is None
  1132. assert out is None
  1133. if not hasattr(a, 'any'):
  1134. a = numpypy.array(a)
  1135. return a.any()
  1136. def alltrue (a, axis=None, out=None):
  1137. """
  1138. Check if all elements of input array are true.
  1139. See Also
  1140. --------
  1141. numpy.all : Equivalent function; see for details.
  1142. """
  1143. assert axis is None
  1144. assert out is None
  1145. if not hasattr(a, 'all'):
  1146. a = numpypy.array(a)
  1147. return a.all()
  1148. def any(a,axis=None, out=None):
  1149. """
  1150. Test whether any array element along a given axis evaluates to True.
  1151. Returns single boolean unless `axis` is not ``None``
  1152. Parameters
  1153. ----------
  1154. a : array_like
  1155. Input array or object that can be converted to an array.
  1156. axis : int, optional
  1157. Axis along which a logical OR is performed. The default
  1158. (`axis` = `None`) is to perform a logical OR over a flattened
  1159. input array. `axis` may be negative, in which case it counts
  1160. from the last to the first axis.
  1161. out : ndarray, optional
  1162. Alternate output array in which to place the result. It must have
  1163. the same shape as the expected output and its type is preserved
  1164. (e.g., if it is of type float, then it will remain so, returning
  1165. 1.0 for True and 0.0 for False, regardless of the type of `a`).
  1166. See `doc.ufuncs` (Section "Output arguments") for details.
  1167. Returns
  1168. -------
  1169. any : bool or ndarray
  1170. A new boolean or `ndarray` is returned unless `out` is specified,
  1171. in which case a reference to `out` is returned.
  1172. See Also
  1173. --------
  1174. ndarray.any : equivalent method
  1175. all : Test whether all elements along a given axis evaluate to True.
  1176. Notes
  1177. -----
  1178. Not a Number (NaN), positive infinity and negative infinity evaluate
  1179. to `True` because these are not equal to zero.
  1180. Examples
  1181. --------
  1182. >>> np.any([[True, False], [True, True]])
  1183. True
  1184. >>> np.any([[True, False], [False, False]], axis=0)
  1185. array([ True, False], dtype=bool)
  1186. >>> np.any([-1, 0, 5])
  1187. True
  1188. >>> np.any(np.nan)
  1189. True
  1190. >>> o=np.array([False])
  1191. >>> z=np.any([-1, 4, 5], out=o)
  1192. >>> z, o
  1193. (array([ True], dtype=bool), array([ True], dtype=bool))
  1194. >>> # Check now that z is a reference to o
  1195. >>> z is o
  1196. True
  1197. >>> id(z), id(o) # identity of z and o # doctest: +SKIP
  1198. (191614240, 191614240)
  1199. """
  1200. assert axis is None
  1201. assert out is None
  1202. if not hasattr(a, 'any'):
  1203. a = numpypy.array(a)
  1204. return a.any()
  1205. def all(a,axis=None, out=None):
  1206. """
  1207. Test whether all array elements along a given axis evaluate to True.
  1208. Parameters
  1209. ----------
  1210. a : array_like
  1211. Input array or object that can be converted to an array.
  1212. axis : int, optional
  1213. Axis along which a logical AND is performed.
  1214. The default (`axis` = `None`) is to perform a logical AND
  1215. over a flattened input array. `axis` may be negative, in which
  1216. case it counts from the last to the first axis.
  1217. out : ndarray, optional
  1218. Alternate output array in which to place the result.
  1219. It must have the same shape as the expected output and its
  1220. type is preserved (e.g., if ``dtype(out)`` is float, the result
  1221. will consist of 0.0's and 1.0's). See `doc.ufuncs` (Section
  1222. "Output arguments") for more details.
  1223. Returns
  1224. -------
  1225. all : ndarray, bool
  1226. A new boolean or array is returned unless `out` is specified,
  1227. in which case a reference to `out` is returned.
  1228. See Also
  1229. --------
  1230. ndarray.all : equivalent method
  1231. any : Test whether any element along a given axis evaluates to True.
  1232. Notes
  1233. -----
  1234. Not a Number (NaN), positive infinity and negative infinity
  1235. evaluate to `True` because these are not equal to zero.
  1236. Examples
  1237. --------
  1238. >>> np.all([[True,False],[True,True]])
  1239. False
  1240. >>> np.all([[True,False],[True,True]], axis=0)
  1241. array([ True, False], dtype=bool)
  1242. >>> np.all([-1, 4, 5])
  1243. True
  1244. >>> np.all([1.0, np.nan])
  1245. True
  1246. >>> o=np.array([False])
  1247. >>> z=np.all([-1, 4, 5], out=o)
  1248. >>> id(z), id(o), z # doctest: +SKIP
  1249. (28293632, 28293632, array([ True], dtype=bool))
  1250. """
  1251. assert axis is None
  1252. assert out is None
  1253. if not hasattr(a, 'all'):
  1254. a = numpypy.array(a)
  1255. return a.all()
  1256. def cumsum (a, axis=None, dtype=None, out=None):
  1257. """
  1258. Return the cumulative sum of the elements along a given axis.
  1259. Parameters
  1260. ----------
  1261. a : array_like
  1262. Input array.
  1263. axis : int, optional
  1264. Axis along which the cumulative sum is computed. The default
  1265. (None) is to compute the cumsum over the flattened array.
  1266. dtype : dtype, optional
  1267. Type of the returned array and of the accumulator in which the
  1268. elements are summed. If `dtype` is not specified, it defaults
  1269. to the dtype of `a`, unless `a` has an integer dtype with a
  1270. precision less than that of the default platform integer. In
  1271. that case, the default platform integer is used.
  1272. out : ndarray, optional
  1273. Alternative output array in which to place the result. It must
  1274. have the same shape and buffer length as the expected output
  1275. but the type will be cast if necessary. See `doc.ufuncs`
  1276. (Section "Output arguments") for more details.
  1277. Returns
  1278. -------
  1279. cumsum_along_axis : ndarray.
  1280. A new array holding the result is returned unless `out` is
  1281. specified, in which case a reference to `out` is returned. The
  1282. result has the same size as `a`, and the same shape as `a` if
  1283. `axis` is not None or `a` is a 1-d array.
  1284. See Also
  1285. --------
  1286. sum : Sum array elements.
  1287. trapz : Integration of array values using the composite trapezoidal rule.
  1288. Notes
  1289. -----
  1290. Arithmetic is modular when using integer types, and no error is
  1291. raised on overflow.
  1292. Examples
  1293. --------
  1294. >>> a = np.array([[1,2,3], [4,5,6]])
  1295. >>> a
  1296. array([[1, 2, 3],
  1297. [4, 5, 6]])
  1298. >>> np.cumsum(a)
  1299. array([ 1, 3, 6, 10, 15, 21])
  1300. >>> np.cumsum(a, dtype=float) # specifies type of output value(s)
  1301. array([ 1., 3., 6., 10., 15., 21.])
  1302. >>> np.cumsum(a,axis=0) # sum over rows for each of the 3 columns
  1303. array([[1, 2, 3],
  1304. [5, 7, 9]])
  1305. >>> np.cumsum(a,axis=1) # sum over columns for each of the 2 rows
  1306. array([[ 1, 3, 6],
  1307. [ 4, 9, 15]])
  1308. """
  1309. raise NotImplementedError('Waiting on interp level method')
  1310. def cumproduct(a, axis=None, dtype=None, out=None):
  1311. """
  1312. Return the cumulative product over the given axis.
  1313. See Also
  1314. --------
  1315. cumprod : equivalent function; see for details.
  1316. """
  1317. raise NotImplementedError('Waiting on interp level method')
  1318. def ptp(a, axis=None, out=None):
  1319. """
  1320. Range of values (maximum - minimum) along an axis.
  1321. The name of the function comes from the acronym for 'peak to peak'.
  1322. Parameters
  1323. ----------
  1324. a : array_like
  1325. Input values.
  1326. axis : int, optional
  1327. Axis along which to find the peaks. By default, flatten the
  1328. array.
  1329. out : array_like
  1330. Alternative output array in which to place the result. It must
  1331. have the same shape and buffer length as the expected output,
  1332. but the type of the output values will be cast if necessary.
  1333. Returns
  1334. -------
  1335. ptp : ndarray
  1336. A new array holding the result, unless `out` was
  1337. specified, in which case a reference to `out` is returned.
  1338. Examples
  1339. --------
  1340. >>> x = np.arange(4).reshape((2,2))
  1341. >>> x
  1342. array([[0, 1],
  1343. [2, 3]])
  1344. >>> np.ptp(x, axis=0)
  1345. array([2, 2])
  1346. >>> np.ptp(x, axis=1)
  1347. array([1, 1])
  1348. """
  1349. raise NotImplementedError('Waiting on interp level method')
  1350. def amax(a, axis=None, out=None):
  1351. """
  1352. Return the maximum of an array or maximum along an axis.
  1353. Parameters
  1354. ----------
  1355. a : array_like
  1356. Input data.
  1357. axis : int, optional
  1358. Axis along which to operate. By default flattened input is used.
  1359. out : ndarray, optional
  1360. Alternate output array in which to place the result. Must be of
  1361. the same shape and buffer length as the expected output. See
  1362. `doc.ufuncs` (Section "Output arguments") for more details.
  1363. Returns
  1364. -------
  1365. amax : ndarray or scalar
  1366. Maximum of `a`. If `axis` is None, the result is a scalar value.
  1367. If `axis` is given, the result is an array of dimension
  1368. ``a.ndim - 1``.
  1369. See Also
  1370. --------
  1371. nanmax : NaN values are ignored instead of being propagated.
  1372. fmax : same behavior as the C99 fmax function.
  1373. argmax : indices of the maximum values.
  1374. Notes
  1375. -----
  1376. NaN values are propagated, that is if at least one item is NaN, the
  1377. corresponding max value will be NaN as well. To ignore NaN values
  1378. (MATLAB behavior), please use nanmax.
  1379. Examples
  1380. --------
  1381. >>> a = np.arange(4).reshape((2,2))
  1382. >>> a
  1383. array([[0, 1],
  1384. [2, 3]])
  1385. >>> np.amax(a)
  1386. 3
  1387. >>> np.amax(a, axis=0)
  1388. array([2, 3])
  1389. >>> np.amax(a, axis=1)
  1390. array([1, 3])
  1391. >>> b = np.arange(5, dtype=np.float)
  1392. >>> b[2] = np.NaN
  1393. >>> np.amax(b)
  1394. nan
  1395. >>> np.nanmax(b)
  1396. 4.0
  1397. """
  1398. assert axis is None
  1399. assert out is None
  1400. if not hasattr(a, "max"):
  1401. a = numpypy.array(a)
  1402. return a.max()
  1403. def amin(a, axis=None, out=None):
  1404. """
  1405. Return the minimum of an array or minimum along an axis.
  1406. Parameters
  1407. ----------
  1408. a : array_like
  1409. Input data.
  1410. axis : int, optional
  1411. Axis along which to operate. By default a flattened input is used.
  1412. out : ndarray, optional
  1413. Alternative output array in which to place the result. Must
  1414. be of the same shape and buffer length as the expected output.
  1415. See `doc.ufuncs` (Section "Output arguments") for more details.
  1416. Returns
  1417. -------
  1418. amin : ndarray
  1419. A new array or a scalar array with the result.
  1420. See Also
  1421. --------
  1422. nanmin: nan values are ignored instead of being propagated
  1423. fmin: same behavior as the C99 fmin function
  1424. argmin: Return the indices of the minimum values.
  1425. amax, nanmax, fmax
  1426. Notes
  1427. -----
  1428. NaN values are propagated, that is if at least one item is nan, the
  1429. corresponding min value will be nan as well. To ignore NaN values (matlab
  1430. behavior), please use nanmin.
  1431. Examples
  1432. --------
  1433. >>> a = np.arange(4).reshape((2,2))
  1434. >>> a
  1435. array([[0, 1],
  1436. [2, 3]])
  1437. >>> np.amin(a) # Minimum of the flattened array
  1438. 0
  1439. >>> np.amin(a, axis=0) # Minima along the first axis
  1440. array([0, 1])
  1441. >>> np.amin(a, axis=1) # Minima along the second axis
  1442. array([0, 2])
  1443. >>> b = np.arange(5, dtype=np.float)
  1444. >>> b[2] = np.NaN
  1445. >>> np.amin(b)
  1446. nan
  1447. >>> np.nanmin(b)
  1448. 0.0
  1449. """
  1450. # amin() is equivalent to min()
  1451. assert axis is None
  1452. assert out is None
  1453. if not hasattr(a, 'min'):
  1454. a = numpypy.array(a)
  1455. return a.min()
  1456. def alen(a):
  1457. """
  1458. Return the length of the first dimension of the input array.
  1459. Parameters
  1460. ----------
  1461. a : array_like
  1462. Input array.
  1463. Returns
  1464. -------
  1465. l : int
  1466. Length of the first dimension of `a`.
  1467. See Also
  1468. --------
  1469. shape, size
  1470. Examples
  1471. --------
  1472. >>> a = np.zeros((7,4,5))
  1473. >>> a.shape[0]
  1474. 7
  1475. >>> np.alen(a)
  1476. 7
  1477. """
  1478. if not hasattr(a, 'shape'):
  1479. a = numpypy.array(a)
  1480. return a.shape[0]
  1481. def prod(a, axis=None, dtype=None, out=None):
  1482. """
  1483. Return the product of array elements over a given axis.
  1484. Parameters
  1485. ----------
  1486. a : array_like
  1487. Input data.
  1488. axis : int, optional
  1489. Axis over which the product is taken. By default, the product
  1490. of all elements is calculated.
  1491. dtype : data-type, optional
  1492. The data-type of the returned array, as well as of the accumulator
  1493. in which the elements are multiplied. By default, if `a` is of
  1494. integer type, `dtype` is the default platform integer. (Note: if
  1495. the type of `a` is unsigned, then so is `dtype`.) Otherwise,
  1496. the dtype is the same as that of `a`.
  1497. out : ndarray, optional
  1498. Alternative output array in which to place the result. It must have
  1499. the same shape as the expected output, but the type of the
  1500. output values will be cast if necessary.
  1501. Returns
  1502. -------
  1503. product_along_axis : ndarray, see `dtype` parameter above.
  1504. An array shaped as `a` but with the specified axis removed.
  1505. Returns a reference to `out` if specified.
  1506. See Also
  1507. --------
  1508. ndarray.prod : equivalent method
  1509. numpy.doc.ufuncs : Section "Output arguments"
  1510. Notes
  1511. -----
  1512. Arithmetic is modular when using integer types, and no error is
  1513. raised on overflow. That means that, on a 32-bit platform:
  1514. >>> x = np.array([536870910, 536870910, 536870910, 536870910])
  1515. >>> np.prod(x) #random
  1516. 16
  1517. Examples
  1518. --------
  1519. By default, calculate the product of all elements:
  1520. >>> np.prod([1.,2.])
  1521. 2.0
  1522. Even when the input array is two-dimensional:
  1523. >>> np.prod([[1.,2.],[3.,4.]])
  1524. 24.0
  1525. But we can also specify the axis over which to multiply:
  1526. >>> np.prod([[1.,2.],[3.,4.]], axis=1)
  1527. array([ 2., 12.])
  1528. If the type of `x` is unsigned, then the output type is
  1529. the unsigned platform integer:
  1530. >>> x = np.array([1, 2, 3], dtype=np.uint8)
  1531. >>> np.prod(x).dtype == np.uint
  1532. True
  1533. If `x` is of a signed integer type, then the output type
  1534. is the default platform integer:
  1535. >>> x = np.array([1, 2, 3], dtype=np.int8)
  1536. >>> np.prod(x).dtype == np.int
  1537. True
  1538. """
  1539. raise NotImplementedError('Waiting on interp level method')
  1540. def cumprod(a, axis=None, dtype=None, out=None):
  1541. """
  1542. Return the cumulative product of elements along a given axis.
  1543. Parameters
  1544. ----------
  1545. a : array_like
  1546. Input array.
  1547. axis : int, optional
  1548. Axis along which the cumulative product is computed. By default
  1549. the input is flattened.
  1550. dtype : dtype, optional
  1551. Type of the returned array, as well as of the accumulator in which
  1552. the elements are multiplied. If *dtype* is not specified, it
  1553. defaults to the dtype of `a`, unless `a` has an integer dtype with
  1554. a precision less than that of the default platform integer. In
  1555. that case, the default platform integer is used instead.
  1556. out : ndarray, optional
  1557. Alternative output array in which to place the result. It must
  1558. have the same shape and buffer length as the expected output
  1559. but the type of the resulting values will be cast if necessary.
  1560. Returns
  1561. -------
  1562. cumprod : ndarray
  1563. A new array holding the result is returned unless `out` is
  1564. specified, in which case a reference to out is returned.
  1565. See Also
  1566. --------
  1567. numpy.doc.ufuncs : Section "Output arguments"
  1568. Notes
  1569. -----
  1570. Arithmetic is modular when using integer types, and no error is
  1571. raised on overflow.
  1572. Examples
  1573. --------
  1574. >>> a = np.array([1,2,3])
  1575. >>> np.cumprod(a) # intermediate results 1, 1*2
  1576. ... # total product 1*2*3 = 6
  1577. array([1, 2, 6])
  1578. >>> a = np.array([[1, 2, 3], [4, 5, 6]])
  1579. >>> np.cumprod(a, dtype=float) # specify type of output
  1580. array([ 1., 2., 6., 24., 120., 720.])
  1581. The cumulative product for each column (i.e., over the rows) of `a`:
  1582. >>> np.cumprod(a, axis=0)
  1583. array([[ 1, 2, 3],
  1584. [ 4, 10, 18]])
  1585. The cumulative product for each row (i.e. over the columns) of `a`:
  1586. >>> np.cumprod(a,axis=1)
  1587. array([[ 1, 2, 6],
  1588. [ 4, 20, 120]])
  1589. """
  1590. raise NotImplementedError('Waiting on interp level method')
  1591. def ndim(a):
  1592. """
  1593. Return the number of dimensions of an array.
  1594. Parameters
  1595. ----------
  1596. a : array_like
  1597. Input array. If it is not already an ndarray, a conversion is
  1598. attempted.
  1599. Returns
  1600. -------
  1601. number_of_dimensions : int
  1602. The number of dimensions in `a`. Scalars are zero-dimensional.
  1603. See Also
  1604. --------
  1605. ndarray.ndim : equivalent method
  1606. shape : dimensions of array
  1607. ndarray.shape : dimensions of array
  1608. Examples
  1609. --------
  1610. >>> np.ndim([[1,2,3],[4,5,6]])
  1611. 2
  1612. >>> np.ndim(np.array([[1,2,3],[4,5,6]]))
  1613. 2
  1614. >>> np.ndim(1)
  1615. 0
  1616. """
  1617. if not hasattr(a, 'ndim'):
  1618. a = numpypy.array(a)
  1619. return a.ndim
  1620. def rank(a):
  1621. """
  1622. Return the number of dimensions of an array.
  1623. If `a` is not already an array, a conversion is attempted.
  1624. Scalars are zero dimensional.
  1625. Parameters
  1626. ----------
  1627. a : array_like
  1628. Array whose number of dimensions is desired. If `a` is not an array,
  1629. a conversion is attempted.
  1630. Returns
  1631. -------
  1632. number_of_dimensions : int
  1633. The number of dimensions in the array.
  1634. See Also
  1635. --------
  1636. ndim : equivalent function
  1637. ndarray.ndim : equivalent property
  1638. shape : dimensions of array
  1639. ndarray.shape : dimensions of array
  1640. Notes
  1641. -----
  1642. In the old Numeric package, `rank` was the term used for the number of
  1643. dimensions, but in Numpy `ndim` is used instead.
  1644. Examples
  1645. --------
  1646. >>> np.rank([1,2,3])
  1647. 1
  1648. >>> np.rank(np.array([[1,2,3],[4,5,6]]))
  1649. 2
  1650. >>> np.rank(1)
  1651. 0
  1652. """
  1653. if not hasattr(a, 'ndim'):
  1654. a = numpypy.array(a)
  1655. return a.ndim
  1656. def size(a, axis=None):
  1657. """
  1658. Return the number of elements along a given axis.
  1659. Parameters
  1660. ----------
  1661. a : array_like
  1662. Input data.
  1663. axis : int, optional
  1664. Axis along which the elements are counted. By default, give
  1665. the total number of elements.
  1666. Returns
  1667. -------
  1668. element_count : int
  1669. Number of elements along the specified axis.
  1670. See Also
  1671. --------
  1672. shape : dimensions of array
  1673. ndarray.shape : dimensions of array
  1674. ndarray.size : number of elements in array
  1675. Examples
  1676. --------
  1677. >>> a = np.array([[1,2,3],[4,5,6]])
  1678. >>> np.size(a)
  1679. 6
  1680. >>> np.size(a,1)
  1681. 3
  1682. >>> np.size(a,0)
  1683. 2
  1684. """
  1685. raise NotImplementedError('Waiting on interp level method')
  1686. def around(a, decimals=0, out=None):
  1687. """
  1688. Evenly round to the given number of decimals.
  1689. Parameters
  1690. ----------
  1691. a : array_like
  1692. Input data.
  1693. decimals : int, optional
  1694. Number of decimal places to round to (default: 0). If
  1695. decimals is negative, it specifies the number of positions to
  1696. the left of the decimal point.
  1697. out : ndarray, optional
  1698. Alternative output array in which to place the result. It must have
  1699. the same shape as the expected output, but the type of the output
  1700. values will be cast if necessary. See `doc.ufuncs` (Section
  1701. "Output arguments") for details.
  1702. Returns
  1703. -------
  1704. rounded_array : ndarray
  1705. An array of the same type as `a`, containing the rounded values.
  1706. Unless `out` was specified, a new array is created. A reference to
  1707. the result is returned.
  1708. The real and imaginary parts of complex numbers are rounded
  1709. separately. The result of rounding a float is a float.
  1710. See Also
  1711. --------
  1712. ndarray.round : equivalent method
  1713. ceil, fix, floor, rint, trunc
  1714. Notes
  1715. -----
  1716. For values exactly halfway between rounded decimal values, Numpy
  1717. rounds to the nearest even value. Thus 1.5 and 2.5 round to 2.0,
  1718. -0.5 and 0.5 round to 0.0, etc. Results may also be surprising due
  1719. to the inexact representation of decimal fractions in the IEEE
  1720. floating point standard [1]_ and errors introduced when scaling
  1721. by powers of ten.
  1722. References
  1723. ----------
  1724. .. [1] "Lecture Notes on the Status of IEEE 754", William Kahan,
  1725. http://www.cs.berkeley.edu/~wkahan/ieee754status/IEEE754.PDF
  1726. .. [2] "How Futile are Mindless Assessments of
  1727. Roundoff in Floating-Point Computation?", William Kahan,
  1728. http://www.cs.berkeley.edu/~wkahan/Mindless.pdf
  1729. Examples
  1730. --------
  1731. >>> np.around([0.37, 1.64])
  1732. array([ 0., 2.])
  1733. >>> np.around([0.37, 1.64], decimals=1)
  1734. array([ 0.4, 1.6])
  1735. >>> np.around([.5, 1.5, 2.5, 3.5, 4.5]) # rounds to nearest even value
  1736. array([ 0., 2., 2., 4., 4.])
  1737. >>> np.around([1,2,3,11], decimals=1) # ndarray of ints is returned
  1738. array([ 1, 2, 3, 11])
  1739. >>> np.around([1,2,3,11], decimals=-1)
  1740. array([ 0, 0, 0, 10])
  1741. """
  1742. raise NotImplementedError('Waiting on interp level method')
  1743. def round_(a, decimals=0, out=None):
  1744. """
  1745. Round an array to the given number of decimals.
  1746. Refer to `around` for full documentation.
  1747. See Also
  1748. --------
  1749. around : equivalent function
  1750. """
  1751. raise NotImplementedError('Waiting on interp level method')
  1752. def mean(a, axis=None, dtype=None, out=None):
  1753. """
  1754. Compute the arithmetic mean along the specified axis.
  1755. Returns the average of the array elements. The average is taken over
  1756. the flattened array by default, otherwise over the specified axis.
  1757. `float64` intermediate and return values are used for integer inputs.
  1758. Parameters
  1759. ----------
  1760. a : array_like
  1761. Array containing numbers whose mean is desired. If `a` is not an
  1762. array, a conversion is attempted.
  1763. axis : int, optional
  1764. Axis along which the means are computed. The default is to compute
  1765. the mean of the flattened array.
  1766. dtype : data-type, optional
  1767. Type to use in computing the mean. For integer inputs, the default
  1768. is `float64`; for floating point inputs, it is the same as the
  1769. input dtype.
  1770. out : ndarray, optional
  1771. Alternate output array in which to place the result. The default
  1772. is ``None``; if provided, it must have the same shape as the
  1773. expected output, but the type will be cast if necessary.
  1774. See `doc.ufuncs` for details.
  1775. Returns
  1776. -------
  1777. m : ndarray, see dtype parameter above
  1778. If `out=None`, returns a new array containing the mean values,
  1779. otherwise a reference to the output array is returned.
  1780. See Also
  1781. --------
  1782. average : Weighted average
  1783. Notes
  1784. -----
  1785. The arithmetic mean is the sum of the elements along the axis divided
  1786. by the number of elements.
  1787. Note that for floating-point input, the mean is computed using the
  1788. same precision the input has. Depending on the input data, this can
  1789. cause the results to be inaccurate, especially for `float32` (see
  1790. example below). Specifying a higher-precision accumulator using the
  1791. `dtype` keyword can alleviate this issue.
  1792. Examples
  1793. --------
  1794. >>> a = np.array([[1, 2], [3, 4]])
  1795. >>> np.mean(a)
  1796. 2.5
  1797. >>> np.mean(a, axis=0)
  1798. array([ 2., 3.])
  1799. >>> np.mean(a, axis=1)
  1800. array([ 1.5, 3.5])
  1801. In single precision, `mean` can be inaccurate:
  1802. >>> a = np.zeros((2, 512*512), dtype=np.float32)
  1803. >>> a[0, :] = 1.0
  1804. >>> a[1, :] = 0.1
  1805. >>> np.mean(a)
  1806. 0.546875
  1807. Computing the mean in float64 is more accurate:
  1808. >>> np.mean(a, dtype=np.float64)
  1809. 0.55000000074505806
  1810. """
  1811. assert dtype is None
  1812. assert out is None
  1813. if not hasattr(a, "mean"):
  1814. a = numpypy.array(a)
  1815. return a.mean(axis=axis)
  1816. def std(a, axis=None, dtype=None, out=None, ddof=0):
  1817. """
  1818. Compute the standard deviation along the specified axis.
  1819. Returns the standard deviation, a measure of the spread of a distribution,
  1820. of the array elements. The standard deviation is computed for the
  1821. flattened array by default, otherwise over the specified axis.
  1822. Parameters
  1823. ----------
  1824. a : array_like
  1825. Calculate the standard deviation of these values.
  1826. axis : int, optional
  1827. Axis along which the standard deviation is computed. The default is
  1828. to compute the standard deviation of the flattened array.
  1829. dtype : dtype, optional
  1830. Type to use in computing the standard deviation. For arrays of
  1831. integer type the default is float64, for arrays of float types it is
  1832. the same as the array type.
  1833. out : ndarray, optional
  1834. Alternative output array in which to place the result. It must have
  1835. the same shape as the expected output but the type (of the calculated
  1836. values) will be cast if necessary.
  1837. ddof : int, optional
  1838. Means Delta Degrees of Freedom. The divisor used in calculations
  1839. is ``N - ddof``, where ``N`` represents the number of elements.
  1840. By default `ddof` is zero.
  1841. Returns
  1842. -------
  1843. standard_deviation : ndarray, see dtype parameter above.
  1844. If `out` is None, return a new array containing the standard deviation,
  1845. otherwise return a reference to the output array.
  1846. See Also
  1847. --------
  1848. var, mean
  1849. numpy.doc.ufuncs : Section "Output arguments"
  1850. Notes
  1851. -----
  1852. The standard deviation is the square root of the average of the squared
  1853. deviations from the mean, i.e., ``std = sqrt(mean(abs(x - x.mean())**2))``.
  1854. The average squared deviation is normally calculated as ``x.sum() / N``, where
  1855. ``N = len(x)``. If, however, `ddof` is specified, the divisor ``N - ddof``
  1856. is used instead. In standard statistical practice, ``ddof=1`` provides an
  1857. unbiased estimator of the variance of the infinite population. ``ddof=0``
  1858. provides a maximum likelihood estimate of the variance for normally
  1859. distributed variables. The standard deviation computed in this function
  1860. is the square root of the estimated variance, so even with ``ddof=1``, it
  1861. will not be an unbiased estimate of the standard deviation per se.
  1862. Note that, for complex numbers, `std` takes the absolute
  1863. value before squaring, so that the result is always real and nonnegative.
  1864. For floating-point input, the *std* is computed using the same
  1865. precision the input has. Depending on the input data, this can cause
  1866. the results to be inaccurate, especially for float32 (see example below).
  1867. Specifying a higher-accuracy accumulator using the `dtype` keyword can
  1868. alleviate this issue.
  1869. Examples
  1870. --------
  1871. >>> a = np.array([[1, 2], [3, 4]])
  1872. >>> np.std(a)
  1873. 1.1180339887498949
  1874. >>> np.std(a, axis=0)
  1875. array([ 1., 1.])
  1876. >>> np.std(a, axis=1)
  1877. array([ 0.5, 0.5])
  1878. In single precision, std() can be inaccurate:
  1879. >>> a = np.zeros((2,512*512), dtype=np.float32)
  1880. >>> a[0,:] = 1.0
  1881. >>> a[1,:] = 0.1
  1882. >>> np.std(a)
  1883. 0.45172946707416706
  1884. Computing the standard deviation in float64 is more accurate:
  1885. >>> np.std(a, dtype=np.float64)
  1886. 0.44999999925552653
  1887. """
  1888. assert dtype is None
  1889. assert out is None
  1890. assert ddof == 0
  1891. if not hasattr(a, "std"):
  1892. a = numpypy.array(a)
  1893. return a.std(axis=axis)
  1894. def var(a, axis=None, dtype=None, out=None, ddof=0):
  1895. """
  1896. Compute the variance along the specified axis.
  1897. Returns the variance of the array elements, a measure of the spread of a
  1898. distribution. The variance is computed for the flattened array by
  1899. default, otherwise over the specified axis.
  1900. Parameters
  1901. ----------
  1902. a : array_like
  1903. Array containing numbers whose variance is desired. If `a` is not an
  1904. array, a conversion is attempted.
  1905. axis : int, optional
  1906. Axis along which the variance is computed. The default is to compute
  1907. the variance of the flattened array.
  1908. dtype : data-type, optional
  1909. Type to use in computing the variance. For arrays of integer type
  1910. the default is `float32`; for arrays of float types it is the same as
  1911. the array type.
  1912. out : ndarray, optional
  1913. Alternate output array in which to place the result. It must have
  1914. the same shape as the expected output, but the type is cast if
  1915. necessary.
  1916. ddof : int, optional
  1917. "Delta Degrees of Freedom": the divisor used in the calculation is
  1918. ``N - ddof``, where ``N`` represents the number of elements. By
  1919. default `ddof` is zero.
  1920. Returns
  1921. -------
  1922. variance : ndarray, see dtype parameter above
  1923. If ``out=None``, returns a new array containing the variance;
  1924. otherwise, a reference to the output array is returned.
  1925. See Also
  1926. --------
  1927. std : Standard deviation
  1928. mean : Average
  1929. numpy.doc.ufuncs : Section "Output arguments"
  1930. Notes
  1931. -----
  1932. The variance is the average of the squared deviations from the mean,
  1933. i.e., ``var = mean(abs(x - x.mean())**2)``.
  1934. The mean is normally calculated as ``x.sum() / N``, where ``N = len(x)``.
  1935. If, however, `ddof` is specified, the divisor ``N - ddof`` is used
  1936. instead. In standard statistical practice, ``ddof=1`` provides an
  1937. unbiased estimator of the variance of a hypothetical infinite population.
  1938. ``ddof=0`` provides a maximum likelihood estimate of the variance for
  1939. normally distributed variables.
  1940. Note that for complex numbers, the absolute value is taken before
  1941. squaring, so that the result is always real and nonnegative.
  1942. For floating-point input, the variance is computed using the same
  1943. precision the input has. Depending on the input data, this can cause
  1944. the results to be inaccurate, especially for `float32` (see example
  1945. below). Specifying a higher-accuracy accumulator using the ``dtype``
  1946. keyword can alleviate this issue.
  1947. Examples
  1948. --------
  1949. >>> a = np.array([[1,2],[3,4]])
  1950. >>> np.var(a)
  1951. 1.25
  1952. >>> np.var(a,0)
  1953. array([ 1., 1.])
  1954. >>> np.var(a,1)
  1955. array([ 0.25, 0.25])
  1956. In single precision, var() can be inaccurate:
  1957. >>> a = np.zeros((2,512*512), dtype=np.float32)
  1958. >>> a[0,:] = 1.0
  1959. >>> a[1,:] = 0.1
  1960. >>> np.var(a)
  1961. 0.20405951142311096
  1962. Computing the standard deviation in float64 is more accurate:
  1963. >>> np.var(a, dtype=np.float64)
  1964. 0.20249999932997387
  1965. >>> ((1-0.55)**2 + (0.1-0.55)**2)/2
  1966. 0.20250000000000001
  1967. """
  1968. assert dtype is None
  1969. assert out is None
  1970. assert ddof == 0
  1971. if not hasattr(a, "var"):
  1972. a = numpypy.array(a)
  1973. return a.var(axis=axis)