multiarray.py 55 KB

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