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