Coverage for /var/srv/projects/api.amasfac.comuna18.com/tmp/venv/lib/python3.9/site-packages/numpy/core/multiarray.py: 74%
104 statements
« prev ^ index » next coverage.py v6.4.4, created at 2023-07-17 14:22 -0600
« prev ^ index » next coverage.py v6.4.4, created at 2023-07-17 14:22 -0600
1"""
2Create the numpy.core.multiarray namespace for backward compatibility. In v1.16
3the multiarray and umath c-extension modules were merged into a single
4_multiarray_umath extension module. So we replicate the old namespace
5by importing from the extension module.
7"""
9import functools
10from . import overrides
11from . import _multiarray_umath
12from ._multiarray_umath import * # noqa: F403
13# These imports are needed for backward compatibility,
14# do not change them. issue gh-15518
15# _get_ndarray_c_version is semi-public, on purpose not added to __all__
16from ._multiarray_umath import (
17 _fastCopyAndTranspose, _flagdict, from_dlpack, _insert, _reconstruct,
18 _vec_string, _ARRAY_API, _monotonicity, _get_ndarray_c_version,
19 _get_madvise_hugepage, _set_madvise_hugepage,
20 )
22__all__ = [
23 '_ARRAY_API', 'ALLOW_THREADS', 'BUFSIZE', 'CLIP', 'DATETIMEUNITS',
24 'ITEM_HASOBJECT', 'ITEM_IS_POINTER', 'LIST_PICKLE', 'MAXDIMS',
25 'MAY_SHARE_BOUNDS', 'MAY_SHARE_EXACT', 'NEEDS_INIT', 'NEEDS_PYAPI',
26 'RAISE', 'USE_GETITEM', 'USE_SETITEM', 'WRAP', '_fastCopyAndTranspose',
27 '_flagdict', 'from_dlpack', '_insert', '_reconstruct', '_vec_string',
28 '_monotonicity', 'add_docstring', 'arange', 'array', 'asarray',
29 'asanyarray', 'ascontiguousarray', 'asfortranarray', 'bincount',
30 'broadcast', 'busday_count', 'busday_offset', 'busdaycalendar', 'can_cast',
31 'compare_chararrays', 'concatenate', 'copyto', 'correlate', 'correlate2',
32 'count_nonzero', 'c_einsum', 'datetime_as_string', 'datetime_data',
33 'dot', 'dragon4_positional', 'dragon4_scientific', 'dtype',
34 'empty', 'empty_like', 'error', 'flagsobj', 'flatiter', 'format_longfloat',
35 'frombuffer', 'fromfile', 'fromiter', 'fromstring',
36 'get_handler_name', 'get_handler_version', 'inner', 'interp',
37 'interp_complex', 'is_busday', 'lexsort', 'matmul', 'may_share_memory',
38 'min_scalar_type', 'ndarray', 'nditer', 'nested_iters',
39 'normalize_axis_index', 'packbits', 'promote_types', 'putmask',
40 'ravel_multi_index', 'result_type', 'scalar', 'set_datetimeparse_function',
41 'set_legacy_print_mode', 'set_numeric_ops', 'set_string_function',
42 'set_typeDict', 'shares_memory', 'tracemalloc_domain', 'typeinfo',
43 'unpackbits', 'unravel_index', 'vdot', 'where', 'zeros']
45# For backward compatibility, make sure pickle imports these functions from here
46_reconstruct.__module__ = 'numpy.core.multiarray'
47scalar.__module__ = 'numpy.core.multiarray'
50from_dlpack.__module__ = 'numpy'
51arange.__module__ = 'numpy'
52array.__module__ = 'numpy'
53asarray.__module__ = 'numpy'
54asanyarray.__module__ = 'numpy'
55ascontiguousarray.__module__ = 'numpy'
56asfortranarray.__module__ = 'numpy'
57datetime_data.__module__ = 'numpy'
58empty.__module__ = 'numpy'
59frombuffer.__module__ = 'numpy'
60fromfile.__module__ = 'numpy'
61fromiter.__module__ = 'numpy'
62frompyfunc.__module__ = 'numpy'
63fromstring.__module__ = 'numpy'
64geterrobj.__module__ = 'numpy'
65may_share_memory.__module__ = 'numpy'
66nested_iters.__module__ = 'numpy'
67promote_types.__module__ = 'numpy'
68set_numeric_ops.__module__ = 'numpy'
69seterrobj.__module__ = 'numpy'
70zeros.__module__ = 'numpy'
73# We can't verify dispatcher signatures because NumPy's C functions don't
74# support introspection.
75array_function_from_c_func_and_dispatcher = functools.partial(
76 overrides.array_function_from_dispatcher,
77 module='numpy', docs_from_dispatcher=True, verify=False)
80@array_function_from_c_func_and_dispatcher(_multiarray_umath.empty_like)
81def empty_like(prototype, dtype=None, order=None, subok=None, shape=None):
82 """
83 empty_like(prototype, dtype=None, order='K', subok=True, shape=None)
85 Return a new array with the same shape and type as a given array.
87 Parameters
88 ----------
89 prototype : array_like
90 The shape and data-type of `prototype` define these same attributes
91 of the returned array.
92 dtype : data-type, optional
93 Overrides the data type of the result.
95 .. versionadded:: 1.6.0
96 order : {'C', 'F', 'A', or 'K'}, optional
97 Overrides the memory layout of the result. 'C' means C-order,
98 'F' means F-order, 'A' means 'F' if `prototype` is Fortran
99 contiguous, 'C' otherwise. 'K' means match the layout of `prototype`
100 as closely as possible.
102 .. versionadded:: 1.6.0
103 subok : bool, optional.
104 If True, then the newly created array will use the sub-class
105 type of `prototype`, otherwise it will be a base-class array. Defaults
106 to True.
107 shape : int or sequence of ints, optional.
108 Overrides the shape of the result. If order='K' and the number of
109 dimensions is unchanged, will try to keep order, otherwise,
110 order='C' is implied.
112 .. versionadded:: 1.17.0
114 Returns
115 -------
116 out : ndarray
117 Array of uninitialized (arbitrary) data with the same
118 shape and type as `prototype`.
120 See Also
121 --------
122 ones_like : Return an array of ones with shape and type of input.
123 zeros_like : Return an array of zeros with shape and type of input.
124 full_like : Return a new array with shape of input filled with value.
125 empty : Return a new uninitialized array.
127 Notes
128 -----
129 This function does *not* initialize the returned array; to do that use
130 `zeros_like` or `ones_like` instead. It may be marginally faster than
131 the functions that do set the array values.
133 Examples
134 --------
135 >>> a = ([1,2,3], [4,5,6]) # a is array-like
136 >>> np.empty_like(a)
137 array([[-1073741821, -1073741821, 3], # uninitialized
138 [ 0, 0, -1073741821]])
139 >>> a = np.array([[1., 2., 3.],[4.,5.,6.]])
140 >>> np.empty_like(a)
141 array([[ -2.00000715e+000, 1.48219694e-323, -2.00000572e+000], # uninitialized
142 [ 4.38791518e-305, -2.00000715e+000, 4.17269252e-309]])
144 """
145 return (prototype,)
148@array_function_from_c_func_and_dispatcher(_multiarray_umath.concatenate)
149def concatenate(arrays, axis=None, out=None, *, dtype=None, casting=None):
150 """
151 concatenate((a1, a2, ...), axis=0, out=None, dtype=None, casting="same_kind")
153 Join a sequence of arrays along an existing axis.
155 Parameters
156 ----------
157 a1, a2, ... : sequence of array_like
158 The arrays must have the same shape, except in the dimension
159 corresponding to `axis` (the first, by default).
160 axis : int, optional
161 The axis along which the arrays will be joined. If axis is None,
162 arrays are flattened before use. Default is 0.
163 out : ndarray, optional
164 If provided, the destination to place the result. The shape must be
165 correct, matching that of what concatenate would have returned if no
166 out argument were specified.
167 dtype : str or dtype
168 If provided, the destination array will have this dtype. Cannot be
169 provided together with `out`.
171 .. versionadded:: 1.20.0
173 casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional
174 Controls what kind of data casting may occur. Defaults to 'same_kind'.
176 .. versionadded:: 1.20.0
178 Returns
179 -------
180 res : ndarray
181 The concatenated array.
183 See Also
184 --------
185 ma.concatenate : Concatenate function that preserves input masks.
186 array_split : Split an array into multiple sub-arrays of equal or
187 near-equal size.
188 split : Split array into a list of multiple sub-arrays of equal size.
189 hsplit : Split array into multiple sub-arrays horizontally (column wise).
190 vsplit : Split array into multiple sub-arrays vertically (row wise).
191 dsplit : Split array into multiple sub-arrays along the 3rd axis (depth).
192 stack : Stack a sequence of arrays along a new axis.
193 block : Assemble arrays from blocks.
194 hstack : Stack arrays in sequence horizontally (column wise).
195 vstack : Stack arrays in sequence vertically (row wise).
196 dstack : Stack arrays in sequence depth wise (along third dimension).
197 column_stack : Stack 1-D arrays as columns into a 2-D array.
199 Notes
200 -----
201 When one or more of the arrays to be concatenated is a MaskedArray,
202 this function will return a MaskedArray object instead of an ndarray,
203 but the input masks are *not* preserved. In cases where a MaskedArray
204 is expected as input, use the ma.concatenate function from the masked
205 array module instead.
207 Examples
208 --------
209 >>> a = np.array([[1, 2], [3, 4]])
210 >>> b = np.array([[5, 6]])
211 >>> np.concatenate((a, b), axis=0)
212 array([[1, 2],
213 [3, 4],
214 [5, 6]])
215 >>> np.concatenate((a, b.T), axis=1)
216 array([[1, 2, 5],
217 [3, 4, 6]])
218 >>> np.concatenate((a, b), axis=None)
219 array([1, 2, 3, 4, 5, 6])
221 This function will not preserve masking of MaskedArray inputs.
223 >>> a = np.ma.arange(3)
224 >>> a[1] = np.ma.masked
225 >>> b = np.arange(2, 5)
226 >>> a
227 masked_array(data=[0, --, 2],
228 mask=[False, True, False],
229 fill_value=999999)
230 >>> b
231 array([2, 3, 4])
232 >>> np.concatenate([a, b])
233 masked_array(data=[0, 1, 2, 2, 3, 4],
234 mask=False,
235 fill_value=999999)
236 >>> np.ma.concatenate([a, b])
237 masked_array(data=[0, --, 2, 2, 3, 4],
238 mask=[False, True, False, False, False, False],
239 fill_value=999999)
241 """
242 if out is not None: 242 ↛ 244line 242 didn't jump to line 244, because the condition on line 242 was never true
243 # optimize for the typical case where only arrays is provided
244 arrays = list(arrays)
245 arrays.append(out)
246 return arrays
249@array_function_from_c_func_and_dispatcher(_multiarray_umath.inner)
250def inner(a, b):
251 """
252 inner(a, b, /)
254 Inner product of two arrays.
256 Ordinary inner product of vectors for 1-D arrays (without complex
257 conjugation), in higher dimensions a sum product over the last axes.
259 Parameters
260 ----------
261 a, b : array_like
262 If `a` and `b` are nonscalar, their last dimensions must match.
264 Returns
265 -------
266 out : ndarray
267 If `a` and `b` are both
268 scalars or both 1-D arrays then a scalar is returned; otherwise
269 an array is returned.
270 ``out.shape = (*a.shape[:-1], *b.shape[:-1])``
272 Raises
273 ------
274 ValueError
275 If both `a` and `b` are nonscalar and their last dimensions have
276 different sizes.
278 See Also
279 --------
280 tensordot : Sum products over arbitrary axes.
281 dot : Generalised matrix product, using second last dimension of `b`.
282 einsum : Einstein summation convention.
284 Notes
285 -----
286 For vectors (1-D arrays) it computes the ordinary inner-product::
288 np.inner(a, b) = sum(a[:]*b[:])
290 More generally, if `ndim(a) = r > 0` and `ndim(b) = s > 0`::
292 np.inner(a, b) = np.tensordot(a, b, axes=(-1,-1))
294 or explicitly::
296 np.inner(a, b)[i0,...,ir-2,j0,...,js-2]
297 = sum(a[i0,...,ir-2,:]*b[j0,...,js-2,:])
299 In addition `a` or `b` may be scalars, in which case::
301 np.inner(a,b) = a*b
303 Examples
304 --------
305 Ordinary inner product for vectors:
307 >>> a = np.array([1,2,3])
308 >>> b = np.array([0,1,0])
309 >>> np.inner(a, b)
310 2
312 Some multidimensional examples:
314 >>> a = np.arange(24).reshape((2,3,4))
315 >>> b = np.arange(4)
316 >>> c = np.inner(a, b)
317 >>> c.shape
318 (2, 3)
319 >>> c
320 array([[ 14, 38, 62],
321 [ 86, 110, 134]])
323 >>> a = np.arange(2).reshape((1,1,2))
324 >>> b = np.arange(6).reshape((3,2))
325 >>> c = np.inner(a, b)
326 >>> c.shape
327 (1, 1, 3)
328 >>> c
329 array([[[1, 3, 5]]])
331 An example where `b` is a scalar:
333 >>> np.inner(np.eye(2), 7)
334 array([[7., 0.],
335 [0., 7.]])
337 """
338 return (a, b)
341@array_function_from_c_func_and_dispatcher(_multiarray_umath.where)
342def where(condition, x=None, y=None):
343 """
344 where(condition, [x, y], /)
346 Return elements chosen from `x` or `y` depending on `condition`.
348 .. note::
349 When only `condition` is provided, this function is a shorthand for
350 ``np.asarray(condition).nonzero()``. Using `nonzero` directly should be
351 preferred, as it behaves correctly for subclasses. The rest of this
352 documentation covers only the case where all three arguments are
353 provided.
355 Parameters
356 ----------
357 condition : array_like, bool
358 Where True, yield `x`, otherwise yield `y`.
359 x, y : array_like
360 Values from which to choose. `x`, `y` and `condition` need to be
361 broadcastable to some shape.
363 Returns
364 -------
365 out : ndarray
366 An array with elements from `x` where `condition` is True, and elements
367 from `y` elsewhere.
369 See Also
370 --------
371 choose
372 nonzero : The function that is called when x and y are omitted
374 Notes
375 -----
376 If all the arrays are 1-D, `where` is equivalent to::
378 [xv if c else yv
379 for c, xv, yv in zip(condition, x, y)]
381 Examples
382 --------
383 >>> a = np.arange(10)
384 >>> a
385 array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
386 >>> np.where(a < 5, a, 10*a)
387 array([ 0, 1, 2, 3, 4, 50, 60, 70, 80, 90])
389 This can be used on multidimensional arrays too:
391 >>> np.where([[True, False], [True, True]],
392 ... [[1, 2], [3, 4]],
393 ... [[9, 8], [7, 6]])
394 array([[1, 8],
395 [3, 4]])
397 The shapes of x, y, and the condition are broadcast together:
399 >>> x, y = np.ogrid[:3, :4]
400 >>> np.where(x < y, x, 10 + y) # both x and 10+y are broadcast
401 array([[10, 0, 0, 0],
402 [10, 11, 1, 1],
403 [10, 11, 12, 2]])
405 >>> a = np.array([[0, 1, 2],
406 ... [0, 2, 4],
407 ... [0, 3, 6]])
408 >>> np.where(a < 4, a, -1) # -1 is broadcast
409 array([[ 0, 1, 2],
410 [ 0, 2, -1],
411 [ 0, 3, -1]])
412 """
413 return (condition, x, y)
416@array_function_from_c_func_and_dispatcher(_multiarray_umath.lexsort)
417def lexsort(keys, axis=None):
418 """
419 lexsort(keys, axis=-1)
421 Perform an indirect stable sort using a sequence of keys.
423 Given multiple sorting keys, which can be interpreted as columns in a
424 spreadsheet, lexsort returns an array of integer indices that describes
425 the sort order by multiple columns. The last key in the sequence is used
426 for the primary sort order, the second-to-last key for the secondary sort
427 order, and so on. The keys argument must be a sequence of objects that
428 can be converted to arrays of the same shape. If a 2D array is provided
429 for the keys argument, its rows are interpreted as the sorting keys and
430 sorting is according to the last row, second last row etc.
432 Parameters
433 ----------
434 keys : (k, N) array or tuple containing k (N,)-shaped sequences
435 The `k` different "columns" to be sorted. The last column (or row if
436 `keys` is a 2D array) is the primary sort key.
437 axis : int, optional
438 Axis to be indirectly sorted. By default, sort over the last axis.
440 Returns
441 -------
442 indices : (N,) ndarray of ints
443 Array of indices that sort the keys along the specified axis.
445 See Also
446 --------
447 argsort : Indirect sort.
448 ndarray.sort : In-place sort.
449 sort : Return a sorted copy of an array.
451 Examples
452 --------
453 Sort names: first by surname, then by name.
455 >>> surnames = ('Hertz', 'Galilei', 'Hertz')
456 >>> first_names = ('Heinrich', 'Galileo', 'Gustav')
457 >>> ind = np.lexsort((first_names, surnames))
458 >>> ind
459 array([1, 2, 0])
461 >>> [surnames[i] + ", " + first_names[i] for i in ind]
462 ['Galilei, Galileo', 'Hertz, Gustav', 'Hertz, Heinrich']
464 Sort two columns of numbers:
466 >>> a = [1,5,1,4,3,4,4] # First column
467 >>> b = [9,4,0,4,0,2,1] # Second column
468 >>> ind = np.lexsort((b,a)) # Sort by a, then by b
469 >>> ind
470 array([2, 0, 4, 6, 5, 3, 1])
472 >>> [(a[i],b[i]) for i in ind]
473 [(1, 0), (1, 9), (3, 0), (4, 1), (4, 2), (4, 4), (5, 4)]
475 Note that sorting is first according to the elements of ``a``.
476 Secondary sorting is according to the elements of ``b``.
478 A normal ``argsort`` would have yielded:
480 >>> [(a[i],b[i]) for i in np.argsort(a)]
481 [(1, 9), (1, 0), (3, 0), (4, 4), (4, 2), (4, 1), (5, 4)]
483 Structured arrays are sorted lexically by ``argsort``:
485 >>> x = np.array([(1,9), (5,4), (1,0), (4,4), (3,0), (4,2), (4,1)],
486 ... dtype=np.dtype([('x', int), ('y', int)]))
488 >>> np.argsort(x) # or np.argsort(x, order=('x', 'y'))
489 array([2, 0, 4, 6, 5, 3, 1])
491 """
492 if isinstance(keys, tuple):
493 return keys
494 else:
495 return (keys,)
498@array_function_from_c_func_and_dispatcher(_multiarray_umath.can_cast)
499def can_cast(from_, to, casting=None):
500 """
501 can_cast(from_, to, casting='safe')
503 Returns True if cast between data types can occur according to the
504 casting rule. If from is a scalar or array scalar, also returns
505 True if the scalar value can be cast without overflow or truncation
506 to an integer.
508 Parameters
509 ----------
510 from_ : dtype, dtype specifier, scalar, or array
511 Data type, scalar, or array to cast from.
512 to : dtype or dtype specifier
513 Data type to cast to.
514 casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional
515 Controls what kind of data casting may occur.
517 * 'no' means the data types should not be cast at all.
518 * 'equiv' means only byte-order changes are allowed.
519 * 'safe' means only casts which can preserve values are allowed.
520 * 'same_kind' means only safe casts or casts within a kind,
521 like float64 to float32, are allowed.
522 * 'unsafe' means any data conversions may be done.
524 Returns
525 -------
526 out : bool
527 True if cast can occur according to the casting rule.
529 Notes
530 -----
531 .. versionchanged:: 1.17.0
532 Casting between a simple data type and a structured one is possible only
533 for "unsafe" casting. Casting to multiple fields is allowed, but
534 casting from multiple fields is not.
536 .. versionchanged:: 1.9.0
537 Casting from numeric to string types in 'safe' casting mode requires
538 that the string dtype length is long enough to store the maximum
539 integer/float value converted.
541 See also
542 --------
543 dtype, result_type
545 Examples
546 --------
547 Basic examples
549 >>> np.can_cast(np.int32, np.int64)
550 True
551 >>> np.can_cast(np.float64, complex)
552 True
553 >>> np.can_cast(complex, float)
554 False
556 >>> np.can_cast('i8', 'f8')
557 True
558 >>> np.can_cast('i8', 'f4')
559 False
560 >>> np.can_cast('i4', 'S4')
561 False
563 Casting scalars
565 >>> np.can_cast(100, 'i1')
566 True
567 >>> np.can_cast(150, 'i1')
568 False
569 >>> np.can_cast(150, 'u1')
570 True
572 >>> np.can_cast(3.5e100, np.float32)
573 False
574 >>> np.can_cast(1000.0, np.float32)
575 True
577 Array scalar checks the value, array does not
579 >>> np.can_cast(np.array(1000.0), np.float32)
580 True
581 >>> np.can_cast(np.array([1000.0]), np.float32)
582 False
584 Using the casting rules
586 >>> np.can_cast('i8', 'i8', 'no')
587 True
588 >>> np.can_cast('<i8', '>i8', 'no')
589 False
591 >>> np.can_cast('<i8', '>i8', 'equiv')
592 True
593 >>> np.can_cast('<i4', '>i8', 'equiv')
594 False
596 >>> np.can_cast('<i4', '>i8', 'safe')
597 True
598 >>> np.can_cast('<i8', '>i4', 'safe')
599 False
601 >>> np.can_cast('<i8', '>i4', 'same_kind')
602 True
603 >>> np.can_cast('<i8', '>u4', 'same_kind')
604 False
606 >>> np.can_cast('<i8', '>u4', 'unsafe')
607 True
609 """
610 return (from_,)
613@array_function_from_c_func_and_dispatcher(_multiarray_umath.min_scalar_type)
614def min_scalar_type(a):
615 """
616 min_scalar_type(a, /)
618 For scalar ``a``, returns the data type with the smallest size
619 and smallest scalar kind which can hold its value. For non-scalar
620 array ``a``, returns the vector's dtype unmodified.
622 Floating point values are not demoted to integers,
623 and complex values are not demoted to floats.
625 Parameters
626 ----------
627 a : scalar or array_like
628 The value whose minimal data type is to be found.
630 Returns
631 -------
632 out : dtype
633 The minimal data type.
635 Notes
636 -----
637 .. versionadded:: 1.6.0
639 See Also
640 --------
641 result_type, promote_types, dtype, can_cast
643 Examples
644 --------
645 >>> np.min_scalar_type(10)
646 dtype('uint8')
648 >>> np.min_scalar_type(-260)
649 dtype('int16')
651 >>> np.min_scalar_type(3.1)
652 dtype('float16')
654 >>> np.min_scalar_type(1e50)
655 dtype('float64')
657 >>> np.min_scalar_type(np.arange(4,dtype='f8'))
658 dtype('float64')
660 """
661 return (a,)
664@array_function_from_c_func_and_dispatcher(_multiarray_umath.result_type)
665def result_type(*arrays_and_dtypes):
666 """
667 result_type(*arrays_and_dtypes)
669 Returns the type that results from applying the NumPy
670 type promotion rules to the arguments.
672 Type promotion in NumPy works similarly to the rules in languages
673 like C++, with some slight differences. When both scalars and
674 arrays are used, the array's type takes precedence and the actual value
675 of the scalar is taken into account.
677 For example, calculating 3*a, where a is an array of 32-bit floats,
678 intuitively should result in a 32-bit float output. If the 3 is a
679 32-bit integer, the NumPy rules indicate it can't convert losslessly
680 into a 32-bit float, so a 64-bit float should be the result type.
681 By examining the value of the constant, '3', we see that it fits in
682 an 8-bit integer, which can be cast losslessly into the 32-bit float.
684 Parameters
685 ----------
686 arrays_and_dtypes : list of arrays and dtypes
687 The operands of some operation whose result type is needed.
689 Returns
690 -------
691 out : dtype
692 The result type.
694 See also
695 --------
696 dtype, promote_types, min_scalar_type, can_cast
698 Notes
699 -----
700 .. versionadded:: 1.6.0
702 The specific algorithm used is as follows.
704 Categories are determined by first checking which of boolean,
705 integer (int/uint), or floating point (float/complex) the maximum
706 kind of all the arrays and the scalars are.
708 If there are only scalars or the maximum category of the scalars
709 is higher than the maximum category of the arrays,
710 the data types are combined with :func:`promote_types`
711 to produce the return value.
713 Otherwise, `min_scalar_type` is called on each array, and
714 the resulting data types are all combined with :func:`promote_types`
715 to produce the return value.
717 The set of int values is not a subset of the uint values for types
718 with the same number of bits, something not reflected in
719 :func:`min_scalar_type`, but handled as a special case in `result_type`.
721 Examples
722 --------
723 >>> np.result_type(3, np.arange(7, dtype='i1'))
724 dtype('int8')
726 >>> np.result_type('i4', 'c8')
727 dtype('complex128')
729 >>> np.result_type(3.0, -2)
730 dtype('float64')
732 """
733 return arrays_and_dtypes
736@array_function_from_c_func_and_dispatcher(_multiarray_umath.dot)
737def dot(a, b, out=None):
738 """
739 dot(a, b, out=None)
741 Dot product of two arrays. Specifically,
743 - If both `a` and `b` are 1-D arrays, it is inner product of vectors
744 (without complex conjugation).
746 - If both `a` and `b` are 2-D arrays, it is matrix multiplication,
747 but using :func:`matmul` or ``a @ b`` is preferred.
749 - If either `a` or `b` is 0-D (scalar), it is equivalent to :func:`multiply`
750 and using ``numpy.multiply(a, b)`` or ``a * b`` is preferred.
752 - If `a` is an N-D array and `b` is a 1-D array, it is a sum product over
753 the last axis of `a` and `b`.
755 - If `a` is an N-D array and `b` is an M-D array (where ``M>=2``), it is a
756 sum product over the last axis of `a` and the second-to-last axis of `b`::
758 dot(a, b)[i,j,k,m] = sum(a[i,j,:] * b[k,:,m])
760 Parameters
761 ----------
762 a : array_like
763 First argument.
764 b : array_like
765 Second argument.
766 out : ndarray, optional
767 Output argument. This must have the exact kind that would be returned
768 if it was not used. In particular, it must have the right type, must be
769 C-contiguous, and its dtype must be the dtype that would be returned
770 for `dot(a,b)`. This is a performance feature. Therefore, if these
771 conditions are not met, an exception is raised, instead of attempting
772 to be flexible.
774 Returns
775 -------
776 output : ndarray
777 Returns the dot product of `a` and `b`. If `a` and `b` are both
778 scalars or both 1-D arrays then a scalar is returned; otherwise
779 an array is returned.
780 If `out` is given, then it is returned.
782 Raises
783 ------
784 ValueError
785 If the last dimension of `a` is not the same size as
786 the second-to-last dimension of `b`.
788 See Also
789 --------
790 vdot : Complex-conjugating dot product.
791 tensordot : Sum products over arbitrary axes.
792 einsum : Einstein summation convention.
793 matmul : '@' operator as method with out parameter.
794 linalg.multi_dot : Chained dot product.
796 Examples
797 --------
798 >>> np.dot(3, 4)
799 12
801 Neither argument is complex-conjugated:
803 >>> np.dot([2j, 3j], [2j, 3j])
804 (-13+0j)
806 For 2-D arrays it is the matrix product:
808 >>> a = [[1, 0], [0, 1]]
809 >>> b = [[4, 1], [2, 2]]
810 >>> np.dot(a, b)
811 array([[4, 1],
812 [2, 2]])
814 >>> a = np.arange(3*4*5*6).reshape((3,4,5,6))
815 >>> b = np.arange(3*4*5*6)[::-1].reshape((5,4,6,3))
816 >>> np.dot(a, b)[2,3,2,1,2,2]
817 499128
818 >>> sum(a[2,3,2,:] * b[1,2,:,2])
819 499128
821 """
822 return (a, b, out)
825@array_function_from_c_func_and_dispatcher(_multiarray_umath.vdot)
826def vdot(a, b):
827 """
828 vdot(a, b, /)
830 Return the dot product of two vectors.
832 The vdot(`a`, `b`) function handles complex numbers differently than
833 dot(`a`, `b`). If the first argument is complex the complex conjugate
834 of the first argument is used for the calculation of the dot product.
836 Note that `vdot` handles multidimensional arrays differently than `dot`:
837 it does *not* perform a matrix product, but flattens input arguments
838 to 1-D vectors first. Consequently, it should only be used for vectors.
840 Parameters
841 ----------
842 a : array_like
843 If `a` is complex the complex conjugate is taken before calculation
844 of the dot product.
845 b : array_like
846 Second argument to the dot product.
848 Returns
849 -------
850 output : ndarray
851 Dot product of `a` and `b`. Can be an int, float, or
852 complex depending on the types of `a` and `b`.
854 See Also
855 --------
856 dot : Return the dot product without using the complex conjugate of the
857 first argument.
859 Examples
860 --------
861 >>> a = np.array([1+2j,3+4j])
862 >>> b = np.array([5+6j,7+8j])
863 >>> np.vdot(a, b)
864 (70-8j)
865 >>> np.vdot(b, a)
866 (70+8j)
868 Note that higher-dimensional arrays are flattened!
870 >>> a = np.array([[1, 4], [5, 6]])
871 >>> b = np.array([[4, 1], [2, 2]])
872 >>> np.vdot(a, b)
873 30
874 >>> np.vdot(b, a)
875 30
876 >>> 1*4 + 4*1 + 5*2 + 6*2
877 30
879 """
880 return (a, b)
883@array_function_from_c_func_and_dispatcher(_multiarray_umath.bincount)
884def bincount(x, weights=None, minlength=None):
885 """
886 bincount(x, /, weights=None, minlength=0)
888 Count number of occurrences of each value in array of non-negative ints.
890 The number of bins (of size 1) is one larger than the largest value in
891 `x`. If `minlength` is specified, there will be at least this number
892 of bins in the output array (though it will be longer if necessary,
893 depending on the contents of `x`).
894 Each bin gives the number of occurrences of its index value in `x`.
895 If `weights` is specified the input array is weighted by it, i.e. if a
896 value ``n`` is found at position ``i``, ``out[n] += weight[i]`` instead
897 of ``out[n] += 1``.
899 Parameters
900 ----------
901 x : array_like, 1 dimension, nonnegative ints
902 Input array.
903 weights : array_like, optional
904 Weights, array of the same shape as `x`.
905 minlength : int, optional
906 A minimum number of bins for the output array.
908 .. versionadded:: 1.6.0
910 Returns
911 -------
912 out : ndarray of ints
913 The result of binning the input array.
914 The length of `out` is equal to ``np.amax(x)+1``.
916 Raises
917 ------
918 ValueError
919 If the input is not 1-dimensional, or contains elements with negative
920 values, or if `minlength` is negative.
921 TypeError
922 If the type of the input is float or complex.
924 See Also
925 --------
926 histogram, digitize, unique
928 Examples
929 --------
930 >>> np.bincount(np.arange(5))
931 array([1, 1, 1, 1, 1])
932 >>> np.bincount(np.array([0, 1, 1, 3, 2, 1, 7]))
933 array([1, 3, 1, 1, 0, 0, 0, 1])
935 >>> x = np.array([0, 1, 1, 3, 2, 1, 7, 23])
936 >>> np.bincount(x).size == np.amax(x)+1
937 True
939 The input array needs to be of integer dtype, otherwise a
940 TypeError is raised:
942 >>> np.bincount(np.arange(5, dtype=float))
943 Traceback (most recent call last):
944 ...
945 TypeError: Cannot cast array data from dtype('float64') to dtype('int64')
946 according to the rule 'safe'
948 A possible use of ``bincount`` is to perform sums over
949 variable-size chunks of an array, using the ``weights`` keyword.
951 >>> w = np.array([0.3, 0.5, 0.2, 0.7, 1., -0.6]) # weights
952 >>> x = np.array([0, 1, 1, 2, 2, 2])
953 >>> np.bincount(x, weights=w)
954 array([ 0.3, 0.7, 1.1])
956 """
957 return (x, weights)
960@array_function_from_c_func_and_dispatcher(_multiarray_umath.ravel_multi_index)
961def ravel_multi_index(multi_index, dims, mode=None, order=None):
962 """
963 ravel_multi_index(multi_index, dims, mode='raise', order='C')
965 Converts a tuple of index arrays into an array of flat
966 indices, applying boundary modes to the multi-index.
968 Parameters
969 ----------
970 multi_index : tuple of array_like
971 A tuple of integer arrays, one array for each dimension.
972 dims : tuple of ints
973 The shape of array into which the indices from ``multi_index`` apply.
974 mode : {'raise', 'wrap', 'clip'}, optional
975 Specifies how out-of-bounds indices are handled. Can specify
976 either one mode or a tuple of modes, one mode per index.
978 * 'raise' -- raise an error (default)
979 * 'wrap' -- wrap around
980 * 'clip' -- clip to the range
982 In 'clip' mode, a negative index which would normally
983 wrap will clip to 0 instead.
984 order : {'C', 'F'}, optional
985 Determines whether the multi-index should be viewed as
986 indexing in row-major (C-style) or column-major
987 (Fortran-style) order.
989 Returns
990 -------
991 raveled_indices : ndarray
992 An array of indices into the flattened version of an array
993 of dimensions ``dims``.
995 See Also
996 --------
997 unravel_index
999 Notes
1000 -----
1001 .. versionadded:: 1.6.0
1003 Examples
1004 --------
1005 >>> arr = np.array([[3,6,6],[4,5,1]])
1006 >>> np.ravel_multi_index(arr, (7,6))
1007 array([22, 41, 37])
1008 >>> np.ravel_multi_index(arr, (7,6), order='F')
1009 array([31, 41, 13])
1010 >>> np.ravel_multi_index(arr, (4,6), mode='clip')
1011 array([22, 23, 19])
1012 >>> np.ravel_multi_index(arr, (4,4), mode=('clip','wrap'))
1013 array([12, 13, 13])
1015 >>> np.ravel_multi_index((3,1,4,1), (6,7,8,9))
1016 1621
1017 """
1018 return multi_index
1021@array_function_from_c_func_and_dispatcher(_multiarray_umath.unravel_index)
1022def unravel_index(indices, shape=None, order=None):
1023 """
1024 unravel_index(indices, shape, order='C')
1026 Converts a flat index or array of flat indices into a tuple
1027 of coordinate arrays.
1029 Parameters
1030 ----------
1031 indices : array_like
1032 An integer array whose elements are indices into the flattened
1033 version of an array of dimensions ``shape``. Before version 1.6.0,
1034 this function accepted just one index value.
1035 shape : tuple of ints
1036 The shape of the array to use for unraveling ``indices``.
1038 .. versionchanged:: 1.16.0
1039 Renamed from ``dims`` to ``shape``.
1041 order : {'C', 'F'}, optional
1042 Determines whether the indices should be viewed as indexing in
1043 row-major (C-style) or column-major (Fortran-style) order.
1045 .. versionadded:: 1.6.0
1047 Returns
1048 -------
1049 unraveled_coords : tuple of ndarray
1050 Each array in the tuple has the same shape as the ``indices``
1051 array.
1053 See Also
1054 --------
1055 ravel_multi_index
1057 Examples
1058 --------
1059 >>> np.unravel_index([22, 41, 37], (7,6))
1060 (array([3, 6, 6]), array([4, 5, 1]))
1061 >>> np.unravel_index([31, 41, 13], (7,6), order='F')
1062 (array([3, 6, 6]), array([4, 5, 1]))
1064 >>> np.unravel_index(1621, (6,7,8,9))
1065 (3, 1, 4, 1)
1067 """
1068 return (indices,)
1071@array_function_from_c_func_and_dispatcher(_multiarray_umath.copyto)
1072def copyto(dst, src, casting=None, where=None):
1073 """
1074 copyto(dst, src, casting='same_kind', where=True)
1076 Copies values from one array to another, broadcasting as necessary.
1078 Raises a TypeError if the `casting` rule is violated, and if
1079 `where` is provided, it selects which elements to copy.
1081 .. versionadded:: 1.7.0
1083 Parameters
1084 ----------
1085 dst : ndarray
1086 The array into which values are copied.
1087 src : array_like
1088 The array from which values are copied.
1089 casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional
1090 Controls what kind of data casting may occur when copying.
1092 * 'no' means the data types should not be cast at all.
1093 * 'equiv' means only byte-order changes are allowed.
1094 * 'safe' means only casts which can preserve values are allowed.
1095 * 'same_kind' means only safe casts or casts within a kind,
1096 like float64 to float32, are allowed.
1097 * 'unsafe' means any data conversions may be done.
1098 where : array_like of bool, optional
1099 A boolean array which is broadcasted to match the dimensions
1100 of `dst`, and selects elements to copy from `src` to `dst`
1101 wherever it contains the value True.
1102 """
1103 return (dst, src, where)
1106@array_function_from_c_func_and_dispatcher(_multiarray_umath.putmask)
1107def putmask(a, mask, values):
1108 """
1109 putmask(a, mask, values)
1111 Changes elements of an array based on conditional and input values.
1113 Sets ``a.flat[n] = values[n]`` for each n where ``mask.flat[n]==True``.
1115 If `values` is not the same size as `a` and `mask` then it will repeat.
1116 This gives behavior different from ``a[mask] = values``.
1118 Parameters
1119 ----------
1120 a : ndarray
1121 Target array.
1122 mask : array_like
1123 Boolean mask array. It has to be the same shape as `a`.
1124 values : array_like
1125 Values to put into `a` where `mask` is True. If `values` is smaller
1126 than `a` it will be repeated.
1128 See Also
1129 --------
1130 place, put, take, copyto
1132 Examples
1133 --------
1134 >>> x = np.arange(6).reshape(2, 3)
1135 >>> np.putmask(x, x>2, x**2)
1136 >>> x
1137 array([[ 0, 1, 2],
1138 [ 9, 16, 25]])
1140 If `values` is smaller than `a` it is repeated:
1142 >>> x = np.arange(5)
1143 >>> np.putmask(x, x>1, [-33, -44])
1144 >>> x
1145 array([ 0, 1, -33, -44, -33])
1147 """
1148 return (a, mask, values)
1151@array_function_from_c_func_and_dispatcher(_multiarray_umath.packbits)
1152def packbits(a, axis=None, bitorder='big'):
1153 """
1154 packbits(a, /, axis=None, bitorder='big')
1156 Packs the elements of a binary-valued array into bits in a uint8 array.
1158 The result is padded to full bytes by inserting zero bits at the end.
1160 Parameters
1161 ----------
1162 a : array_like
1163 An array of integers or booleans whose elements should be packed to
1164 bits.
1165 axis : int, optional
1166 The dimension over which bit-packing is done.
1167 ``None`` implies packing the flattened array.
1168 bitorder : {'big', 'little'}, optional
1169 The order of the input bits. 'big' will mimic bin(val),
1170 ``[0, 0, 0, 0, 0, 0, 1, 1] => 3 = 0b00000011``, 'little' will
1171 reverse the order so ``[1, 1, 0, 0, 0, 0, 0, 0] => 3``.
1172 Defaults to 'big'.
1174 .. versionadded:: 1.17.0
1176 Returns
1177 -------
1178 packed : ndarray
1179 Array of type uint8 whose elements represent bits corresponding to the
1180 logical (0 or nonzero) value of the input elements. The shape of
1181 `packed` has the same number of dimensions as the input (unless `axis`
1182 is None, in which case the output is 1-D).
1184 See Also
1185 --------
1186 unpackbits: Unpacks elements of a uint8 array into a binary-valued output
1187 array.
1189 Examples
1190 --------
1191 >>> a = np.array([[[1,0,1],
1192 ... [0,1,0]],
1193 ... [[1,1,0],
1194 ... [0,0,1]]])
1195 >>> b = np.packbits(a, axis=-1)
1196 >>> b
1197 array([[[160],
1198 [ 64]],
1199 [[192],
1200 [ 32]]], dtype=uint8)
1202 Note that in binary 160 = 1010 0000, 64 = 0100 0000, 192 = 1100 0000,
1203 and 32 = 0010 0000.
1205 """
1206 return (a,)
1209@array_function_from_c_func_and_dispatcher(_multiarray_umath.unpackbits)
1210def unpackbits(a, axis=None, count=None, bitorder='big'):
1211 """
1212 unpackbits(a, /, axis=None, count=None, bitorder='big')
1214 Unpacks elements of a uint8 array into a binary-valued output array.
1216 Each element of `a` represents a bit-field that should be unpacked
1217 into a binary-valued output array. The shape of the output array is
1218 either 1-D (if `axis` is ``None``) or the same shape as the input
1219 array with unpacking done along the axis specified.
1221 Parameters
1222 ----------
1223 a : ndarray, uint8 type
1224 Input array.
1225 axis : int, optional
1226 The dimension over which bit-unpacking is done.
1227 ``None`` implies unpacking the flattened array.
1228 count : int or None, optional
1229 The number of elements to unpack along `axis`, provided as a way
1230 of undoing the effect of packing a size that is not a multiple
1231 of eight. A non-negative number means to only unpack `count`
1232 bits. A negative number means to trim off that many bits from
1233 the end. ``None`` means to unpack the entire array (the
1234 default). Counts larger than the available number of bits will
1235 add zero padding to the output. Negative counts must not
1236 exceed the available number of bits.
1238 .. versionadded:: 1.17.0
1240 bitorder : {'big', 'little'}, optional
1241 The order of the returned bits. 'big' will mimic bin(val),
1242 ``3 = 0b00000011 => [0, 0, 0, 0, 0, 0, 1, 1]``, 'little' will reverse
1243 the order to ``[1, 1, 0, 0, 0, 0, 0, 0]``.
1244 Defaults to 'big'.
1246 .. versionadded:: 1.17.0
1248 Returns
1249 -------
1250 unpacked : ndarray, uint8 type
1251 The elements are binary-valued (0 or 1).
1253 See Also
1254 --------
1255 packbits : Packs the elements of a binary-valued array into bits in
1256 a uint8 array.
1258 Examples
1259 --------
1260 >>> a = np.array([[2], [7], [23]], dtype=np.uint8)
1261 >>> a
1262 array([[ 2],
1263 [ 7],
1264 [23]], dtype=uint8)
1265 >>> b = np.unpackbits(a, axis=1)
1266 >>> b
1267 array([[0, 0, 0, 0, 0, 0, 1, 0],
1268 [0, 0, 0, 0, 0, 1, 1, 1],
1269 [0, 0, 0, 1, 0, 1, 1, 1]], dtype=uint8)
1270 >>> c = np.unpackbits(a, axis=1, count=-3)
1271 >>> c
1272 array([[0, 0, 0, 0, 0],
1273 [0, 0, 0, 0, 0],
1274 [0, 0, 0, 1, 0]], dtype=uint8)
1276 >>> p = np.packbits(b, axis=0)
1277 >>> np.unpackbits(p, axis=0)
1278 array([[0, 0, 0, 0, 0, 0, 1, 0],
1279 [0, 0, 0, 0, 0, 1, 1, 1],
1280 [0, 0, 0, 1, 0, 1, 1, 1],
1281 [0, 0, 0, 0, 0, 0, 0, 0],
1282 [0, 0, 0, 0, 0, 0, 0, 0],
1283 [0, 0, 0, 0, 0, 0, 0, 0],
1284 [0, 0, 0, 0, 0, 0, 0, 0],
1285 [0, 0, 0, 0, 0, 0, 0, 0]], dtype=uint8)
1286 >>> np.array_equal(b, np.unpackbits(p, axis=0, count=b.shape[0]))
1287 True
1289 """
1290 return (a,)
1293@array_function_from_c_func_and_dispatcher(_multiarray_umath.shares_memory)
1294def shares_memory(a, b, max_work=None):
1295 """
1296 shares_memory(a, b, /, max_work=None)
1298 Determine if two arrays share memory.
1300 .. warning::
1302 This function can be exponentially slow for some inputs, unless
1303 `max_work` is set to a finite number or ``MAY_SHARE_BOUNDS``.
1304 If in doubt, use `numpy.may_share_memory` instead.
1306 Parameters
1307 ----------
1308 a, b : ndarray
1309 Input arrays
1310 max_work : int, optional
1311 Effort to spend on solving the overlap problem (maximum number
1312 of candidate solutions to consider). The following special
1313 values are recognized:
1315 max_work=MAY_SHARE_EXACT (default)
1316 The problem is solved exactly. In this case, the function returns
1317 True only if there is an element shared between the arrays. Finding
1318 the exact solution may take extremely long in some cases.
1319 max_work=MAY_SHARE_BOUNDS
1320 Only the memory bounds of a and b are checked.
1322 Raises
1323 ------
1324 numpy.TooHardError
1325 Exceeded max_work.
1327 Returns
1328 -------
1329 out : bool
1331 See Also
1332 --------
1333 may_share_memory
1335 Examples
1336 --------
1337 >>> x = np.array([1, 2, 3, 4])
1338 >>> np.shares_memory(x, np.array([5, 6, 7]))
1339 False
1340 >>> np.shares_memory(x[::2], x)
1341 True
1342 >>> np.shares_memory(x[::2], x[1::2])
1343 False
1345 Checking whether two arrays share memory is NP-complete, and
1346 runtime may increase exponentially in the number of
1347 dimensions. Hence, `max_work` should generally be set to a finite
1348 number, as it is possible to construct examples that take
1349 extremely long to run:
1351 >>> from numpy.lib.stride_tricks import as_strided
1352 >>> x = np.zeros([192163377], dtype=np.int8)
1353 >>> x1 = as_strided(x, strides=(36674, 61119, 85569), shape=(1049, 1049, 1049))
1354 >>> x2 = as_strided(x[64023025:], strides=(12223, 12224, 1), shape=(1049, 1049, 1))
1355 >>> np.shares_memory(x1, x2, max_work=1000)
1356 Traceback (most recent call last):
1357 ...
1358 numpy.TooHardError: Exceeded max_work
1360 Running ``np.shares_memory(x1, x2)`` without `max_work` set takes
1361 around 1 minute for this case. It is possible to find problems
1362 that take still significantly longer.
1364 """
1365 return (a, b)
1368@array_function_from_c_func_and_dispatcher(_multiarray_umath.may_share_memory)
1369def may_share_memory(a, b, max_work=None):
1370 """
1371 may_share_memory(a, b, /, max_work=None)
1373 Determine if two arrays might share memory
1375 A return of True does not necessarily mean that the two arrays
1376 share any element. It just means that they *might*.
1378 Only the memory bounds of a and b are checked by default.
1380 Parameters
1381 ----------
1382 a, b : ndarray
1383 Input arrays
1384 max_work : int, optional
1385 Effort to spend on solving the overlap problem. See
1386 `shares_memory` for details. Default for ``may_share_memory``
1387 is to do a bounds check.
1389 Returns
1390 -------
1391 out : bool
1393 See Also
1394 --------
1395 shares_memory
1397 Examples
1398 --------
1399 >>> np.may_share_memory(np.array([1,2]), np.array([5,8,9]))
1400 False
1401 >>> x = np.zeros([3, 4])
1402 >>> np.may_share_memory(x[:,0], x[:,1])
1403 True
1405 """
1406 return (a, b)
1409@array_function_from_c_func_and_dispatcher(_multiarray_umath.is_busday)
1410def is_busday(dates, weekmask=None, holidays=None, busdaycal=None, out=None):
1411 """
1412 is_busday(dates, weekmask='1111100', holidays=None, busdaycal=None, out=None)
1414 Calculates which of the given dates are valid days, and which are not.
1416 .. versionadded:: 1.7.0
1418 Parameters
1419 ----------
1420 dates : array_like of datetime64[D]
1421 The array of dates to process.
1422 weekmask : str or array_like of bool, optional
1423 A seven-element array indicating which of Monday through Sunday are
1424 valid days. May be specified as a length-seven list or array, like
1425 [1,1,1,1,1,0,0]; a length-seven string, like '1111100'; or a string
1426 like "Mon Tue Wed Thu Fri", made up of 3-character abbreviations for
1427 weekdays, optionally separated by white space. Valid abbreviations
1428 are: Mon Tue Wed Thu Fri Sat Sun
1429 holidays : array_like of datetime64[D], optional
1430 An array of dates to consider as invalid dates. They may be
1431 specified in any order, and NaT (not-a-time) dates are ignored.
1432 This list is saved in a normalized form that is suited for
1433 fast calculations of valid days.
1434 busdaycal : busdaycalendar, optional
1435 A `busdaycalendar` object which specifies the valid days. If this
1436 parameter is provided, neither weekmask nor holidays may be
1437 provided.
1438 out : array of bool, optional
1439 If provided, this array is filled with the result.
1441 Returns
1442 -------
1443 out : array of bool
1444 An array with the same shape as ``dates``, containing True for
1445 each valid day, and False for each invalid day.
1447 See Also
1448 --------
1449 busdaycalendar : An object that specifies a custom set of valid days.
1450 busday_offset : Applies an offset counted in valid days.
1451 busday_count : Counts how many valid days are in a half-open date range.
1453 Examples
1454 --------
1455 >>> # The weekdays are Friday, Saturday, and Monday
1456 ... np.is_busday(['2011-07-01', '2011-07-02', '2011-07-18'],
1457 ... holidays=['2011-07-01', '2011-07-04', '2011-07-17'])
1458 array([False, False, True])
1459 """
1460 return (dates, weekmask, holidays, out)
1463@array_function_from_c_func_and_dispatcher(_multiarray_umath.busday_offset)
1464def busday_offset(dates, offsets, roll=None, weekmask=None, holidays=None,
1465 busdaycal=None, out=None):
1466 """
1467 busday_offset(dates, offsets, roll='raise', weekmask='1111100', holidays=None, busdaycal=None, out=None)
1469 First adjusts the date to fall on a valid day according to
1470 the ``roll`` rule, then applies offsets to the given dates
1471 counted in valid days.
1473 .. versionadded:: 1.7.0
1475 Parameters
1476 ----------
1477 dates : array_like of datetime64[D]
1478 The array of dates to process.
1479 offsets : array_like of int
1480 The array of offsets, which is broadcast with ``dates``.
1481 roll : {'raise', 'nat', 'forward', 'following', 'backward', 'preceding', 'modifiedfollowing', 'modifiedpreceding'}, optional
1482 How to treat dates that do not fall on a valid day. The default
1483 is 'raise'.
1485 * 'raise' means to raise an exception for an invalid day.
1486 * 'nat' means to return a NaT (not-a-time) for an invalid day.
1487 * 'forward' and 'following' mean to take the first valid day
1488 later in time.
1489 * 'backward' and 'preceding' mean to take the first valid day
1490 earlier in time.
1491 * 'modifiedfollowing' means to take the first valid day
1492 later in time unless it is across a Month boundary, in which
1493 case to take the first valid day earlier in time.
1494 * 'modifiedpreceding' means to take the first valid day
1495 earlier in time unless it is across a Month boundary, in which
1496 case to take the first valid day later in time.
1497 weekmask : str or array_like of bool, optional
1498 A seven-element array indicating which of Monday through Sunday are
1499 valid days. May be specified as a length-seven list or array, like
1500 [1,1,1,1,1,0,0]; a length-seven string, like '1111100'; or a string
1501 like "Mon Tue Wed Thu Fri", made up of 3-character abbreviations for
1502 weekdays, optionally separated by white space. Valid abbreviations
1503 are: Mon Tue Wed Thu Fri Sat Sun
1504 holidays : array_like of datetime64[D], optional
1505 An array of dates to consider as invalid dates. They may be
1506 specified in any order, and NaT (not-a-time) dates are ignored.
1507 This list is saved in a normalized form that is suited for
1508 fast calculations of valid days.
1509 busdaycal : busdaycalendar, optional
1510 A `busdaycalendar` object which specifies the valid days. If this
1511 parameter is provided, neither weekmask nor holidays may be
1512 provided.
1513 out : array of datetime64[D], optional
1514 If provided, this array is filled with the result.
1516 Returns
1517 -------
1518 out : array of datetime64[D]
1519 An array with a shape from broadcasting ``dates`` and ``offsets``
1520 together, containing the dates with offsets applied.
1522 See Also
1523 --------
1524 busdaycalendar : An object that specifies a custom set of valid days.
1525 is_busday : Returns a boolean array indicating valid days.
1526 busday_count : Counts how many valid days are in a half-open date range.
1528 Examples
1529 --------
1530 >>> # First business day in October 2011 (not accounting for holidays)
1531 ... np.busday_offset('2011-10', 0, roll='forward')
1532 numpy.datetime64('2011-10-03')
1533 >>> # Last business day in February 2012 (not accounting for holidays)
1534 ... np.busday_offset('2012-03', -1, roll='forward')
1535 numpy.datetime64('2012-02-29')
1536 >>> # Third Wednesday in January 2011
1537 ... np.busday_offset('2011-01', 2, roll='forward', weekmask='Wed')
1538 numpy.datetime64('2011-01-19')
1539 >>> # 2012 Mother's Day in Canada and the U.S.
1540 ... np.busday_offset('2012-05', 1, roll='forward', weekmask='Sun')
1541 numpy.datetime64('2012-05-13')
1543 >>> # First business day on or after a date
1544 ... np.busday_offset('2011-03-20', 0, roll='forward')
1545 numpy.datetime64('2011-03-21')
1546 >>> np.busday_offset('2011-03-22', 0, roll='forward')
1547 numpy.datetime64('2011-03-22')
1548 >>> # First business day after a date
1549 ... np.busday_offset('2011-03-20', 1, roll='backward')
1550 numpy.datetime64('2011-03-21')
1551 >>> np.busday_offset('2011-03-22', 1, roll='backward')
1552 numpy.datetime64('2011-03-23')
1553 """
1554 return (dates, offsets, weekmask, holidays, out)
1557@array_function_from_c_func_and_dispatcher(_multiarray_umath.busday_count)
1558def busday_count(begindates, enddates, weekmask=None, holidays=None,
1559 busdaycal=None, out=None):
1560 """
1561 busday_count(begindates, enddates, weekmask='1111100', holidays=[], busdaycal=None, out=None)
1563 Counts the number of valid days between `begindates` and
1564 `enddates`, not including the day of `enddates`.
1566 If ``enddates`` specifies a date value that is earlier than the
1567 corresponding ``begindates`` date value, the count will be negative.
1569 .. versionadded:: 1.7.0
1571 Parameters
1572 ----------
1573 begindates : array_like of datetime64[D]
1574 The array of the first dates for counting.
1575 enddates : array_like of datetime64[D]
1576 The array of the end dates for counting, which are excluded
1577 from the count themselves.
1578 weekmask : str or array_like of bool, optional
1579 A seven-element array indicating which of Monday through Sunday are
1580 valid days. May be specified as a length-seven list or array, like
1581 [1,1,1,1,1,0,0]; a length-seven string, like '1111100'; or a string
1582 like "Mon Tue Wed Thu Fri", made up of 3-character abbreviations for
1583 weekdays, optionally separated by white space. Valid abbreviations
1584 are: Mon Tue Wed Thu Fri Sat Sun
1585 holidays : array_like of datetime64[D], optional
1586 An array of dates to consider as invalid dates. They may be
1587 specified in any order, and NaT (not-a-time) dates are ignored.
1588 This list is saved in a normalized form that is suited for
1589 fast calculations of valid days.
1590 busdaycal : busdaycalendar, optional
1591 A `busdaycalendar` object which specifies the valid days. If this
1592 parameter is provided, neither weekmask nor holidays may be
1593 provided.
1594 out : array of int, optional
1595 If provided, this array is filled with the result.
1597 Returns
1598 -------
1599 out : array of int
1600 An array with a shape from broadcasting ``begindates`` and ``enddates``
1601 together, containing the number of valid days between
1602 the begin and end dates.
1604 See Also
1605 --------
1606 busdaycalendar : An object that specifies a custom set of valid days.
1607 is_busday : Returns a boolean array indicating valid days.
1608 busday_offset : Applies an offset counted in valid days.
1610 Examples
1611 --------
1612 >>> # Number of weekdays in January 2011
1613 ... np.busday_count('2011-01', '2011-02')
1614 21
1615 >>> # Number of weekdays in 2011
1616 >>> np.busday_count('2011', '2012')
1617 260
1618 >>> # Number of Saturdays in 2011
1619 ... np.busday_count('2011', '2012', weekmask='Sat')
1620 53
1621 """
1622 return (begindates, enddates, weekmask, holidays, out)
1625@array_function_from_c_func_and_dispatcher(
1626 _multiarray_umath.datetime_as_string)
1627def datetime_as_string(arr, unit=None, timezone=None, casting=None):
1628 """
1629 datetime_as_string(arr, unit=None, timezone='naive', casting='same_kind')
1631 Convert an array of datetimes into an array of strings.
1633 Parameters
1634 ----------
1635 arr : array_like of datetime64
1636 The array of UTC timestamps to format.
1637 unit : str
1638 One of None, 'auto', or a :ref:`datetime unit <arrays.dtypes.dateunits>`.
1639 timezone : {'naive', 'UTC', 'local'} or tzinfo
1640 Timezone information to use when displaying the datetime. If 'UTC', end
1641 with a Z to indicate UTC time. If 'local', convert to the local timezone
1642 first, and suffix with a +-#### timezone offset. If a tzinfo object,
1643 then do as with 'local', but use the specified timezone.
1644 casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}
1645 Casting to allow when changing between datetime units.
1647 Returns
1648 -------
1649 str_arr : ndarray
1650 An array of strings the same shape as `arr`.
1652 Examples
1653 --------
1654 >>> import pytz
1655 >>> d = np.arange('2002-10-27T04:30', 4*60, 60, dtype='M8[m]')
1656 >>> d
1657 array(['2002-10-27T04:30', '2002-10-27T05:30', '2002-10-27T06:30',
1658 '2002-10-27T07:30'], dtype='datetime64[m]')
1660 Setting the timezone to UTC shows the same information, but with a Z suffix
1662 >>> np.datetime_as_string(d, timezone='UTC')
1663 array(['2002-10-27T04:30Z', '2002-10-27T05:30Z', '2002-10-27T06:30Z',
1664 '2002-10-27T07:30Z'], dtype='<U35')
1666 Note that we picked datetimes that cross a DST boundary. Passing in a
1667 ``pytz`` timezone object will print the appropriate offset
1669 >>> np.datetime_as_string(d, timezone=pytz.timezone('US/Eastern'))
1670 array(['2002-10-27T00:30-0400', '2002-10-27T01:30-0400',
1671 '2002-10-27T01:30-0500', '2002-10-27T02:30-0500'], dtype='<U39')
1673 Passing in a unit will change the precision
1675 >>> np.datetime_as_string(d, unit='h')
1676 array(['2002-10-27T04', '2002-10-27T05', '2002-10-27T06', '2002-10-27T07'],
1677 dtype='<U32')
1678 >>> np.datetime_as_string(d, unit='s')
1679 array(['2002-10-27T04:30:00', '2002-10-27T05:30:00', '2002-10-27T06:30:00',
1680 '2002-10-27T07:30:00'], dtype='<U38')
1682 'casting' can be used to specify whether precision can be changed
1684 >>> np.datetime_as_string(d, unit='h', casting='safe')
1685 Traceback (most recent call last):
1686 ...
1687 TypeError: Cannot create a datetime string as units 'h' from a NumPy
1688 datetime with units 'm' according to the rule 'safe'
1689 """
1690 return (arr,)