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