multiarray.py 50 KB

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