multiarray.py 57 KB

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