multiarray.py 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714
  1. """
  2. Create the numpy.core.multiarray namespace for backward compatibility. In v1.16
  3. the multiarray and umath c-extension modules were merged into a single
  4. _multiarray_umath extension module. So we replicate the old namespace
  5. by importing from the extension module.
  6. """
  7. import functools
  8. from . import overrides
  9. from . import _multiarray_umath
  10. from ._multiarray_umath import * # noqa: F403
  11. # These imports are needed for backward compatibility,
  12. # do not change them. issue gh-15518
  13. # _get_ndarray_c_version is semi-public, on purpose not added to __all__
  14. from ._multiarray_umath import (
  15. fastCopyAndTranspose, _flagdict, from_dlpack, _insert, _reconstruct,
  16. _vec_string, _ARRAY_API, _monotonicity, _get_ndarray_c_version,
  17. _get_madvise_hugepage, _set_madvise_hugepage,
  18. _get_promotion_state, _set_promotion_state,
  19. )
  20. __all__ = [
  21. '_ARRAY_API', 'ALLOW_THREADS', 'BUFSIZE', 'CLIP', 'DATETIMEUNITS',
  22. 'ITEM_HASOBJECT', 'ITEM_IS_POINTER', 'LIST_PICKLE', 'MAXDIMS',
  23. 'MAY_SHARE_BOUNDS', 'MAY_SHARE_EXACT', 'NEEDS_INIT', 'NEEDS_PYAPI',
  24. 'RAISE', 'USE_GETITEM', 'USE_SETITEM', 'WRAP',
  25. '_flagdict', 'from_dlpack', '_insert', '_reconstruct', '_vec_string',
  26. '_monotonicity', 'add_docstring', 'arange', 'array', 'asarray',
  27. 'asanyarray', 'ascontiguousarray', 'asfortranarray', 'bincount',
  28. 'broadcast', 'busday_count', 'busday_offset', 'busdaycalendar', 'can_cast',
  29. 'compare_chararrays', 'concatenate', 'copyto', 'correlate', 'correlate2',
  30. 'count_nonzero', 'c_einsum', 'datetime_as_string', 'datetime_data',
  31. 'dot', 'dragon4_positional', 'dragon4_scientific', 'dtype',
  32. 'empty', 'empty_like', 'error', 'flagsobj', 'flatiter', 'format_longfloat',
  33. 'frombuffer', 'fromfile', 'fromiter', 'fromstring',
  34. 'get_handler_name', 'get_handler_version', 'inner', 'interp',
  35. 'interp_complex', 'is_busday', 'lexsort', 'matmul', 'may_share_memory',
  36. 'min_scalar_type', 'ndarray', 'nditer', 'nested_iters',
  37. 'normalize_axis_index', 'packbits', 'promote_types', 'putmask',
  38. 'ravel_multi_index', 'result_type', 'scalar', 'set_datetimeparse_function',
  39. 'set_legacy_print_mode', 'set_numeric_ops', 'set_string_function',
  40. 'set_typeDict', 'shares_memory', 'tracemalloc_domain', 'typeinfo',
  41. 'unpackbits', 'unravel_index', 'vdot', 'where', 'zeros',
  42. '_get_promotion_state', '_set_promotion_state']
  43. # For backward compatibility, make sure pickle imports these functions from here
  44. _reconstruct.__module__ = 'numpy.core.multiarray'
  45. scalar.__module__ = 'numpy.core.multiarray'
  46. from_dlpack.__module__ = 'numpy'
  47. arange.__module__ = 'numpy'
  48. array.__module__ = 'numpy'
  49. asarray.__module__ = 'numpy'
  50. asanyarray.__module__ = 'numpy'
  51. ascontiguousarray.__module__ = 'numpy'
  52. asfortranarray.__module__ = 'numpy'
  53. datetime_data.__module__ = 'numpy'
  54. empty.__module__ = 'numpy'
  55. frombuffer.__module__ = 'numpy'
  56. fromfile.__module__ = 'numpy'
  57. fromiter.__module__ = 'numpy'
  58. frompyfunc.__module__ = 'numpy'
  59. fromstring.__module__ = 'numpy'
  60. geterrobj.__module__ = 'numpy'
  61. may_share_memory.__module__ = 'numpy'
  62. nested_iters.__module__ = 'numpy'
  63. promote_types.__module__ = 'numpy'
  64. set_numeric_ops.__module__ = 'numpy'
  65. seterrobj.__module__ = 'numpy'
  66. zeros.__module__ = 'numpy'
  67. _get_promotion_state.__module__ = 'numpy'
  68. _set_promotion_state.__module__ = 'numpy'
  69. # We can't verify dispatcher signatures because NumPy's C functions don't
  70. # support introspection.
  71. array_function_from_c_func_and_dispatcher = functools.partial(
  72. overrides.array_function_from_dispatcher,
  73. module='numpy', docs_from_dispatcher=True, verify=False)
  74. @array_function_from_c_func_and_dispatcher(_multiarray_umath.empty_like)
  75. def empty_like(prototype, dtype=None, order=None, subok=None, shape=None):
  76. """
  77. empty_like(prototype, dtype=None, order='K', subok=True, shape=None)
  78. Return a new array with the same shape and type as a given array.
  79. Parameters
  80. ----------
  81. prototype : array_like
  82. The shape and data-type of `prototype` define these same attributes
  83. of the returned array.
  84. dtype : data-type, optional
  85. Overrides the data type of the result.
  86. .. versionadded:: 1.6.0
  87. order : {'C', 'F', 'A', or 'K'}, optional
  88. Overrides the memory layout of the result. 'C' means C-order,
  89. 'F' means F-order, 'A' means 'F' if `prototype` is Fortran
  90. contiguous, 'C' otherwise. 'K' means match the layout of `prototype`
  91. as closely as possible.
  92. .. versionadded:: 1.6.0
  93. subok : bool, optional.
  94. If True, then the newly created array will use the sub-class
  95. type of `prototype`, otherwise it will be a base-class array. Defaults
  96. to True.
  97. shape : int or sequence of ints, optional.
  98. Overrides the shape of the result. If order='K' and the number of
  99. dimensions is unchanged, will try to keep order, otherwise,
  100. order='C' is implied.
  101. .. versionadded:: 1.17.0
  102. Returns
  103. -------
  104. out : ndarray
  105. Array of uninitialized (arbitrary) data with the same
  106. shape and type as `prototype`.
  107. See Also
  108. --------
  109. ones_like : Return an array of ones with shape and type of input.
  110. zeros_like : Return an array of zeros with shape and type of input.
  111. full_like : Return a new array with shape of input filled with value.
  112. empty : Return a new uninitialized array.
  113. Notes
  114. -----
  115. This function does *not* initialize the returned array; to do that use
  116. `zeros_like` or `ones_like` instead. It may be marginally faster than
  117. the functions that do set the array values.
  118. Examples
  119. --------
  120. >>> a = ([1,2,3], [4,5,6]) # a is array-like
  121. >>> np.empty_like(a)
  122. array([[-1073741821, -1073741821, 3], # uninitialized
  123. [ 0, 0, -1073741821]])
  124. >>> a = np.array([[1., 2., 3.],[4.,5.,6.]])
  125. >>> np.empty_like(a)
  126. array([[ -2.00000715e+000, 1.48219694e-323, -2.00000572e+000], # uninitialized
  127. [ 4.38791518e-305, -2.00000715e+000, 4.17269252e-309]])
  128. """
  129. return (prototype,)
  130. @array_function_from_c_func_and_dispatcher(_multiarray_umath.concatenate)
  131. def concatenate(arrays, axis=None, out=None, *, dtype=None, casting=None):
  132. """
  133. concatenate((a1, a2, ...), axis=0, out=None, dtype=None, casting="same_kind")
  134. Join a sequence of arrays along an existing axis.
  135. Parameters
  136. ----------
  137. a1, a2, ... : sequence of array_like
  138. The arrays must have the same shape, except in the dimension
  139. corresponding to `axis` (the first, by default).
  140. axis : int, optional
  141. The axis along which the arrays will be joined. If axis is None,
  142. arrays are flattened before use. Default is 0.
  143. out : ndarray, optional
  144. If provided, the destination to place the result. The shape must be
  145. correct, matching that of what concatenate would have returned if no
  146. out argument were specified.
  147. dtype : str or dtype
  148. If provided, the destination array will have this dtype. Cannot be
  149. provided together with `out`.
  150. .. versionadded:: 1.20.0
  151. casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional
  152. Controls what kind of data casting may occur. Defaults to 'same_kind'.
  153. .. versionadded:: 1.20.0
  154. Returns
  155. -------
  156. res : ndarray
  157. The concatenated array.
  158. See Also
  159. --------
  160. ma.concatenate : Concatenate function that preserves input masks.
  161. array_split : Split an array into multiple sub-arrays of equal or
  162. near-equal size.
  163. split : Split array into a list of multiple sub-arrays of equal size.
  164. hsplit : Split array into multiple sub-arrays horizontally (column wise).
  165. vsplit : Split array into multiple sub-arrays vertically (row wise).
  166. dsplit : Split array into multiple sub-arrays along the 3rd axis (depth).
  167. stack : Stack a sequence of arrays along a new axis.
  168. block : Assemble arrays from blocks.
  169. hstack : Stack arrays in sequence horizontally (column wise).
  170. vstack : Stack arrays in sequence vertically (row wise).
  171. dstack : Stack arrays in sequence depth wise (along third dimension).
  172. column_stack : Stack 1-D arrays as columns into a 2-D array.
  173. Notes
  174. -----
  175. When one or more of the arrays to be concatenated is a MaskedArray,
  176. this function will return a MaskedArray object instead of an ndarray,
  177. but the input masks are *not* preserved. In cases where a MaskedArray
  178. is expected as input, use the ma.concatenate function from the masked
  179. array module instead.
  180. Examples
  181. --------
  182. >>> a = np.array([[1, 2], [3, 4]])
  183. >>> b = np.array([[5, 6]])
  184. >>> np.concatenate((a, b), axis=0)
  185. array([[1, 2],
  186. [3, 4],
  187. [5, 6]])
  188. >>> np.concatenate((a, b.T), axis=1)
  189. array([[1, 2, 5],
  190. [3, 4, 6]])
  191. >>> np.concatenate((a, b), axis=None)
  192. array([1, 2, 3, 4, 5, 6])
  193. This function will not preserve masking of MaskedArray inputs.
  194. >>> a = np.ma.arange(3)
  195. >>> a[1] = np.ma.masked
  196. >>> b = np.arange(2, 5)
  197. >>> a
  198. masked_array(data=[0, --, 2],
  199. mask=[False, True, False],
  200. fill_value=999999)
  201. >>> b
  202. array([2, 3, 4])
  203. >>> np.concatenate([a, b])
  204. masked_array(data=[0, 1, 2, 2, 3, 4],
  205. mask=False,
  206. fill_value=999999)
  207. >>> np.ma.concatenate([a, b])
  208. masked_array(data=[0, --, 2, 2, 3, 4],
  209. mask=[False, True, False, False, False, False],
  210. fill_value=999999)
  211. """
  212. if out is not None:
  213. # optimize for the typical case where only arrays is provided
  214. arrays = list(arrays)
  215. arrays.append(out)
  216. return arrays
  217. @array_function_from_c_func_and_dispatcher(_multiarray_umath.inner)
  218. def inner(a, b):
  219. """
  220. inner(a, b, /)
  221. Inner product of two arrays.
  222. Ordinary inner product of vectors for 1-D arrays (without complex
  223. conjugation), in higher dimensions a sum product over the last axes.
  224. Parameters
  225. ----------
  226. a, b : array_like
  227. If `a` and `b` are nonscalar, their last dimensions must match.
  228. Returns
  229. -------
  230. out : ndarray
  231. If `a` and `b` are both
  232. scalars or both 1-D arrays then a scalar is returned; otherwise
  233. an array is returned.
  234. ``out.shape = (*a.shape[:-1], *b.shape[:-1])``
  235. Raises
  236. ------
  237. ValueError
  238. If both `a` and `b` are nonscalar and their last dimensions have
  239. different sizes.
  240. See Also
  241. --------
  242. tensordot : Sum products over arbitrary axes.
  243. dot : Generalised matrix product, using second last dimension of `b`.
  244. einsum : Einstein summation convention.
  245. Notes
  246. -----
  247. For vectors (1-D arrays) it computes the ordinary inner-product::
  248. np.inner(a, b) = sum(a[:]*b[:])
  249. More generally, if ``ndim(a) = r > 0`` and ``ndim(b) = s > 0``::
  250. np.inner(a, b) = np.tensordot(a, b, axes=(-1,-1))
  251. or explicitly::
  252. np.inner(a, b)[i0,...,ir-2,j0,...,js-2]
  253. = sum(a[i0,...,ir-2,:]*b[j0,...,js-2,:])
  254. In addition `a` or `b` may be scalars, in which case::
  255. np.inner(a,b) = a*b
  256. Examples
  257. --------
  258. Ordinary inner product for vectors:
  259. >>> a = np.array([1,2,3])
  260. >>> b = np.array([0,1,0])
  261. >>> np.inner(a, b)
  262. 2
  263. Some multidimensional examples:
  264. >>> a = np.arange(24).reshape((2,3,4))
  265. >>> b = np.arange(4)
  266. >>> c = np.inner(a, b)
  267. >>> c.shape
  268. (2, 3)
  269. >>> c
  270. array([[ 14, 38, 62],
  271. [ 86, 110, 134]])
  272. >>> a = np.arange(2).reshape((1,1,2))
  273. >>> b = np.arange(6).reshape((3,2))
  274. >>> c = np.inner(a, b)
  275. >>> c.shape
  276. (1, 1, 3)
  277. >>> c
  278. array([[[1, 3, 5]]])
  279. An example where `b` is a scalar:
  280. >>> np.inner(np.eye(2), 7)
  281. array([[7., 0.],
  282. [0., 7.]])
  283. """
  284. return (a, b)
  285. @array_function_from_c_func_and_dispatcher(_multiarray_umath.where)
  286. def where(condition, x=None, y=None):
  287. """
  288. where(condition, [x, y], /)
  289. Return elements chosen from `x` or `y` depending on `condition`.
  290. .. note::
  291. When only `condition` is provided, this function is a shorthand for
  292. ``np.asarray(condition).nonzero()``. Using `nonzero` directly should be
  293. preferred, as it behaves correctly for subclasses. The rest of this
  294. documentation covers only the case where all three arguments are
  295. provided.
  296. Parameters
  297. ----------
  298. condition : array_like, bool
  299. Where True, yield `x`, otherwise yield `y`.
  300. x, y : array_like
  301. Values from which to choose. `x`, `y` and `condition` need to be
  302. broadcastable to some shape.
  303. Returns
  304. -------
  305. out : ndarray
  306. An array with elements from `x` where `condition` is True, and elements
  307. from `y` elsewhere.
  308. See Also
  309. --------
  310. choose
  311. nonzero : The function that is called when x and y are omitted
  312. Notes
  313. -----
  314. If all the arrays are 1-D, `where` is equivalent to::
  315. [xv if c else yv
  316. for c, xv, yv in zip(condition, x, y)]
  317. Examples
  318. --------
  319. >>> a = np.arange(10)
  320. >>> a
  321. array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
  322. >>> np.where(a < 5, a, 10*a)
  323. array([ 0, 1, 2, 3, 4, 50, 60, 70, 80, 90])
  324. This can be used on multidimensional arrays too:
  325. >>> np.where([[True, False], [True, True]],
  326. ... [[1, 2], [3, 4]],
  327. ... [[9, 8], [7, 6]])
  328. array([[1, 8],
  329. [3, 4]])
  330. The shapes of x, y, and the condition are broadcast together:
  331. >>> x, y = np.ogrid[:3, :4]
  332. >>> np.where(x < y, x, 10 + y) # both x and 10+y are broadcast
  333. array([[10, 0, 0, 0],
  334. [10, 11, 1, 1],
  335. [10, 11, 12, 2]])
  336. >>> a = np.array([[0, 1, 2],
  337. ... [0, 2, 4],
  338. ... [0, 3, 6]])
  339. >>> np.where(a < 4, a, -1) # -1 is broadcast
  340. array([[ 0, 1, 2],
  341. [ 0, 2, -1],
  342. [ 0, 3, -1]])
  343. """
  344. return (condition, x, y)
  345. @array_function_from_c_func_and_dispatcher(_multiarray_umath.lexsort)
  346. def lexsort(keys, axis=None):
  347. """
  348. lexsort(keys, axis=-1)
  349. Perform an indirect stable sort using a sequence of keys.
  350. Given multiple sorting keys, which can be interpreted as columns in a
  351. spreadsheet, lexsort returns an array of integer indices that describes
  352. the sort order by multiple columns. The last key in the sequence is used
  353. for the primary sort order, the second-to-last key for the secondary sort
  354. order, and so on. The keys argument must be a sequence of objects that
  355. can be converted to arrays of the same shape. If a 2D array is provided
  356. for the keys argument, its rows are interpreted as the sorting keys and
  357. sorting is according to the last row, second last row etc.
  358. Parameters
  359. ----------
  360. keys : (k, N) array or tuple containing k (N,)-shaped sequences
  361. The `k` different "columns" to be sorted. The last column (or row if
  362. `keys` is a 2D array) is the primary sort key.
  363. axis : int, optional
  364. Axis to be indirectly sorted. By default, sort over the last axis.
  365. Returns
  366. -------
  367. indices : (N,) ndarray of ints
  368. Array of indices that sort the keys along the specified axis.
  369. See Also
  370. --------
  371. argsort : Indirect sort.
  372. ndarray.sort : In-place sort.
  373. sort : Return a sorted copy of an array.
  374. Examples
  375. --------
  376. Sort names: first by surname, then by name.
  377. >>> surnames = ('Hertz', 'Galilei', 'Hertz')
  378. >>> first_names = ('Heinrich', 'Galileo', 'Gustav')
  379. >>> ind = np.lexsort((first_names, surnames))
  380. >>> ind
  381. array([1, 2, 0])
  382. >>> [surnames[i] + ", " + first_names[i] for i in ind]
  383. ['Galilei, Galileo', 'Hertz, Gustav', 'Hertz, Heinrich']
  384. Sort two columns of numbers:
  385. >>> a = [1,5,1,4,3,4,4] # First column
  386. >>> b = [9,4,0,4,0,2,1] # Second column
  387. >>> ind = np.lexsort((b,a)) # Sort by a, then by b
  388. >>> ind
  389. array([2, 0, 4, 6, 5, 3, 1])
  390. >>> [(a[i],b[i]) for i in ind]
  391. [(1, 0), (1, 9), (3, 0), (4, 1), (4, 2), (4, 4), (5, 4)]
  392. Note that sorting is first according to the elements of ``a``.
  393. Secondary sorting is according to the elements of ``b``.
  394. A normal ``argsort`` would have yielded:
  395. >>> [(a[i],b[i]) for i in np.argsort(a)]
  396. [(1, 9), (1, 0), (3, 0), (4, 4), (4, 2), (4, 1), (5, 4)]
  397. Structured arrays are sorted lexically by ``argsort``:
  398. >>> x = np.array([(1,9), (5,4), (1,0), (4,4), (3,0), (4,2), (4,1)],
  399. ... dtype=np.dtype([('x', int), ('y', int)]))
  400. >>> np.argsort(x) # or np.argsort(x, order=('x', 'y'))
  401. array([2, 0, 4, 6, 5, 3, 1])
  402. """
  403. if isinstance(keys, tuple):
  404. return keys
  405. else:
  406. return (keys,)
  407. @array_function_from_c_func_and_dispatcher(_multiarray_umath.can_cast)
  408. def can_cast(from_, to, casting=None):
  409. """
  410. can_cast(from_, to, casting='safe')
  411. Returns True if cast between data types can occur according to the
  412. casting rule. If from is a scalar or array scalar, also returns
  413. True if the scalar value can be cast without overflow or truncation
  414. to an integer.
  415. Parameters
  416. ----------
  417. from_ : dtype, dtype specifier, scalar, or array
  418. Data type, scalar, or array to cast from.
  419. to : dtype or dtype specifier
  420. Data type to cast to.
  421. casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional
  422. Controls what kind of data casting may occur.
  423. * 'no' means the data types should not be cast at all.
  424. * 'equiv' means only byte-order changes are allowed.
  425. * 'safe' means only casts which can preserve values are allowed.
  426. * 'same_kind' means only safe casts or casts within a kind,
  427. like float64 to float32, are allowed.
  428. * 'unsafe' means any data conversions may be done.
  429. Returns
  430. -------
  431. out : bool
  432. True if cast can occur according to the casting rule.
  433. Notes
  434. -----
  435. .. versionchanged:: 1.17.0
  436. Casting between a simple data type and a structured one is possible only
  437. for "unsafe" casting. Casting to multiple fields is allowed, but
  438. casting from multiple fields is not.
  439. .. versionchanged:: 1.9.0
  440. Casting from numeric to string types in 'safe' casting mode requires
  441. that the string dtype length is long enough to store the maximum
  442. integer/float value converted.
  443. See also
  444. --------
  445. dtype, result_type
  446. Examples
  447. --------
  448. Basic examples
  449. >>> np.can_cast(np.int32, np.int64)
  450. True
  451. >>> np.can_cast(np.float64, complex)
  452. True
  453. >>> np.can_cast(complex, float)
  454. False
  455. >>> np.can_cast('i8', 'f8')
  456. True
  457. >>> np.can_cast('i8', 'f4')
  458. False
  459. >>> np.can_cast('i4', 'S4')
  460. False
  461. Casting scalars
  462. >>> np.can_cast(100, 'i1')
  463. True
  464. >>> np.can_cast(150, 'i1')
  465. False
  466. >>> np.can_cast(150, 'u1')
  467. True
  468. >>> np.can_cast(3.5e100, np.float32)
  469. False
  470. >>> np.can_cast(1000.0, np.float32)
  471. True
  472. Array scalar checks the value, array does not
  473. >>> np.can_cast(np.array(1000.0), np.float32)
  474. True
  475. >>> np.can_cast(np.array([1000.0]), np.float32)
  476. False
  477. Using the casting rules
  478. >>> np.can_cast('i8', 'i8', 'no')
  479. True
  480. >>> np.can_cast('<i8', '>i8', 'no')
  481. False
  482. >>> np.can_cast('<i8', '>i8', 'equiv')
  483. True
  484. >>> np.can_cast('<i4', '>i8', 'equiv')
  485. False
  486. >>> np.can_cast('<i4', '>i8', 'safe')
  487. True
  488. >>> np.can_cast('<i8', '>i4', 'safe')
  489. False
  490. >>> np.can_cast('<i8', '>i4', 'same_kind')
  491. True
  492. >>> np.can_cast('<i8', '>u4', 'same_kind')
  493. False
  494. >>> np.can_cast('<i8', '>u4', 'unsafe')
  495. True
  496. """
  497. return (from_,)
  498. @array_function_from_c_func_and_dispatcher(_multiarray_umath.min_scalar_type)
  499. def min_scalar_type(a):
  500. """
  501. min_scalar_type(a, /)
  502. For scalar ``a``, returns the data type with the smallest size
  503. and smallest scalar kind which can hold its value. For non-scalar
  504. array ``a``, returns the vector's dtype unmodified.
  505. Floating point values are not demoted to integers,
  506. and complex values are not demoted to floats.
  507. Parameters
  508. ----------
  509. a : scalar or array_like
  510. The value whose minimal data type is to be found.
  511. Returns
  512. -------
  513. out : dtype
  514. The minimal data type.
  515. Notes
  516. -----
  517. .. versionadded:: 1.6.0
  518. See Also
  519. --------
  520. result_type, promote_types, dtype, can_cast
  521. Examples
  522. --------
  523. >>> np.min_scalar_type(10)
  524. dtype('uint8')
  525. >>> np.min_scalar_type(-260)
  526. dtype('int16')
  527. >>> np.min_scalar_type(3.1)
  528. dtype('float16')
  529. >>> np.min_scalar_type(1e50)
  530. dtype('float64')
  531. >>> np.min_scalar_type(np.arange(4,dtype='f8'))
  532. dtype('float64')
  533. """
  534. return (a,)
  535. @array_function_from_c_func_and_dispatcher(_multiarray_umath.result_type)
  536. def result_type(*arrays_and_dtypes):
  537. """
  538. result_type(*arrays_and_dtypes)
  539. Returns the type that results from applying the NumPy
  540. type promotion rules to the arguments.
  541. Type promotion in NumPy works similarly to the rules in languages
  542. like C++, with some slight differences. When both scalars and
  543. arrays are used, the array's type takes precedence and the actual value
  544. of the scalar is taken into account.
  545. For example, calculating 3*a, where a is an array of 32-bit floats,
  546. intuitively should result in a 32-bit float output. If the 3 is a
  547. 32-bit integer, the NumPy rules indicate it can't convert losslessly
  548. into a 32-bit float, so a 64-bit float should be the result type.
  549. By examining the value of the constant, '3', we see that it fits in
  550. an 8-bit integer, which can be cast losslessly into the 32-bit float.
  551. Parameters
  552. ----------
  553. arrays_and_dtypes : list of arrays and dtypes
  554. The operands of some operation whose result type is needed.
  555. Returns
  556. -------
  557. out : dtype
  558. The result type.
  559. See also
  560. --------
  561. dtype, promote_types, min_scalar_type, can_cast
  562. Notes
  563. -----
  564. .. versionadded:: 1.6.0
  565. The specific algorithm used is as follows.
  566. Categories are determined by first checking which of boolean,
  567. integer (int/uint), or floating point (float/complex) the maximum
  568. kind of all the arrays and the scalars are.
  569. If there are only scalars or the maximum category of the scalars
  570. is higher than the maximum category of the arrays,
  571. the data types are combined with :func:`promote_types`
  572. to produce the return value.
  573. Otherwise, `min_scalar_type` is called on each array, and
  574. the resulting data types are all combined with :func:`promote_types`
  575. to produce the return value.
  576. The set of int values is not a subset of the uint values for types
  577. with the same number of bits, something not reflected in
  578. :func:`min_scalar_type`, but handled as a special case in `result_type`.
  579. Examples
  580. --------
  581. >>> np.result_type(3, np.arange(7, dtype='i1'))
  582. dtype('int8')
  583. >>> np.result_type('i4', 'c8')
  584. dtype('complex128')
  585. >>> np.result_type(3.0, -2)
  586. dtype('float64')
  587. """
  588. return arrays_and_dtypes
  589. @array_function_from_c_func_and_dispatcher(_multiarray_umath.dot)
  590. def dot(a, b, out=None):
  591. """
  592. dot(a, b, out=None)
  593. Dot product of two arrays. Specifically,
  594. - If both `a` and `b` are 1-D arrays, it is inner product of vectors
  595. (without complex conjugation).
  596. - If both `a` and `b` are 2-D arrays, it is matrix multiplication,
  597. but using :func:`matmul` or ``a @ b`` is preferred.
  598. - If either `a` or `b` is 0-D (scalar), it is equivalent to
  599. :func:`multiply` and using ``numpy.multiply(a, b)`` or ``a * b`` is
  600. preferred.
  601. - If `a` is an N-D array and `b` is a 1-D array, it is a sum product over
  602. the last axis of `a` and `b`.
  603. - If `a` is an N-D array and `b` is an M-D array (where ``M>=2``), it is a
  604. sum product over the last axis of `a` and the second-to-last axis of
  605. `b`::
  606. dot(a, b)[i,j,k,m] = sum(a[i,j,:] * b[k,:,m])
  607. It uses an optimized BLAS library when possible (see `numpy.linalg`).
  608. Parameters
  609. ----------
  610. a : array_like
  611. First argument.
  612. b : array_like
  613. Second argument.
  614. out : ndarray, optional
  615. Output argument. This must have the exact kind that would be returned
  616. if it was not used. In particular, it must have the right type, must be
  617. C-contiguous, and its dtype must be the dtype that would be returned
  618. for `dot(a,b)`. This is a performance feature. Therefore, if these
  619. conditions are not met, an exception is raised, instead of attempting
  620. to be flexible.
  621. Returns
  622. -------
  623. output : ndarray
  624. Returns the dot product of `a` and `b`. If `a` and `b` are both
  625. scalars or both 1-D arrays then a scalar is returned; otherwise
  626. an array is returned.
  627. If `out` is given, then it is returned.
  628. Raises
  629. ------
  630. ValueError
  631. If the last dimension of `a` is not the same size as
  632. the second-to-last dimension of `b`.
  633. See Also
  634. --------
  635. vdot : Complex-conjugating dot product.
  636. tensordot : Sum products over arbitrary axes.
  637. einsum : Einstein summation convention.
  638. matmul : '@' operator as method with out parameter.
  639. linalg.multi_dot : Chained dot product.
  640. Examples
  641. --------
  642. >>> np.dot(3, 4)
  643. 12
  644. Neither argument is complex-conjugated:
  645. >>> np.dot([2j, 3j], [2j, 3j])
  646. (-13+0j)
  647. For 2-D arrays it is the matrix product:
  648. >>> a = [[1, 0], [0, 1]]
  649. >>> b = [[4, 1], [2, 2]]
  650. >>> np.dot(a, b)
  651. array([[4, 1],
  652. [2, 2]])
  653. >>> a = np.arange(3*4*5*6).reshape((3,4,5,6))
  654. >>> b = np.arange(3*4*5*6)[::-1].reshape((5,4,6,3))
  655. >>> np.dot(a, b)[2,3,2,1,2,2]
  656. 499128
  657. >>> sum(a[2,3,2,:] * b[1,2,:,2])
  658. 499128
  659. """
  660. return (a, b, out)
  661. @array_function_from_c_func_and_dispatcher(_multiarray_umath.vdot)
  662. def vdot(a, b):
  663. """
  664. vdot(a, b, /)
  665. Return the dot product of two vectors.
  666. The vdot(`a`, `b`) function handles complex numbers differently than
  667. dot(`a`, `b`). If the first argument is complex the complex conjugate
  668. of the first argument is used for the calculation of the dot product.
  669. Note that `vdot` handles multidimensional arrays differently than `dot`:
  670. it does *not* perform a matrix product, but flattens input arguments
  671. to 1-D vectors first. Consequently, it should only be used for vectors.
  672. Parameters
  673. ----------
  674. a : array_like
  675. If `a` is complex the complex conjugate is taken before calculation
  676. of the dot product.
  677. b : array_like
  678. Second argument to the dot product.
  679. Returns
  680. -------
  681. output : ndarray
  682. Dot product of `a` and `b`. Can be an int, float, or
  683. complex depending on the types of `a` and `b`.
  684. See Also
  685. --------
  686. dot : Return the dot product without using the complex conjugate of the
  687. first argument.
  688. Examples
  689. --------
  690. >>> a = np.array([1+2j,3+4j])
  691. >>> b = np.array([5+6j,7+8j])
  692. >>> np.vdot(a, b)
  693. (70-8j)
  694. >>> np.vdot(b, a)
  695. (70+8j)
  696. Note that higher-dimensional arrays are flattened!
  697. >>> a = np.array([[1, 4], [5, 6]])
  698. >>> b = np.array([[4, 1], [2, 2]])
  699. >>> np.vdot(a, b)
  700. 30
  701. >>> np.vdot(b, a)
  702. 30
  703. >>> 1*4 + 4*1 + 5*2 + 6*2
  704. 30
  705. """
  706. return (a, b)
  707. @array_function_from_c_func_and_dispatcher(_multiarray_umath.bincount)
  708. def bincount(x, weights=None, minlength=None):
  709. """
  710. bincount(x, /, weights=None, minlength=0)
  711. Count number of occurrences of each value in array of non-negative ints.
  712. The number of bins (of size 1) is one larger than the largest value in
  713. `x`. If `minlength` is specified, there will be at least this number
  714. of bins in the output array (though it will be longer if necessary,
  715. depending on the contents of `x`).
  716. Each bin gives the number of occurrences of its index value in `x`.
  717. If `weights` is specified the input array is weighted by it, i.e. if a
  718. value ``n`` is found at position ``i``, ``out[n] += weight[i]`` instead
  719. of ``out[n] += 1``.
  720. Parameters
  721. ----------
  722. x : array_like, 1 dimension, nonnegative ints
  723. Input array.
  724. weights : array_like, optional
  725. Weights, array of the same shape as `x`.
  726. minlength : int, optional
  727. A minimum number of bins for the output array.
  728. .. versionadded:: 1.6.0
  729. Returns
  730. -------
  731. out : ndarray of ints
  732. The result of binning the input array.
  733. The length of `out` is equal to ``np.amax(x)+1``.
  734. Raises
  735. ------
  736. ValueError
  737. If the input is not 1-dimensional, or contains elements with negative
  738. values, or if `minlength` is negative.
  739. TypeError
  740. If the type of the input is float or complex.
  741. See Also
  742. --------
  743. histogram, digitize, unique
  744. Examples
  745. --------
  746. >>> np.bincount(np.arange(5))
  747. array([1, 1, 1, 1, 1])
  748. >>> np.bincount(np.array([0, 1, 1, 3, 2, 1, 7]))
  749. array([1, 3, 1, 1, 0, 0, 0, 1])
  750. >>> x = np.array([0, 1, 1, 3, 2, 1, 7, 23])
  751. >>> np.bincount(x).size == np.amax(x)+1
  752. True
  753. The input array needs to be of integer dtype, otherwise a
  754. TypeError is raised:
  755. >>> np.bincount(np.arange(5, dtype=float))
  756. Traceback (most recent call last):
  757. ...
  758. TypeError: Cannot cast array data from dtype('float64') to dtype('int64')
  759. according to the rule 'safe'
  760. A possible use of ``bincount`` is to perform sums over
  761. variable-size chunks of an array, using the ``weights`` keyword.
  762. >>> w = np.array([0.3, 0.5, 0.2, 0.7, 1., -0.6]) # weights
  763. >>> x = np.array([0, 1, 1, 2, 2, 2])
  764. >>> np.bincount(x, weights=w)
  765. array([ 0.3, 0.7, 1.1])
  766. """
  767. return (x, weights)
  768. @array_function_from_c_func_and_dispatcher(_multiarray_umath.ravel_multi_index)
  769. def ravel_multi_index(multi_index, dims, mode=None, order=None):
  770. """
  771. ravel_multi_index(multi_index, dims, mode='raise', order='C')
  772. Converts a tuple of index arrays into an array of flat
  773. indices, applying boundary modes to the multi-index.
  774. Parameters
  775. ----------
  776. multi_index : tuple of array_like
  777. A tuple of integer arrays, one array for each dimension.
  778. dims : tuple of ints
  779. The shape of array into which the indices from ``multi_index`` apply.
  780. mode : {'raise', 'wrap', 'clip'}, optional
  781. Specifies how out-of-bounds indices are handled. Can specify
  782. either one mode or a tuple of modes, one mode per index.
  783. * 'raise' -- raise an error (default)
  784. * 'wrap' -- wrap around
  785. * 'clip' -- clip to the range
  786. In 'clip' mode, a negative index which would normally
  787. wrap will clip to 0 instead.
  788. order : {'C', 'F'}, optional
  789. Determines whether the multi-index should be viewed as
  790. indexing in row-major (C-style) or column-major
  791. (Fortran-style) order.
  792. Returns
  793. -------
  794. raveled_indices : ndarray
  795. An array of indices into the flattened version of an array
  796. of dimensions ``dims``.
  797. See Also
  798. --------
  799. unravel_index
  800. Notes
  801. -----
  802. .. versionadded:: 1.6.0
  803. Examples
  804. --------
  805. >>> arr = np.array([[3,6,6],[4,5,1]])
  806. >>> np.ravel_multi_index(arr, (7,6))
  807. array([22, 41, 37])
  808. >>> np.ravel_multi_index(arr, (7,6), order='F')
  809. array([31, 41, 13])
  810. >>> np.ravel_multi_index(arr, (4,6), mode='clip')
  811. array([22, 23, 19])
  812. >>> np.ravel_multi_index(arr, (4,4), mode=('clip','wrap'))
  813. array([12, 13, 13])
  814. >>> np.ravel_multi_index((3,1,4,1), (6,7,8,9))
  815. 1621
  816. """
  817. return multi_index
  818. @array_function_from_c_func_and_dispatcher(_multiarray_umath.unravel_index)
  819. def unravel_index(indices, shape=None, order=None):
  820. """
  821. unravel_index(indices, shape, order='C')
  822. Converts a flat index or array of flat indices into a tuple
  823. of coordinate arrays.
  824. Parameters
  825. ----------
  826. indices : array_like
  827. An integer array whose elements are indices into the flattened
  828. version of an array of dimensions ``shape``. Before version 1.6.0,
  829. this function accepted just one index value.
  830. shape : tuple of ints
  831. The shape of the array to use for unraveling ``indices``.
  832. .. versionchanged:: 1.16.0
  833. Renamed from ``dims`` to ``shape``.
  834. order : {'C', 'F'}, optional
  835. Determines whether the indices should be viewed as indexing in
  836. row-major (C-style) or column-major (Fortran-style) order.
  837. .. versionadded:: 1.6.0
  838. Returns
  839. -------
  840. unraveled_coords : tuple of ndarray
  841. Each array in the tuple has the same shape as the ``indices``
  842. array.
  843. See Also
  844. --------
  845. ravel_multi_index
  846. Examples
  847. --------
  848. >>> np.unravel_index([22, 41, 37], (7,6))
  849. (array([3, 6, 6]), array([4, 5, 1]))
  850. >>> np.unravel_index([31, 41, 13], (7,6), order='F')
  851. (array([3, 6, 6]), array([4, 5, 1]))
  852. >>> np.unravel_index(1621, (6,7,8,9))
  853. (3, 1, 4, 1)
  854. """
  855. return (indices,)
  856. @array_function_from_c_func_and_dispatcher(_multiarray_umath.copyto)
  857. def copyto(dst, src, casting=None, where=None):
  858. """
  859. copyto(dst, src, casting='same_kind', where=True)
  860. Copies values from one array to another, broadcasting as necessary.
  861. Raises a TypeError if the `casting` rule is violated, and if
  862. `where` is provided, it selects which elements to copy.
  863. .. versionadded:: 1.7.0
  864. Parameters
  865. ----------
  866. dst : ndarray
  867. The array into which values are copied.
  868. src : array_like
  869. The array from which values are copied.
  870. casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional
  871. Controls what kind of data casting may occur when copying.
  872. * 'no' means the data types should not be cast at all.
  873. * 'equiv' means only byte-order changes are allowed.
  874. * 'safe' means only casts which can preserve values are allowed.
  875. * 'same_kind' means only safe casts or casts within a kind,
  876. like float64 to float32, are allowed.
  877. * 'unsafe' means any data conversions may be done.
  878. where : array_like of bool, optional
  879. A boolean array which is broadcasted to match the dimensions
  880. of `dst`, and selects elements to copy from `src` to `dst`
  881. wherever it contains the value True.
  882. Examples
  883. --------
  884. >>> A = np.array([4, 5, 6])
  885. >>> B = [1, 2, 3]
  886. >>> np.copyto(A, B)
  887. >>> A
  888. array([1, 2, 3])
  889. >>> A = np.array([[1, 2, 3], [4, 5, 6]])
  890. >>> B = [[4, 5, 6], [7, 8, 9]]
  891. >>> np.copyto(A, B)
  892. >>> A
  893. array([[4, 5, 6],
  894. [7, 8, 9]])
  895. """
  896. return (dst, src, where)
  897. @array_function_from_c_func_and_dispatcher(_multiarray_umath.putmask)
  898. def putmask(a, mask, values):
  899. """
  900. putmask(a, mask, values)
  901. Changes elements of an array based on conditional and input values.
  902. Sets ``a.flat[n] = values[n]`` for each n where ``mask.flat[n]==True``.
  903. If `values` is not the same size as `a` and `mask` then it will repeat.
  904. This gives behavior different from ``a[mask] = values``.
  905. Parameters
  906. ----------
  907. a : ndarray
  908. Target array.
  909. mask : array_like
  910. Boolean mask array. It has to be the same shape as `a`.
  911. values : array_like
  912. Values to put into `a` where `mask` is True. If `values` is smaller
  913. than `a` it will be repeated.
  914. See Also
  915. --------
  916. place, put, take, copyto
  917. Examples
  918. --------
  919. >>> x = np.arange(6).reshape(2, 3)
  920. >>> np.putmask(x, x>2, x**2)
  921. >>> x
  922. array([[ 0, 1, 2],
  923. [ 9, 16, 25]])
  924. If `values` is smaller than `a` it is repeated:
  925. >>> x = np.arange(5)
  926. >>> np.putmask(x, x>1, [-33, -44])
  927. >>> x
  928. array([ 0, 1, -33, -44, -33])
  929. """
  930. return (a, mask, values)
  931. @array_function_from_c_func_and_dispatcher(_multiarray_umath.packbits)
  932. def packbits(a, axis=None, bitorder='big'):
  933. """
  934. packbits(a, /, axis=None, bitorder='big')
  935. Packs the elements of a binary-valued array into bits in a uint8 array.
  936. The result is padded to full bytes by inserting zero bits at the end.
  937. Parameters
  938. ----------
  939. a : array_like
  940. An array of integers or booleans whose elements should be packed to
  941. bits.
  942. axis : int, optional
  943. The dimension over which bit-packing is done.
  944. ``None`` implies packing the flattened array.
  945. bitorder : {'big', 'little'}, optional
  946. The order of the input bits. 'big' will mimic bin(val),
  947. ``[0, 0, 0, 0, 0, 0, 1, 1] => 3 = 0b00000011``, 'little' will
  948. reverse the order so ``[1, 1, 0, 0, 0, 0, 0, 0] => 3``.
  949. Defaults to 'big'.
  950. .. versionadded:: 1.17.0
  951. Returns
  952. -------
  953. packed : ndarray
  954. Array of type uint8 whose elements represent bits corresponding to the
  955. logical (0 or nonzero) value of the input elements. The shape of
  956. `packed` has the same number of dimensions as the input (unless `axis`
  957. is None, in which case the output is 1-D).
  958. See Also
  959. --------
  960. unpackbits: Unpacks elements of a uint8 array into a binary-valued output
  961. array.
  962. Examples
  963. --------
  964. >>> a = np.array([[[1,0,1],
  965. ... [0,1,0]],
  966. ... [[1,1,0],
  967. ... [0,0,1]]])
  968. >>> b = np.packbits(a, axis=-1)
  969. >>> b
  970. array([[[160],
  971. [ 64]],
  972. [[192],
  973. [ 32]]], dtype=uint8)
  974. Note that in binary 160 = 1010 0000, 64 = 0100 0000, 192 = 1100 0000,
  975. and 32 = 0010 0000.
  976. """
  977. return (a,)
  978. @array_function_from_c_func_and_dispatcher(_multiarray_umath.unpackbits)
  979. def unpackbits(a, axis=None, count=None, bitorder='big'):
  980. """
  981. unpackbits(a, /, axis=None, count=None, bitorder='big')
  982. Unpacks elements of a uint8 array into a binary-valued output array.
  983. Each element of `a` represents a bit-field that should be unpacked
  984. into a binary-valued output array. The shape of the output array is
  985. either 1-D (if `axis` is ``None``) or the same shape as the input
  986. array with unpacking done along the axis specified.
  987. Parameters
  988. ----------
  989. a : ndarray, uint8 type
  990. Input array.
  991. axis : int, optional
  992. The dimension over which bit-unpacking is done.
  993. ``None`` implies unpacking the flattened array.
  994. count : int or None, optional
  995. The number of elements to unpack along `axis`, provided as a way
  996. of undoing the effect of packing a size that is not a multiple
  997. of eight. A non-negative number means to only unpack `count`
  998. bits. A negative number means to trim off that many bits from
  999. the end. ``None`` means to unpack the entire array (the
  1000. default). Counts larger than the available number of bits will
  1001. add zero padding to the output. Negative counts must not
  1002. exceed the available number of bits.
  1003. .. versionadded:: 1.17.0
  1004. bitorder : {'big', 'little'}, optional
  1005. The order of the returned bits. 'big' will mimic bin(val),
  1006. ``3 = 0b00000011 => [0, 0, 0, 0, 0, 0, 1, 1]``, 'little' will reverse
  1007. the order to ``[1, 1, 0, 0, 0, 0, 0, 0]``.
  1008. Defaults to 'big'.
  1009. .. versionadded:: 1.17.0
  1010. Returns
  1011. -------
  1012. unpacked : ndarray, uint8 type
  1013. The elements are binary-valued (0 or 1).
  1014. See Also
  1015. --------
  1016. packbits : Packs the elements of a binary-valued array into bits in
  1017. a uint8 array.
  1018. Examples
  1019. --------
  1020. >>> a = np.array([[2], [7], [23]], dtype=np.uint8)
  1021. >>> a
  1022. array([[ 2],
  1023. [ 7],
  1024. [23]], dtype=uint8)
  1025. >>> b = np.unpackbits(a, axis=1)
  1026. >>> b
  1027. array([[0, 0, 0, 0, 0, 0, 1, 0],
  1028. [0, 0, 0, 0, 0, 1, 1, 1],
  1029. [0, 0, 0, 1, 0, 1, 1, 1]], dtype=uint8)
  1030. >>> c = np.unpackbits(a, axis=1, count=-3)
  1031. >>> c
  1032. array([[0, 0, 0, 0, 0],
  1033. [0, 0, 0, 0, 0],
  1034. [0, 0, 0, 1, 0]], dtype=uint8)
  1035. >>> p = np.packbits(b, axis=0)
  1036. >>> np.unpackbits(p, axis=0)
  1037. array([[0, 0, 0, 0, 0, 0, 1, 0],
  1038. [0, 0, 0, 0, 0, 1, 1, 1],
  1039. [0, 0, 0, 1, 0, 1, 1, 1],
  1040. [0, 0, 0, 0, 0, 0, 0, 0],
  1041. [0, 0, 0, 0, 0, 0, 0, 0],
  1042. [0, 0, 0, 0, 0, 0, 0, 0],
  1043. [0, 0, 0, 0, 0, 0, 0, 0],
  1044. [0, 0, 0, 0, 0, 0, 0, 0]], dtype=uint8)
  1045. >>> np.array_equal(b, np.unpackbits(p, axis=0, count=b.shape[0]))
  1046. True
  1047. """
  1048. return (a,)
  1049. @array_function_from_c_func_and_dispatcher(_multiarray_umath.shares_memory)
  1050. def shares_memory(a, b, max_work=None):
  1051. """
  1052. shares_memory(a, b, /, max_work=None)
  1053. Determine if two arrays share memory.
  1054. .. warning::
  1055. This function can be exponentially slow for some inputs, unless
  1056. `max_work` is set to a finite number or ``MAY_SHARE_BOUNDS``.
  1057. If in doubt, use `numpy.may_share_memory` instead.
  1058. Parameters
  1059. ----------
  1060. a, b : ndarray
  1061. Input arrays
  1062. max_work : int, optional
  1063. Effort to spend on solving the overlap problem (maximum number
  1064. of candidate solutions to consider). The following special
  1065. values are recognized:
  1066. max_work=MAY_SHARE_EXACT (default)
  1067. The problem is solved exactly. In this case, the function returns
  1068. True only if there is an element shared between the arrays. Finding
  1069. the exact solution may take extremely long in some cases.
  1070. max_work=MAY_SHARE_BOUNDS
  1071. Only the memory bounds of a and b are checked.
  1072. Raises
  1073. ------
  1074. numpy.TooHardError
  1075. Exceeded max_work.
  1076. Returns
  1077. -------
  1078. out : bool
  1079. See Also
  1080. --------
  1081. may_share_memory
  1082. Examples
  1083. --------
  1084. >>> x = np.array([1, 2, 3, 4])
  1085. >>> np.shares_memory(x, np.array([5, 6, 7]))
  1086. False
  1087. >>> np.shares_memory(x[::2], x)
  1088. True
  1089. >>> np.shares_memory(x[::2], x[1::2])
  1090. False
  1091. Checking whether two arrays share memory is NP-complete, and
  1092. runtime may increase exponentially in the number of
  1093. dimensions. Hence, `max_work` should generally be set to a finite
  1094. number, as it is possible to construct examples that take
  1095. extremely long to run:
  1096. >>> from numpy.lib.stride_tricks import as_strided
  1097. >>> x = np.zeros([192163377], dtype=np.int8)
  1098. >>> x1 = as_strided(x, strides=(36674, 61119, 85569), shape=(1049, 1049, 1049))
  1099. >>> x2 = as_strided(x[64023025:], strides=(12223, 12224, 1), shape=(1049, 1049, 1))
  1100. >>> np.shares_memory(x1, x2, max_work=1000)
  1101. Traceback (most recent call last):
  1102. ...
  1103. numpy.TooHardError: Exceeded max_work
  1104. Running ``np.shares_memory(x1, x2)`` without `max_work` set takes
  1105. around 1 minute for this case. It is possible to find problems
  1106. that take still significantly longer.
  1107. """
  1108. return (a, b)
  1109. @array_function_from_c_func_and_dispatcher(_multiarray_umath.may_share_memory)
  1110. def may_share_memory(a, b, max_work=None):
  1111. """
  1112. may_share_memory(a, b, /, max_work=None)
  1113. Determine if two arrays might share memory
  1114. A return of True does not necessarily mean that the two arrays
  1115. share any element. It just means that they *might*.
  1116. Only the memory bounds of a and b are checked by default.
  1117. Parameters
  1118. ----------
  1119. a, b : ndarray
  1120. Input arrays
  1121. max_work : int, optional
  1122. Effort to spend on solving the overlap problem. See
  1123. `shares_memory` for details. Default for ``may_share_memory``
  1124. is to do a bounds check.
  1125. Returns
  1126. -------
  1127. out : bool
  1128. See Also
  1129. --------
  1130. shares_memory
  1131. Examples
  1132. --------
  1133. >>> np.may_share_memory(np.array([1,2]), np.array([5,8,9]))
  1134. False
  1135. >>> x = np.zeros([3, 4])
  1136. >>> np.may_share_memory(x[:,0], x[:,1])
  1137. True
  1138. """
  1139. return (a, b)
  1140. @array_function_from_c_func_and_dispatcher(_multiarray_umath.is_busday)
  1141. def is_busday(dates, weekmask=None, holidays=None, busdaycal=None, out=None):
  1142. """
  1143. is_busday(dates, weekmask='1111100', holidays=None, busdaycal=None, out=None)
  1144. Calculates which of the given dates are valid days, and which are not.
  1145. .. versionadded:: 1.7.0
  1146. Parameters
  1147. ----------
  1148. dates : array_like of datetime64[D]
  1149. The array of dates to process.
  1150. weekmask : str or array_like of bool, optional
  1151. A seven-element array indicating which of Monday through Sunday are
  1152. valid days. May be specified as a length-seven list or array, like
  1153. [1,1,1,1,1,0,0]; a length-seven string, like '1111100'; or a string
  1154. like "Mon Tue Wed Thu Fri", made up of 3-character abbreviations for
  1155. weekdays, optionally separated by white space. Valid abbreviations
  1156. are: Mon Tue Wed Thu Fri Sat Sun
  1157. holidays : array_like of datetime64[D], optional
  1158. An array of dates to consider as invalid dates. They may be
  1159. specified in any order, and NaT (not-a-time) dates are ignored.
  1160. This list is saved in a normalized form that is suited for
  1161. fast calculations of valid days.
  1162. busdaycal : busdaycalendar, optional
  1163. A `busdaycalendar` object which specifies the valid days. If this
  1164. parameter is provided, neither weekmask nor holidays may be
  1165. provided.
  1166. out : array of bool, optional
  1167. If provided, this array is filled with the result.
  1168. Returns
  1169. -------
  1170. out : array of bool
  1171. An array with the same shape as ``dates``, containing True for
  1172. each valid day, and False for each invalid day.
  1173. See Also
  1174. --------
  1175. busdaycalendar : An object that specifies a custom set of valid days.
  1176. busday_offset : Applies an offset counted in valid days.
  1177. busday_count : Counts how many valid days are in a half-open date range.
  1178. Examples
  1179. --------
  1180. >>> # The weekdays are Friday, Saturday, and Monday
  1181. ... np.is_busday(['2011-07-01', '2011-07-02', '2011-07-18'],
  1182. ... holidays=['2011-07-01', '2011-07-04', '2011-07-17'])
  1183. array([False, False, True])
  1184. """
  1185. return (dates, weekmask, holidays, out)
  1186. @array_function_from_c_func_and_dispatcher(_multiarray_umath.busday_offset)
  1187. def busday_offset(dates, offsets, roll=None, weekmask=None, holidays=None,
  1188. busdaycal=None, out=None):
  1189. """
  1190. busday_offset(dates, offsets, roll='raise', weekmask='1111100', holidays=None, busdaycal=None, out=None)
  1191. First adjusts the date to fall on a valid day according to
  1192. the ``roll`` rule, then applies offsets to the given dates
  1193. counted in valid days.
  1194. .. versionadded:: 1.7.0
  1195. Parameters
  1196. ----------
  1197. dates : array_like of datetime64[D]
  1198. The array of dates to process.
  1199. offsets : array_like of int
  1200. The array of offsets, which is broadcast with ``dates``.
  1201. roll : {'raise', 'nat', 'forward', 'following', 'backward', 'preceding', 'modifiedfollowing', 'modifiedpreceding'}, optional
  1202. How to treat dates that do not fall on a valid day. The default
  1203. is 'raise'.
  1204. * 'raise' means to raise an exception for an invalid day.
  1205. * 'nat' means to return a NaT (not-a-time) for an invalid day.
  1206. * 'forward' and 'following' mean to take the first valid day
  1207. later in time.
  1208. * 'backward' and 'preceding' mean to take the first valid day
  1209. earlier in time.
  1210. * 'modifiedfollowing' means to take the first valid day
  1211. later in time unless it is across a Month boundary, in which
  1212. case to take the first valid day earlier in time.
  1213. * 'modifiedpreceding' means to take the first valid day
  1214. earlier in time unless it is across a Month boundary, in which
  1215. case to take the first valid day later in time.
  1216. weekmask : str or array_like of bool, optional
  1217. A seven-element array indicating which of Monday through Sunday are
  1218. valid days. May be specified as a length-seven list or array, like
  1219. [1,1,1,1,1,0,0]; a length-seven string, like '1111100'; or a string
  1220. like "Mon Tue Wed Thu Fri", made up of 3-character abbreviations for
  1221. weekdays, optionally separated by white space. Valid abbreviations
  1222. are: Mon Tue Wed Thu Fri Sat Sun
  1223. holidays : array_like of datetime64[D], optional
  1224. An array of dates to consider as invalid dates. They may be
  1225. specified in any order, and NaT (not-a-time) dates are ignored.
  1226. This list is saved in a normalized form that is suited for
  1227. fast calculations of valid days.
  1228. busdaycal : busdaycalendar, optional
  1229. A `busdaycalendar` object which specifies the valid days. If this
  1230. parameter is provided, neither weekmask nor holidays may be
  1231. provided.
  1232. out : array of datetime64[D], optional
  1233. If provided, this array is filled with the result.
  1234. Returns
  1235. -------
  1236. out : array of datetime64[D]
  1237. An array with a shape from broadcasting ``dates`` and ``offsets``
  1238. together, containing the dates with offsets applied.
  1239. See Also
  1240. --------
  1241. busdaycalendar : An object that specifies a custom set of valid days.
  1242. is_busday : Returns a boolean array indicating valid days.
  1243. busday_count : Counts how many valid days are in a half-open date range.
  1244. Examples
  1245. --------
  1246. >>> # First business day in October 2011 (not accounting for holidays)
  1247. ... np.busday_offset('2011-10', 0, roll='forward')
  1248. numpy.datetime64('2011-10-03')
  1249. >>> # Last business day in February 2012 (not accounting for holidays)
  1250. ... np.busday_offset('2012-03', -1, roll='forward')
  1251. numpy.datetime64('2012-02-29')
  1252. >>> # Third Wednesday in January 2011
  1253. ... np.busday_offset('2011-01', 2, roll='forward', weekmask='Wed')
  1254. numpy.datetime64('2011-01-19')
  1255. >>> # 2012 Mother's Day in Canada and the U.S.
  1256. ... np.busday_offset('2012-05', 1, roll='forward', weekmask='Sun')
  1257. numpy.datetime64('2012-05-13')
  1258. >>> # First business day on or after a date
  1259. ... np.busday_offset('2011-03-20', 0, roll='forward')
  1260. numpy.datetime64('2011-03-21')
  1261. >>> np.busday_offset('2011-03-22', 0, roll='forward')
  1262. numpy.datetime64('2011-03-22')
  1263. >>> # First business day after a date
  1264. ... np.busday_offset('2011-03-20', 1, roll='backward')
  1265. numpy.datetime64('2011-03-21')
  1266. >>> np.busday_offset('2011-03-22', 1, roll='backward')
  1267. numpy.datetime64('2011-03-23')
  1268. """
  1269. return (dates, offsets, weekmask, holidays, out)
  1270. @array_function_from_c_func_and_dispatcher(_multiarray_umath.busday_count)
  1271. def busday_count(begindates, enddates, weekmask=None, holidays=None,
  1272. busdaycal=None, out=None):
  1273. """
  1274. busday_count(begindates, enddates, weekmask='1111100', holidays=[], busdaycal=None, out=None)
  1275. Counts the number of valid days between `begindates` and
  1276. `enddates`, not including the day of `enddates`.
  1277. If ``enddates`` specifies a date value that is earlier than the
  1278. corresponding ``begindates`` date value, the count will be negative.
  1279. .. versionadded:: 1.7.0
  1280. Parameters
  1281. ----------
  1282. begindates : array_like of datetime64[D]
  1283. The array of the first dates for counting.
  1284. enddates : array_like of datetime64[D]
  1285. The array of the end dates for counting, which are excluded
  1286. from the count themselves.
  1287. weekmask : str or array_like of bool, optional
  1288. A seven-element array indicating which of Monday through Sunday are
  1289. valid days. May be specified as a length-seven list or array, like
  1290. [1,1,1,1,1,0,0]; a length-seven string, like '1111100'; or a string
  1291. like "Mon Tue Wed Thu Fri", made up of 3-character abbreviations for
  1292. weekdays, optionally separated by white space. Valid abbreviations
  1293. are: Mon Tue Wed Thu Fri Sat Sun
  1294. holidays : array_like of datetime64[D], optional
  1295. An array of dates to consider as invalid dates. They may be
  1296. specified in any order, and NaT (not-a-time) dates are ignored.
  1297. This list is saved in a normalized form that is suited for
  1298. fast calculations of valid days.
  1299. busdaycal : busdaycalendar, optional
  1300. A `busdaycalendar` object which specifies the valid days. If this
  1301. parameter is provided, neither weekmask nor holidays may be
  1302. provided.
  1303. out : array of int, optional
  1304. If provided, this array is filled with the result.
  1305. Returns
  1306. -------
  1307. out : array of int
  1308. An array with a shape from broadcasting ``begindates`` and ``enddates``
  1309. together, containing the number of valid days between
  1310. the begin and end dates.
  1311. See Also
  1312. --------
  1313. busdaycalendar : An object that specifies a custom set of valid days.
  1314. is_busday : Returns a boolean array indicating valid days.
  1315. busday_offset : Applies an offset counted in valid days.
  1316. Examples
  1317. --------
  1318. >>> # Number of weekdays in January 2011
  1319. ... np.busday_count('2011-01', '2011-02')
  1320. 21
  1321. >>> # Number of weekdays in 2011
  1322. >>> np.busday_count('2011', '2012')
  1323. 260
  1324. >>> # Number of Saturdays in 2011
  1325. ... np.busday_count('2011', '2012', weekmask='Sat')
  1326. 53
  1327. """
  1328. return (begindates, enddates, weekmask, holidays, out)
  1329. @array_function_from_c_func_and_dispatcher(
  1330. _multiarray_umath.datetime_as_string)
  1331. def datetime_as_string(arr, unit=None, timezone=None, casting=None):
  1332. """
  1333. datetime_as_string(arr, unit=None, timezone='naive', casting='same_kind')
  1334. Convert an array of datetimes into an array of strings.
  1335. Parameters
  1336. ----------
  1337. arr : array_like of datetime64
  1338. The array of UTC timestamps to format.
  1339. unit : str
  1340. One of None, 'auto', or a :ref:`datetime unit <arrays.dtypes.dateunits>`.
  1341. timezone : {'naive', 'UTC', 'local'} or tzinfo
  1342. Timezone information to use when displaying the datetime. If 'UTC', end
  1343. with a Z to indicate UTC time. If 'local', convert to the local timezone
  1344. first, and suffix with a +-#### timezone offset. If a tzinfo object,
  1345. then do as with 'local', but use the specified timezone.
  1346. casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}
  1347. Casting to allow when changing between datetime units.
  1348. Returns
  1349. -------
  1350. str_arr : ndarray
  1351. An array of strings the same shape as `arr`.
  1352. Examples
  1353. --------
  1354. >>> import pytz
  1355. >>> d = np.arange('2002-10-27T04:30', 4*60, 60, dtype='M8[m]')
  1356. >>> d
  1357. array(['2002-10-27T04:30', '2002-10-27T05:30', '2002-10-27T06:30',
  1358. '2002-10-27T07:30'], dtype='datetime64[m]')
  1359. Setting the timezone to UTC shows the same information, but with a Z suffix
  1360. >>> np.datetime_as_string(d, timezone='UTC')
  1361. array(['2002-10-27T04:30Z', '2002-10-27T05:30Z', '2002-10-27T06:30Z',
  1362. '2002-10-27T07:30Z'], dtype='<U35')
  1363. Note that we picked datetimes that cross a DST boundary. Passing in a
  1364. ``pytz`` timezone object will print the appropriate offset
  1365. >>> np.datetime_as_string(d, timezone=pytz.timezone('US/Eastern'))
  1366. array(['2002-10-27T00:30-0400', '2002-10-27T01:30-0400',
  1367. '2002-10-27T01:30-0500', '2002-10-27T02:30-0500'], dtype='<U39')
  1368. Passing in a unit will change the precision
  1369. >>> np.datetime_as_string(d, unit='h')
  1370. array(['2002-10-27T04', '2002-10-27T05', '2002-10-27T06', '2002-10-27T07'],
  1371. dtype='<U32')
  1372. >>> np.datetime_as_string(d, unit='s')
  1373. array(['2002-10-27T04:30:00', '2002-10-27T05:30:00', '2002-10-27T06:30:00',
  1374. '2002-10-27T07:30:00'], dtype='<U38')
  1375. 'casting' can be used to specify whether precision can be changed
  1376. >>> np.datetime_as_string(d, unit='h', casting='safe')
  1377. Traceback (most recent call last):
  1378. ...
  1379. TypeError: Cannot create a datetime string as units 'h' from a NumPy
  1380. datetime with units 'm' according to the rule 'safe'
  1381. """
  1382. return (arr,)