multiarray.py 54 KB

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