multiarray.py 55 KB

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