multiarray.py 53 KB

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