m2m模型翻译
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1690 lines
54 KiB

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