multiarray.py 52 KB

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