1"""
2This is only meant to add docs to objects defined in C-extension modules.
3The purpose is to allow easier editing of the docstrings without
4requiring a re-compile.
5
6NOTE: Many of the methods of ndarray have corresponding functions.
7 If you update these docstrings, please keep also the ones in
8 _core/fromnumeric.py, matrixlib/defmatrix.py up-to-date.
9
10"""
11
12import textwrap
13
14from numpy._core.function_base import add_newdoc
15from numpy._core.overrides import get_array_function_like_doc # noqa: F401
16
17###############################################################################
18#
19# flatiter
20#
21# flatiter needs a toplevel description
22#
23###############################################################################
24
25add_newdoc('numpy._core', 'flatiter',
26 """
27 Flat iterator object to iterate over arrays.
28
29 A `flatiter` iterator is returned by ``x.flat`` for any array `x`.
30 It allows iterating over the array as if it were a 1-D array,
31 either in a for-loop or by calling its `next` method.
32
33 Iteration is done in row-major, C-style order (the last
34 index varying the fastest). The iterator can also be indexed using
35 basic slicing or advanced indexing.
36
37 See Also
38 --------
39 ndarray.flat : Return a flat iterator over an array.
40 ndarray.flatten : Returns a flattened copy of an array.
41
42 Notes
43 -----
44 A `flatiter` iterator can not be constructed directly from Python code
45 by calling the `flatiter` constructor.
46
47 Examples
48 --------
49 >>> import numpy as np
50 >>> x = np.arange(6).reshape(2, 3)
51 >>> fl = x.flat
52 >>> type(fl)
53 <class 'numpy.flatiter'>
54 >>> for item in fl:
55 ... print(item)
56 ...
57 0
58 1
59 2
60 3
61 4
62 5
63
64 >>> fl[2:4]
65 array([2, 3])
66
67 """)
68
69# flatiter attributes
70
71add_newdoc('numpy._core', 'flatiter', ('base',
72 """
73 A reference to the array that is iterated over.
74
75 Examples
76 --------
77 >>> import numpy as np
78 >>> x = np.arange(5)
79 >>> fl = x.flat
80 >>> fl.base is x
81 True
82
83 """))
84
85add_newdoc('numpy._core', 'flatiter', ('coords',
86 """
87 An N-dimensional tuple of current coordinates.
88
89 Examples
90 --------
91 >>> import numpy as np
92 >>> x = np.arange(6).reshape(2, 3)
93 >>> fl = x.flat
94 >>> fl.coords
95 (0, 0)
96 >>> next(fl)
97 0
98 >>> fl.coords
99 (0, 1)
100
101 """))
102
103add_newdoc('numpy._core', 'flatiter', ('index',
104 """
105 Current flat index into the array.
106
107 Examples
108 --------
109 >>> import numpy as np
110 >>> x = np.arange(6).reshape(2, 3)
111 >>> fl = x.flat
112 >>> fl.index
113 0
114 >>> next(fl)
115 0
116 >>> fl.index
117 1
118
119 """))
120
121# flatiter methods
122
123add_newdoc('numpy._core', 'flatiter', ('__array__',
124 """
125 __array__($self, dtype=None, /, *, copy=None)
126 --
127
128 flat.__array__([dtype], *, copy=None)
129
130 Get array from iterator
131
132 """))
133
134add_newdoc('numpy._core', 'flatiter', ('copy',
135 """
136 copy($self, /)
137 --
138
139 flat.copy()
140
141 Get a copy of the iterator as a 1-D array.
142
143 Examples
144 --------
145 >>> import numpy as np
146 >>> x = np.arange(6).reshape(2, 3)
147 >>> x
148 array([[0, 1, 2],
149 [3, 4, 5]])
150 >>> fl = x.flat
151 >>> fl.copy()
152 array([0, 1, 2, 3, 4, 5])
153
154 """))
155
156
157###############################################################################
158#
159# nditer
160#
161###############################################################################
162
163add_newdoc('numpy._core', 'nditer',
164 """
165 nditer(
166 op,
167 flags=None,
168 op_flags=None,
169 op_dtypes=None,
170 order='K',
171 casting='safe',
172 op_axes=None,
173 itershape=None,
174 buffersize=0,
175 )
176 --
177
178 nditer(op, flags=None, op_flags=None, op_dtypes=None, order='K',
179 casting='safe', op_axes=None, itershape=None, buffersize=0)
180
181 Efficient multi-dimensional iterator object to iterate over arrays.
182 To get started using this object, see the
183 :ref:`introductory guide to array iteration <arrays.nditer>`.
184
185 Parameters
186 ----------
187 op : ndarray or sequence of array_like
188 The array(s) to iterate over.
189 flags : sequence of str, optional
190 Flags to control the behavior of the iterator.
191
192 * ``buffered`` enables buffering when required.
193 * ``c_index`` causes a C-order index to be tracked.
194 * ``f_index`` causes a Fortran-order index to be tracked.
195 * ``multi_index`` causes a multi-index, or a tuple of indices
196 with one per iteration dimension, to be tracked.
197 * ``common_dtype`` causes all the operands to be converted to
198 a common data type, with copying or buffering as necessary.
199 * ``copy_if_overlap`` causes the iterator to determine if read
200 operands have overlap with write operands, and make temporary
201 copies as necessary to avoid overlap. False positives (needless
202 copying) are possible in some cases.
203 * ``delay_bufalloc`` delays allocation of the buffers until
204 a reset() call is made. Allows ``allocate`` operands to
205 be initialized before their values are copied into the buffers.
206 * ``external_loop`` causes the ``values`` given to be
207 one-dimensional arrays with multiple values instead of
208 zero-dimensional arrays.
209 * ``grow_inner`` allows the ``value`` array sizes to be made
210 larger than the buffer size when both ``buffered`` and
211 ``external_loop`` is used.
212 * ``ranged`` allows the iterator to be restricted to a sub-range
213 of the iterindex values.
214 * ``refs_ok`` enables iteration of reference types, such as
215 object arrays.
216 * ``reduce_ok`` enables iteration of ``readwrite`` operands
217 which are broadcasted, also known as reduction operands.
218 * ``zerosize_ok`` allows `itersize` to be zero.
219 op_flags : list of list of str, optional
220 This is a list of flags for each operand. At minimum, one of
221 ``readonly``, ``readwrite``, or ``writeonly`` must be specified.
222
223 * ``readonly`` indicates the operand will only be read from.
224 * ``readwrite`` indicates the operand will be read from and written to.
225 * ``writeonly`` indicates the operand will only be written to.
226 * ``no_broadcast`` prevents the operand from being broadcasted.
227 * ``contig`` forces the operand data to be contiguous.
228 * ``aligned`` forces the operand data to be aligned.
229 * ``nbo`` forces the operand data to be in native byte order.
230 * ``copy`` allows a temporary read-only copy if required.
231 * ``updateifcopy`` allows a temporary read-write copy if required.
232 * ``allocate`` causes the array to be allocated if it is None
233 in the ``op`` parameter.
234 * ``no_subtype`` prevents an ``allocate`` operand from using a subtype.
235 * ``arraymask`` indicates that this operand is the mask to use
236 for selecting elements when writing to operands with the
237 'writemasked' flag set. The iterator does not enforce this,
238 but when writing from a buffer back to the array, it only
239 copies those elements indicated by this mask.
240 * ``writemasked`` indicates that only elements where the chosen
241 ``arraymask`` operand is True will be written to.
242 * ``overlap_assume_elementwise`` can be used to mark operands that are
243 accessed only in the iterator order, to allow less conservative
244 copying when ``copy_if_overlap`` is present.
245 op_dtypes : dtype or tuple of dtype(s), optional
246 The required data type(s) of the operands. If copying or buffering
247 is enabled, the data will be converted to/from their original types.
248 order : {'C', 'F', 'A', 'K'}, optional
249 Controls the iteration order. 'C' means C order, 'F' means
250 Fortran order, 'A' means 'F' order if all the arrays are Fortran
251 contiguous, 'C' order otherwise, and 'K' means as close to the
252 order the array elements appear in memory as possible. This also
253 affects the element memory order of ``allocate`` operands, as they
254 are allocated to be compatible with iteration order.
255 Default is 'K'.
256 casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional
257 Controls what kind of data casting may occur when making a copy
258 or buffering. Setting this to 'unsafe' is not recommended,
259 as it can adversely affect accumulations.
260
261 * 'no' means the data types should not be cast at all.
262 * 'equiv' means only byte-order changes are allowed.
263 * 'safe' means only casts which can preserve values are allowed.
264 * 'same_kind' means only safe casts or casts within a kind,
265 like float64 to float32, are allowed.
266 * 'unsafe' means any data conversions may be done.
267 op_axes : list of list of ints, optional
268 If provided, is a list of ints or None for each operands.
269 The list of axes for an operand is a mapping from the dimensions
270 of the iterator to the dimensions of the operand. A value of
271 -1 can be placed for entries, causing that dimension to be
272 treated as `newaxis`.
273 itershape : tuple of ints, optional
274 The desired shape of the iterator. This allows ``allocate`` operands
275 with a dimension mapped by op_axes not corresponding to a dimension
276 of a different operand to get a value not equal to 1 for that
277 dimension.
278 buffersize : int, optional
279 When buffering is enabled, controls the size of the temporary
280 buffers. Set to 0 for the default value.
281
282 Attributes
283 ----------
284 dtypes : tuple of dtype(s)
285 The data types of the values provided in `value`. This may be
286 different from the operand data types if buffering is enabled.
287 Valid only before the iterator is closed.
288 finished : bool
289 Whether the iteration over the operands is finished or not.
290 has_delayed_bufalloc : bool
291 If True, the iterator was created with the ``delay_bufalloc`` flag,
292 and no reset() function was called on it yet.
293 has_index : bool
294 If True, the iterator was created with either the ``c_index`` or
295 the ``f_index`` flag, and the property `index` can be used to
296 retrieve it.
297 has_multi_index : bool
298 If True, the iterator was created with the ``multi_index`` flag,
299 and the property `multi_index` can be used to retrieve it.
300 index
301 When the ``c_index`` or ``f_index`` flag was used, this property
302 provides access to the index. Raises a ValueError if accessed
303 and ``has_index`` is False.
304 iterationneedsapi : bool
305 Whether iteration requires access to the Python API, for example
306 if one of the operands is an object array.
307 iterindex : int
308 An index which matches the order of iteration.
309 itersize : int
310 Size of the iterator.
311 itviews
312 Structured view(s) of `operands` in memory, matching the reordered
313 and optimized iterator access pattern. Valid only before the iterator
314 is closed.
315 multi_index
316 When the ``multi_index`` flag was used, this property
317 provides access to the index. Raises a ValueError if accessed
318 accessed and ``has_multi_index`` is False.
319 ndim : int
320 The dimensions of the iterator.
321 nop : int
322 The number of iterator operands.
323 operands : tuple of operand(s)
324 The array(s) to be iterated over. Valid only before the iterator is
325 closed.
326 shape : tuple of ints
327 Shape tuple, the shape of the iterator.
328 value
329 Value of ``operands`` at current iteration. Normally, this is a
330 tuple of array scalars, but if the flag ``external_loop`` is used,
331 it is a tuple of one dimensional arrays.
332
333 Notes
334 -----
335 `nditer` supersedes `flatiter`. The iterator implementation behind
336 `nditer` is also exposed by the NumPy C API.
337
338 The Python exposure supplies two iteration interfaces, one which follows
339 the Python iterator protocol, and another which mirrors the C-style
340 do-while pattern. The native Python approach is better in most cases, but
341 if you need the coordinates or index of an iterator, use the C-style pattern.
342
343 Examples
344 --------
345 Here is how we might write an ``iter_add`` function, using the
346 Python iterator protocol:
347
348 >>> import numpy as np
349
350 >>> def iter_add_py(x, y, out=None):
351 ... addop = np.add
352 ... it = np.nditer([x, y, out], [],
353 ... [['readonly'], ['readonly'], ['writeonly','allocate']])
354 ... with it:
355 ... for (a, b, c) in it:
356 ... addop(a, b, out=c)
357 ... return it.operands[2]
358
359 Here is the same function, but following the C-style pattern:
360
361 >>> def iter_add(x, y, out=None):
362 ... addop = np.add
363 ... it = np.nditer([x, y, out], [],
364 ... [['readonly'], ['readonly'], ['writeonly','allocate']])
365 ... with it:
366 ... while not it.finished:
367 ... addop(it[0], it[1], out=it[2])
368 ... it.iternext()
369 ... return it.operands[2]
370
371 Here is an example outer product function:
372
373 >>> def outer_it(x, y, out=None):
374 ... mulop = np.multiply
375 ... it = np.nditer([x, y, out], ['external_loop'],
376 ... [['readonly'], ['readonly'], ['writeonly', 'allocate']],
377 ... op_axes=[list(range(x.ndim)) + [-1] * y.ndim,
378 ... [-1] * x.ndim + list(range(y.ndim)),
379 ... None])
380 ... with it:
381 ... for (a, b, c) in it:
382 ... mulop(a, b, out=c)
383 ... return it.operands[2]
384
385 >>> a = np.arange(2)+1
386 >>> b = np.arange(3)+1
387 >>> outer_it(a,b)
388 array([[1, 2, 3],
389 [2, 4, 6]])
390
391 Here is an example function which operates like a "lambda" ufunc:
392
393 >>> def luf(lamdaexpr, *args, **kwargs):
394 ... '''luf(lambdaexpr, op1, ..., opn, out=None, order='K', casting='safe', buffersize=0)'''
395 ... nargs = len(args)
396 ... op = (kwargs.get('out',None),) + args
397 ... it = np.nditer(op, ['buffered','external_loop'],
398 ... [['writeonly','allocate','no_broadcast']] +
399 ... [['readonly','nbo','aligned']]*nargs,
400 ... order=kwargs.get('order','K'),
401 ... casting=kwargs.get('casting','safe'),
402 ... buffersize=kwargs.get('buffersize',0))
403 ... while not it.finished:
404 ... it[0] = lamdaexpr(*it[1:])
405 ... it.iternext()
406 ... return it.operands[0]
407
408 >>> a = np.arange(5)
409 >>> b = np.ones(5)
410 >>> luf(lambda i,j:i*i + j/2, a, b)
411 array([ 0.5, 1.5, 4.5, 9.5, 16.5])
412
413 If operand flags ``"writeonly"`` or ``"readwrite"`` are used the
414 operands may be views into the original data with the
415 `WRITEBACKIFCOPY` flag. In this case `nditer` must be used as a
416 context manager or the `nditer.close` method must be called before
417 using the result. The temporary data will be written back to the
418 original data when the :meth:`~object.__exit__` function is called
419 but not before:
420
421 >>> a = np.arange(6, dtype='i4')[::-2]
422 >>> with np.nditer(a, [],
423 ... [['writeonly', 'updateifcopy']],
424 ... casting='unsafe',
425 ... op_dtypes=[np.dtype('f4')]) as i:
426 ... x = i.operands[0]
427 ... x[:] = [-1, -2, -3]
428 ... # a still unchanged here
429 >>> a, x
430 (array([-1, -2, -3], dtype=int32), array([-1., -2., -3.], dtype=float32))
431
432 It is important to note that once the iterator is exited, dangling
433 references (like `x` in the example) may or may not share data with
434 the original data `a`. If writeback semantics were active, i.e. if
435 `x.base.flags.writebackifcopy` is `True`, then exiting the iterator
436 will sever the connection between `x` and `a`, writing to `x` will
437 no longer write to `a`. If writeback semantics are not active, then
438 `x.data` will still point at some part of `a.data`, and writing to
439 one will affect the other.
440
441 Context management and the `close` method appeared in version 1.15.0.
442
443 """)
444
445# nditer attributes
446
447add_newdoc('numpy._core', 'nditer', ('operands',
448 """
449 operands[`Slice`]
450
451 The array(s) to be iterated over. Valid only before the iterator is closed.
452 """))
453
454# nditer methods
455
456add_newdoc('numpy._core', 'nditer', ('copy',
457 """
458 copy($self, /)
459 --
460
461 copy()
462
463 Get a copy of the iterator in its current state.
464
465 Examples
466 --------
467 >>> import numpy as np
468 >>> x = np.arange(10)
469 >>> y = x + 1
470 >>> it = np.nditer([x, y])
471 >>> next(it)
472 (array(0), array(1))
473 >>> it2 = it.copy()
474 >>> next(it2)
475 (array(1), array(2))
476
477 """))
478
479add_newdoc('numpy._core', 'nditer', ('debug_print',
480 """
481 debug_print($self, /)
482 --
483
484 debug_print()
485
486 Print the current state of the `nditer` instance and debug info to stdout.
487
488 """))
489
490add_newdoc('numpy._core', 'nditer', ('enable_external_loop',
491 """
492 enable_external_loop($self, /)
493 --
494
495 enable_external_loop()
496
497 When the "external_loop" was not used during construction, but
498 is desired, this modifies the iterator to behave as if the flag
499 was specified.
500
501 """))
502
503add_newdoc('numpy._core', 'nditer', ('iternext',
504 """
505 iternext($self, /)
506 --
507
508 iternext()
509
510 Check whether iterations are left, and perform a single internal iteration
511 without returning the result. Used in the C-style pattern do-while
512 pattern. For an example, see `nditer`.
513
514 Returns
515 -------
516 iternext : bool
517 Whether or not there are iterations left.
518
519 """))
520
521add_newdoc('numpy._core', 'nditer', ('remove_axis',
522 """
523 remove_axis($self, i, /)
524 --
525
526 remove_axis(i, /)
527
528 Removes axis `i` from the iterator. Requires that the flag "multi_index"
529 be enabled.
530
531 """))
532
533add_newdoc('numpy._core', 'nditer', ('remove_multi_index',
534 """
535 remove_multi_index($self, /)
536 --
537
538 remove_multi_index()
539
540 When the "multi_index" flag was specified, this removes it, allowing
541 the internal iteration structure to be optimized further.
542
543 """))
544
545add_newdoc('numpy._core', 'nditer', ('reset',
546 """
547 reset($self, /)
548 --
549
550 reset()
551
552 Reset the iterator to its initial state.
553
554 """))
555
556add_newdoc('numpy._core', 'nditer', ('close',
557 """
558 close($self, /)
559 --
560
561 close()
562
563 Resolve all writeback semantics in writeable operands.
564
565 See Also
566 --------
567 :ref:`nditer-context-manager`
568
569 """))
570
571# nested_iters
572
573add_newdoc('numpy._core', 'nested_iters',
574 """
575 nested_iters(
576 op,
577 axes,
578 flags=None,
579 op_flags=None,
580 op_dtypes=None,
581 order='K',
582 casting='safe',
583 buffersize=0,
584 )
585 --
586
587 nested_iters(op, axes, flags=None, op_flags=None, op_dtypes=None,
588 order='K', casting='safe', buffersize=0)
589
590 Create nditers for use in nested loops
591
592 Create a tuple of `nditer` objects which iterate in nested loops over
593 different axes of the op argument. The first iterator is used in the
594 outermost loop, the last in the innermost loop. Advancing one will
595 change the subsequent iterators to point at its new element.
596
597 Parameters
598 ----------
599 op : ndarray or sequence of array_like
600 The array(s) to iterate over.
601 axes : list of list of int
602 Each item is used as an "op_axes" argument to an nditer
603 flags, op_flags, op_dtypes, order, casting, buffersize (optional)
604 See `nditer` parameters of the same name
605
606 Returns
607 -------
608 iters : tuple of nditer
609 An nditer for each item in `axes`, outermost first
610
611 See Also
612 --------
613 nditer
614
615 Examples
616 --------
617
618 Basic usage. Note how y is the "flattened" version of
619 [a[:, 0, :], a[:, 1, 0], a[:, 2, :]] since we specified
620 the first iter's axes as [1]
621
622 >>> import numpy as np
623 >>> a = np.arange(12).reshape(2, 3, 2)
624 >>> i, j = np.nested_iters(a, [[1], [0, 2]], flags=["multi_index"])
625 >>> for x in i:
626 ... print(i.multi_index)
627 ... for y in j:
628 ... print('', j.multi_index, y)
629 (0,)
630 (0, 0) 0
631 (0, 1) 1
632 (1, 0) 6
633 (1, 1) 7
634 (1,)
635 (0, 0) 2
636 (0, 1) 3
637 (1, 0) 8
638 (1, 1) 9
639 (2,)
640 (0, 0) 4
641 (0, 1) 5
642 (1, 0) 10
643 (1, 1) 11
644
645 """)
646
647###############################################################################
648#
649# broadcast
650#
651###############################################################################
652
653add_newdoc('numpy._core', 'broadcast',
654 """
655 broadcast(*arrays)
656 --
657
658 Produce an object that mimics broadcasting.
659
660 Parameters
661 ----------
662 in1, in2, ... : array_like
663 Input parameters.
664
665 Returns
666 -------
667 b : broadcast object
668 Broadcast the input parameters against one another, and
669 return an object that encapsulates the result.
670 Amongst others, it has ``shape`` and ``nd`` properties, and
671 may be used as an iterator.
672
673 See Also
674 --------
675 broadcast_arrays
676 broadcast_to
677 broadcast_shapes
678
679 Examples
680 --------
681
682 Manually adding two vectors, using broadcasting:
683
684 >>> import numpy as np
685 >>> x = np.array([[1], [2], [3]])
686 >>> y = np.array([4, 5, 6])
687 >>> b = np.broadcast(x, y)
688
689 >>> out = np.empty(b.shape)
690 >>> out.flat = [u+v for (u,v) in b]
691 >>> out
692 array([[5., 6., 7.],
693 [6., 7., 8.],
694 [7., 8., 9.]])
695
696 Compare against built-in broadcasting:
697
698 >>> x + y
699 array([[5, 6, 7],
700 [6, 7, 8],
701 [7, 8, 9]])
702
703 """)
704
705# attributes
706
707add_newdoc('numpy._core', 'broadcast', ('index',
708 """
709 current index in broadcasted result
710
711 Examples
712 --------
713
714 >>> import numpy as np
715 >>> x = np.array([[1], [2], [3]])
716 >>> y = np.array([4, 5, 6])
717 >>> b = np.broadcast(x, y)
718 >>> b.index
719 0
720 >>> next(b), next(b), next(b)
721 ((1, 4), (1, 5), (1, 6))
722 >>> b.index
723 3
724
725 """))
726
727add_newdoc('numpy._core', 'broadcast', ('iters',
728 """
729 tuple of iterators along ``self``'s "components."
730
731 Returns a tuple of `numpy.flatiter` objects, one for each "component"
732 of ``self``.
733
734 See Also
735 --------
736 numpy.flatiter
737
738 Examples
739 --------
740
741 >>> import numpy as np
742 >>> x = np.array([1, 2, 3])
743 >>> y = np.array([[4], [5], [6]])
744 >>> b = np.broadcast(x, y)
745 >>> row, col = b.iters
746 >>> next(row), next(col)
747 (1, 4)
748
749 """))
750
751add_newdoc('numpy._core', 'broadcast', ('ndim',
752 """
753 Number of dimensions of broadcasted result. Alias for `nd`.
754
755 Examples
756 --------
757 >>> import numpy as np
758 >>> x = np.array([1, 2, 3])
759 >>> y = np.array([[4], [5], [6]])
760 >>> b = np.broadcast(x, y)
761 >>> b.ndim
762 2
763
764 """))
765
766add_newdoc('numpy._core', 'broadcast', ('nd',
767 """
768 Number of dimensions of broadcasted result. For code intended for NumPy
769 1.12.0 and later the more consistent `ndim` is preferred.
770
771 Examples
772 --------
773 >>> import numpy as np
774 >>> x = np.array([1, 2, 3])
775 >>> y = np.array([[4], [5], [6]])
776 >>> b = np.broadcast(x, y)
777 >>> b.nd
778 2
779
780 """))
781
782add_newdoc('numpy._core', 'broadcast', ('numiter',
783 """
784 Number of iterators possessed by the broadcasted result.
785
786 Examples
787 --------
788 >>> import numpy as np
789 >>> x = np.array([1, 2, 3])
790 >>> y = np.array([[4], [5], [6]])
791 >>> b = np.broadcast(x, y)
792 >>> b.numiter
793 2
794
795 """))
796
797add_newdoc('numpy._core', 'broadcast', ('shape',
798 """
799 Shape of broadcasted result.
800
801 Examples
802 --------
803 >>> import numpy as np
804 >>> x = np.array([1, 2, 3])
805 >>> y = np.array([[4], [5], [6]])
806 >>> b = np.broadcast(x, y)
807 >>> b.shape
808 (3, 3)
809
810 """))
811
812add_newdoc('numpy._core', 'broadcast', ('size',
813 """
814 Total size of broadcasted result.
815
816 Examples
817 --------
818 >>> import numpy as np
819 >>> x = np.array([1, 2, 3])
820 >>> y = np.array([[4], [5], [6]])
821 >>> b = np.broadcast(x, y)
822 >>> b.size
823 9
824
825 """))
826
827# methods
828
829add_newdoc('numpy._core', 'broadcast', ('reset',
830 """
831 reset($self, /)
832 --
833
834 reset()
835
836 Reset the broadcasted result's iterator(s).
837
838 Parameters
839 ----------
840 None
841
842 Returns
843 -------
844 None
845
846 Examples
847 --------
848 >>> import numpy as np
849 >>> x = np.array([1, 2, 3])
850 >>> y = np.array([[4], [5], [6]])
851 >>> b = np.broadcast(x, y)
852 >>> b.index
853 0
854 >>> next(b), next(b), next(b)
855 ((1, 4), (2, 4), (3, 4))
856 >>> b.index
857 3
858 >>> b.reset()
859 >>> b.index
860 0
861
862 """))
863
864###############################################################################
865#
866# numpy functions
867#
868###############################################################################
869
870add_newdoc('numpy._core.multiarray', 'array',
871 """
872 array(
873 object,
874 dtype=None,
875 *,
876 copy=True,
877 order='K',
878 subok=False,
879 ndmin=0,
880 ndmax=0,
881 like=None,
882 )
883 --
884
885 array(object, dtype=None, *, copy=True, order='K', subok=False, ndmin=0,
886 ndmax=0, like=None)
887
888 Create an array.
889
890 Parameters
891 ----------
892 object : array_like
893 An array, any object exposing the array interface, an object whose
894 ``__array__`` method returns an array, or any (nested) sequence.
895 If object is a scalar, a 0-dimensional array containing object is
896 returned.
897 dtype : data-type, optional
898 The desired data-type for the array. If not given, NumPy will try to use
899 a default ``dtype`` that can represent the values (by applying promotion
900 rules when necessary.)
901 copy : bool, optional
902 If ``True`` (default), then the array data is copied. If ``None``,
903 a copy will only be made if ``__array__`` returns a copy, if obj is
904 a nested sequence, or if a copy is needed to satisfy any of the other
905 requirements (``dtype``, ``order``, etc.). Note that any copy of
906 the data is shallow, i.e., for arrays with object dtype, the new
907 array will point to the same objects. See Examples for `ndarray.copy`.
908 For ``False`` it raises a ``ValueError`` if a copy cannot be avoided.
909 Default: ``True``.
910 order : {'K', 'A', 'C', 'F'}, optional
911 Specify the memory layout of the array. If object is not an array, the
912 newly created array will be in C order (row major) unless 'F' is
913 specified, in which case it will be in Fortran order (column major).
914 If object is an array the following holds.
915
916 ===== ========= ===================================================
917 order no copy copy=True
918 ===== ========= ===================================================
919 'K' unchanged F & C order preserved, otherwise most similar order
920 'A' unchanged F order if input is F and not C, otherwise C order
921 'C' C order C order
922 'F' F order F order
923 ===== ========= ===================================================
924
925 When ``copy=None`` and a copy is made for other reasons, the result is
926 the same as if ``copy=True``, with some exceptions for 'A', see the
927 Notes section. The default order is 'K'.
928 subok : bool, optional
929 If True, then sub-classes will be passed-through, otherwise
930 the returned array will be forced to be a base-class array (default).
931 ndmin : int, optional
932 Specifies the minimum number of dimensions that the resulting
933 array should have. Ones will be prepended to the shape as
934 needed to meet this requirement.
935 ndmax : int, optional
936 Specifies the maximum number of dimensions to create when inferring
937 shape from nested sequences. By default (ndmax=0), NumPy recurses
938 through all nesting levels (up to the compile-time constant
939 ``NPY_MAXDIMS``).
940 Setting ``ndmax`` stops recursion at the specified depth, preserving
941 deeper nested structures as objects instead of promoting them to
942 higher-dimensional arrays. In this case, ``dtype=object`` is required.
943
944 .. versionadded:: 2.4.0
945 ${ARRAY_FUNCTION_LIKE}
946
947 .. versionadded:: 1.20.0
948
949 Returns
950 -------
951 out : ndarray
952 An array object satisfying the specified requirements.
953
954 See Also
955 --------
956 empty_like : Return an empty array with shape and type of input.
957 ones_like : Return an array of ones with shape and type of input.
958 zeros_like : Return an array of zeros with shape and type of input.
959 full_like : Return a new array with shape of input filled with value.
960 empty : Return a new uninitialized array.
961 ones : Return a new array setting values to one.
962 zeros : Return a new array setting values to zero.
963 full : Return a new array of given shape filled with value.
964 copy : Return an array copy of the given object.
965
966
967 Notes
968 -----
969 When order is 'A' and ``object`` is an array in neither 'C' nor 'F' order,
970 and a copy is forced by a change in dtype, then the order of the result is
971 not necessarily 'C' as expected. This is likely a bug.
972
973 Examples
974 --------
975 >>> import numpy as np
976 >>> np.array([1, 2, 3])
977 array([1, 2, 3])
978
979 Upcasting:
980
981 >>> np.array([1, 2, 3.0])
982 array([ 1., 2., 3.])
983
984 More than one dimension:
985
986 >>> np.array([[1, 2], [3, 4]])
987 array([[1, 2],
988 [3, 4]])
989
990 Minimum dimensions 2:
991
992 >>> np.array([1, 2, 3], ndmin=2)
993 array([[1, 2, 3]])
994
995 Type provided:
996
997 >>> np.array([1, 2, 3], dtype=complex)
998 array([ 1.+0.j, 2.+0.j, 3.+0.j])
999
1000 Data-type consisting of more than one element:
1001
1002 >>> x = np.array([(1,2),(3,4)],dtype=[('a','<i4'),('b','<i4')])
1003 >>> x['a']
1004 array([1, 3], dtype=int32)
1005
1006 Creating an array from sub-classes:
1007
1008 >>> np.array(np.asmatrix('1 2; 3 4'))
1009 array([[1, 2],
1010 [3, 4]])
1011
1012 >>> np.array(np.asmatrix('1 2; 3 4'), subok=True)
1013 matrix([[1, 2],
1014 [3, 4]])
1015
1016 Limiting the maximum dimensions with ``ndmax``:
1017
1018 >>> a = np.array([[1, 2], [3, 4]], dtype=object, ndmax=2)
1019 >>> a
1020 array([[1, 2],
1021 [3, 4]], dtype=object)
1022 >>> a.shape
1023 (2, 2)
1024
1025 >>> b = np.array([[1, 2], [3, 4]], dtype=object, ndmax=1)
1026 >>> b
1027 array([list([1, 2]), list([3, 4])], dtype=object)
1028 >>> b.shape
1029 (2,)
1030
1031 """)
1032
1033add_newdoc('numpy._core.multiarray', 'asarray',
1034 """
1035 asarray(a, dtype=None, order=None, *, device=None, copy=None, like=None)
1036 --
1037
1038 asarray(a, dtype=None, order=None, *, device=None, copy=None, like=None)
1039
1040 Convert the input to an array.
1041
1042 Parameters
1043 ----------
1044 a : array_like
1045 Input data, in any form that can be converted to an array. This
1046 includes lists, lists of tuples, tuples, tuples of tuples, tuples
1047 of lists and ndarrays.
1048 dtype : data-type, optional
1049 By default, the data-type is inferred from the input data.
1050 order : {'C', 'F', 'A', 'K'}, optional
1051 The memory layout of the output.
1052 'C' gives a row-major layout (C-style),
1053 'F' gives a column-major layout (Fortran-style).
1054 'C' and 'F' will copy if needed to ensure the output format.
1055 'A' (any) is equivalent to 'F' if input a is non-contiguous or Fortran-contiguous, otherwise, it is equivalent to 'C'.
1056 Unlike 'C' or 'F', 'A' does not ensure that the result is contiguous.
1057 'K' (keep) is the default and preserves the input order for the output.
1058 device : str, optional
1059 The device on which to place the created array. Default: ``None``.
1060 For Array-API interoperability only, so must be ``"cpu"`` if passed.
1061
1062 .. versionadded:: 2.0.0
1063 copy : bool, optional
1064 If ``True``, then the object is copied. If ``None`` then the object is
1065 copied only if needed, i.e. if ``__array__`` returns a copy, if obj
1066 is a nested sequence, or if a copy is needed to satisfy any of
1067 the other requirements (``dtype``, ``order``, etc.).
1068 For ``False`` it raises a ``ValueError`` if a copy cannot be avoided.
1069 Default: ``None``.
1070
1071 .. versionadded:: 2.0.0
1072 ${ARRAY_FUNCTION_LIKE}
1073
1074 .. versionadded:: 1.20.0
1075
1076 Returns
1077 -------
1078 out : ndarray
1079 Array interpretation of ``a``. No copy is performed if the input
1080 is already an ndarray with matching dtype and order. If ``a`` is a
1081 subclass of ndarray, a base class ndarray is returned.
1082
1083 See Also
1084 --------
1085 asanyarray : Similar function which passes through subclasses.
1086 ascontiguousarray : Convert input to a contiguous array.
1087 asfortranarray : Convert input to an ndarray with column-major memory order.
1088 asarray_chkfinite : Similar function which checks input for NaNs and Infs.
1089 fromiter : Create an array from an iterator.
1090 fromfunction : Construct an array by executing a function on grid positions.
1091
1092 Examples
1093 --------
1094 Convert a list into an array:
1095
1096 >>> a = [1, 2]
1097 >>> import numpy as np
1098 >>> np.asarray(a)
1099 array([1, 2])
1100
1101 Existing arrays are not copied:
1102
1103 >>> a = np.array([1, 2])
1104 >>> np.asarray(a) is a
1105 True
1106
1107 If `dtype` is set, array is copied only if dtype does not match:
1108
1109 >>> a = np.array([1, 2], dtype=np.float32)
1110 >>> np.shares_memory(np.asarray(a, dtype=np.float32), a)
1111 True
1112 >>> np.shares_memory(np.asarray(a, dtype=np.float64), a)
1113 False
1114
1115 Contrary to `asanyarray`, ndarray subclasses are not passed through:
1116
1117 >>> issubclass(np.recarray, np.ndarray)
1118 True
1119 >>> a = np.array([(1., 2), (3., 4)], dtype='f4,i4').view(np.recarray)
1120 >>> np.asarray(a) is a
1121 False
1122 >>> np.asanyarray(a) is a
1123 True
1124
1125 """)
1126
1127add_newdoc('numpy._core.multiarray', 'asanyarray',
1128 """
1129 asanyarray(a, dtype=None, order=None, *, device=None, copy=None, like=None)
1130 --
1131
1132 asanyarray(a, dtype=None, order=None, *, device=None, copy=None, like=None)
1133
1134 Convert the input to an ndarray, but pass ndarray subclasses through.
1135
1136 Parameters
1137 ----------
1138 a : array_like
1139 Input data, in any form that can be converted to an array. This
1140 includes scalars, lists, lists of tuples, tuples, tuples of tuples,
1141 tuples of lists, and ndarrays.
1142 dtype : data-type, optional
1143 By default, the data-type is inferred from the input data.
1144 order : {'C', 'F', 'A', 'K'}, optional
1145 The memory layout of the output.
1146 'C' gives a row-major layout (C-style),
1147 'F' gives a column-major layout (Fortran-style).
1148 'C' and 'F' will copy if needed to ensure the output format.
1149 'A' (any) is equivalent to 'F' if input a is non-contiguous or Fortran-contiguous, otherwise, it is equivalent to 'C'.
1150 Unlike 'C' or 'F', 'A' does not ensure that the result is contiguous.
1151 'K' (keep) preserves the input order for the output.
1152 'C' is the default.
1153 device : str, optional
1154 The device on which to place the created array. Default: ``None``.
1155 For Array-API interoperability only, so must be ``"cpu"`` if passed.
1156
1157 .. versionadded:: 2.1.0
1158
1159 copy : bool, optional
1160 If ``True``, then the object is copied. If ``None`` then the object is
1161 copied only if needed, i.e. if ``__array__`` returns a copy, if obj
1162 is a nested sequence, or if a copy is needed to satisfy any of
1163 the other requirements (``dtype``, ``order``, etc.).
1164 For ``False`` it raises a ``ValueError`` if a copy cannot be avoided.
1165 Default: ``None``.
1166
1167 .. versionadded:: 2.1.0
1168
1169 ${ARRAY_FUNCTION_LIKE}
1170
1171 .. versionadded:: 1.20.0
1172
1173 Returns
1174 -------
1175 out : ndarray or an ndarray subclass
1176 Array interpretation of `a`. If `a` is an ndarray or a subclass
1177 of ndarray, it is returned as-is and no copy is performed.
1178
1179 See Also
1180 --------
1181 asarray : Similar function which always returns ndarrays.
1182 ascontiguousarray : Convert input to a contiguous array.
1183 asfortranarray : Convert input to an ndarray with column-major memory order.
1184 asarray_chkfinite : Similar function which checks input for NaNs and Infs.
1185 fromiter : Create an array from an iterator.
1186 fromfunction : Construct an array by executing a function on grid positions.
1187
1188 Examples
1189 --------
1190 Convert a list into an array:
1191
1192 >>> a = [1, 2]
1193 >>> import numpy as np
1194 >>> np.asanyarray(a)
1195 array([1, 2])
1196
1197 Instances of `ndarray` subclasses are passed through as-is:
1198
1199 >>> a = np.array([(1., 2), (3., 4)], dtype='f4,i4').view(np.recarray)
1200 >>> np.asanyarray(a) is a
1201 True
1202
1203 """)
1204
1205add_newdoc('numpy._core.multiarray', 'ascontiguousarray',
1206 """
1207 ascontiguousarray(a, dtype=None, *, like=None)
1208 --
1209
1210 ascontiguousarray(a, dtype=None, *, like=None)
1211
1212 Return a contiguous array (ndim >= 1) in memory (C order).
1213
1214 Parameters
1215 ----------
1216 a : array_like
1217 Input array.
1218 dtype : str or dtype object, optional
1219 Data-type of returned array.
1220 ${ARRAY_FUNCTION_LIKE}
1221
1222 .. versionadded:: 1.20.0
1223
1224 Returns
1225 -------
1226 out : ndarray
1227 Contiguous array of same shape and content as `a`, with type `dtype`
1228 if specified.
1229
1230 See Also
1231 --------
1232 asfortranarray : Convert input to an ndarray with column-major memory order.
1233 require : Return an ndarray that satisfies requirements.
1234 ndarray.flags : Information about the memory layout of the array.
1235
1236 Examples
1237 --------
1238 Starting with a Fortran-contiguous array:
1239
1240 >>> import numpy as np
1241 >>> x = np.ones((2, 3), order='F')
1242 >>> x.flags['F_CONTIGUOUS']
1243 True
1244
1245 Calling ``ascontiguousarray`` makes a C-contiguous copy:
1246
1247 >>> y = np.ascontiguousarray(x)
1248 >>> y.flags['C_CONTIGUOUS']
1249 True
1250 >>> np.may_share_memory(x, y)
1251 False
1252
1253 Now, starting with a C-contiguous array:
1254
1255 >>> x = np.ones((2, 3), order='C')
1256 >>> x.flags['C_CONTIGUOUS']
1257 True
1258
1259 Then, calling ``ascontiguousarray`` returns the same object:
1260
1261 >>> y = np.ascontiguousarray(x)
1262 >>> x is y
1263 True
1264
1265 Note: This function returns an array with at least one-dimension (1-d)
1266 so it will not preserve 0-d arrays.
1267
1268 """)
1269
1270add_newdoc('numpy._core.multiarray', 'asfortranarray',
1271 """
1272 asfortranarray(a, dtype=None, *, like=None)
1273 --
1274
1275 asfortranarray(a, dtype=None, *, like=None)
1276
1277 Return an array (ndim >= 1) laid out in Fortran order in memory.
1278
1279 Parameters
1280 ----------
1281 a : array_like
1282 Input array.
1283 dtype : str or dtype object, optional
1284 By default, the data-type is inferred from the input data.
1285 ${ARRAY_FUNCTION_LIKE}
1286
1287 .. versionadded:: 1.20.0
1288
1289 Returns
1290 -------
1291 out : ndarray
1292 The input `a` in Fortran, or column-major, order.
1293
1294 See Also
1295 --------
1296 ascontiguousarray : Convert input to a contiguous (C order) array.
1297 asanyarray : Convert input to an ndarray with either row or
1298 column-major memory order.
1299 require : Return an ndarray that satisfies requirements.
1300 ndarray.flags : Information about the memory layout of the array.
1301
1302 Examples
1303 --------
1304 Starting with a C-contiguous array:
1305
1306 >>> import numpy as np
1307 >>> x = np.ones((2, 3), order='C')
1308 >>> x.flags['C_CONTIGUOUS']
1309 True
1310
1311 Calling ``asfortranarray`` makes a Fortran-contiguous copy:
1312
1313 >>> y = np.asfortranarray(x)
1314 >>> y.flags['F_CONTIGUOUS']
1315 True
1316 >>> np.may_share_memory(x, y)
1317 False
1318
1319 Now, starting with a Fortran-contiguous array:
1320
1321 >>> x = np.ones((2, 3), order='F')
1322 >>> x.flags['F_CONTIGUOUS']
1323 True
1324
1325 Then, calling ``asfortranarray`` returns the same object:
1326
1327 >>> y = np.asfortranarray(x)
1328 >>> x is y
1329 True
1330
1331 Note: This function returns an array with at least one-dimension (1-d)
1332 so it will not preserve 0-d arrays.
1333
1334 """)
1335
1336add_newdoc('numpy._core.multiarray', 'empty',
1337 """
1338 empty(shape, dtype=None, order='C', *, device=None, like=None)
1339 --
1340
1341 empty(shape, dtype=None, order='C', *, device=None, like=None)
1342
1343 Return a new array of given shape and type, without initializing entries.
1344
1345 Parameters
1346 ----------
1347 shape : int or tuple of int
1348 Shape of the empty array, e.g., ``(2, 3)`` or ``2``.
1349 dtype : data-type, optional
1350 Desired output data-type for the array, e.g, `numpy.int8`. Default is
1351 `numpy.float64`.
1352 order : {'C', 'F'}, optional, default: 'C'
1353 Whether to store multi-dimensional data in row-major
1354 (C-style) or column-major (Fortran-style) order in memory.
1355 device : str, optional
1356 The device on which to place the created array. Default: ``None``.
1357 For Array-API interoperability only, so must be ``"cpu"`` if passed.
1358
1359 .. versionadded:: 2.0.0
1360 ${ARRAY_FUNCTION_LIKE}
1361
1362 .. versionadded:: 1.20.0
1363
1364 Returns
1365 -------
1366 out : ndarray
1367 Array of uninitialized (arbitrary) data of the given shape, dtype, and
1368 order. Object arrays will be initialized to None.
1369
1370 See Also
1371 --------
1372 empty_like : Return an empty array with shape and type of input.
1373 ones : Return a new array setting values to one.
1374 zeros : Return a new array setting values to zero.
1375 full : Return a new array of given shape filled with value.
1376
1377 Notes
1378 -----
1379 Unlike other array creation functions (e.g. `zeros`, `ones`, `full`),
1380 `empty` does not initialize the values of the array, and may therefore be
1381 marginally faster. However, the values stored in the newly allocated array
1382 are arbitrary. For reproducible behavior, be sure to set each element of
1383 the array before reading.
1384
1385 Examples
1386 --------
1387 >>> import numpy as np
1388 >>> np.empty([2, 2])
1389 array([[ -9.74499359e+001, 6.69583040e-309],
1390 [ 2.13182611e-314, 3.06959433e-309]]) #uninitialized
1391
1392 >>> np.empty([2, 2], dtype=int)
1393 array([[-1073741821, -1067949133],
1394 [ 496041986, 19249760]]) #uninitialized
1395
1396 """)
1397
1398add_newdoc('numpy._core.multiarray', 'scalar',
1399 """
1400 scalar(dtype, obj)
1401
1402 Return a new scalar array of the given type initialized with obj.
1403
1404 This function is meant mainly for pickle support. `dtype` must be a
1405 valid data-type descriptor. If `dtype` corresponds to an object
1406 descriptor, then `obj` can be any object, otherwise `obj` must be a
1407 string. If `obj` is not given, it will be interpreted as None for object
1408 type and as zeros for all other types.
1409
1410 """) # sufficient null bytes for all number dtypes
1411
1412add_newdoc('numpy._core.multiarray', 'zeros',
1413 """
1414 zeros(shape, dtype=None, order='C', *, device=None, like=None)
1415 --
1416
1417 zeros(shape, dtype=None, order='C', *, device=None, like=None)
1418
1419 Return a new array of given shape and type, filled with zeros.
1420
1421 Parameters
1422 ----------
1423 shape : int or tuple of ints
1424 Shape of the new array, e.g., ``(2, 3)`` or ``2``.
1425 dtype : data-type, optional
1426 The desired data-type for the array, e.g., `numpy.int8`. Default is
1427 `numpy.float64`.
1428 order : {'C', 'F'}, optional, default: 'C'
1429 Whether to store multi-dimensional data in row-major
1430 (C-style) or column-major (Fortran-style) order in memory.
1431 device : str, optional
1432 The device on which to place the created array. Default: ``None``.
1433 For Array-API interoperability only, so must be ``"cpu"`` if passed.
1434
1435 .. versionadded:: 2.0.0
1436 ${ARRAY_FUNCTION_LIKE}
1437
1438 .. versionadded:: 1.20.0
1439
1440 Returns
1441 -------
1442 out : ndarray
1443 Array of zeros with the given shape, dtype, and order.
1444
1445 See Also
1446 --------
1447 zeros_like : Return an array of zeros with shape and type of input.
1448 empty : Return a new uninitialized array.
1449 ones : Return a new array setting values to one.
1450 full : Return a new array of given shape filled with value.
1451
1452 Examples
1453 --------
1454 >>> import numpy as np
1455 >>> np.zeros(5)
1456 array([ 0., 0., 0., 0., 0.])
1457
1458 >>> np.zeros((5,), dtype=int)
1459 array([0, 0, 0, 0, 0])
1460
1461 >>> np.zeros((2, 1))
1462 array([[ 0.],
1463 [ 0.]])
1464
1465 >>> s = (2,2)
1466 >>> np.zeros(s)
1467 array([[ 0., 0.],
1468 [ 0., 0.]])
1469
1470 >>> np.zeros((2,), dtype=[('x', 'i4'), ('y', 'i4')]) # custom dtype
1471 array([(0, 0), (0, 0)],
1472 dtype=[('x', '<i4'), ('y', '<i4')])
1473
1474 """)
1475
1476add_newdoc('numpy._core.multiarray', 'set_typeDict',
1477 """
1478 set_typeDict(dict)
1479
1480 Set the internal dictionary that can look up an array type using a
1481 registered code.
1482
1483 """)
1484
1485# Signature can be updated for 2.5.0 release, see gh-30235 for details
1486add_newdoc('numpy._core.multiarray', 'fromstring',
1487 """
1488 fromstring(string, dtype=float, count=-1, *, sep, like=None)
1489
1490 A new 1-D array initialized from text data in a string.
1491
1492 Parameters
1493 ----------
1494 string : str
1495 A string containing the data.
1496 dtype : data-type, optional
1497 The data type of the array; default: `numpy.float64`. For binary input data,
1498 the data must be in exactly this format. Most builtin numeric types are
1499 supported and extension types may be supported.
1500 count : int, optional
1501 Read this number of `dtype` elements from the data. If this is
1502 negative (the default), the count will be determined from the
1503 length of the data.
1504 sep : str, optional
1505 The string separating numbers in the data; extra whitespace between
1506 elements is also ignored.
1507
1508 .. deprecated:: 1.14
1509 Passing ``sep=''``, the default, is deprecated since it will
1510 trigger the deprecated binary mode of this function. This mode
1511 interprets `string` as binary bytes, rather than ASCII text with
1512 decimal numbers, an operation which is better spelt
1513 ``frombuffer(string, dtype, count)``. If `string` contains unicode
1514 text, the binary mode of `fromstring` will first encode it into
1515 bytes using utf-8, which will not produce sane results.
1516
1517 ${ARRAY_FUNCTION_LIKE}
1518
1519 .. versionadded:: 1.20.0
1520
1521 Returns
1522 -------
1523 arr : ndarray
1524 The constructed array.
1525
1526 Raises
1527 ------
1528 ValueError
1529 If the string is not the correct size to satisfy the requested
1530 `dtype` and `count`.
1531
1532 See Also
1533 --------
1534 frombuffer, fromfile, fromiter
1535
1536 Examples
1537 --------
1538 >>> import numpy as np
1539 >>> np.fromstring('1 2', dtype=int, sep=' ')
1540 array([1, 2])
1541 >>> np.fromstring('1, 2', dtype=int, sep=',')
1542 array([1, 2])
1543
1544 """)
1545
1546add_newdoc('numpy._core.multiarray', 'compare_chararrays',
1547 """
1548 compare_chararrays(a1, a2, cmp, rstrip)
1549 --
1550
1551 compare_chararrays(a1, a2, cmp, rstrip)
1552
1553 Performs element-wise comparison of two string arrays using the
1554 comparison operator specified by `cmp`.
1555
1556 Parameters
1557 ----------
1558 a1, a2 : array_like
1559 Arrays to be compared.
1560 cmp : {"<", "<=", "==", ">=", ">", "!="}
1561 Type of comparison.
1562 rstrip : bool
1563 If True, the spaces at the end of strings are removed before the comparison.
1564
1565 Returns
1566 -------
1567 out : ndarray
1568 The output array of type `numpy.bool` with the same shape as `a1` and `a2`.
1569
1570 Raises
1571 ------
1572 ValueError
1573 If `cmp` is not valid.
1574 TypeError
1575 If at least one of `a1` or `a2` is a non-string array
1576
1577 Examples
1578 --------
1579 >>> import numpy as np
1580 >>> a = np.array(["a", "b", "cde"])
1581 >>> b = np.array(["a", "a", "dec"])
1582 >>> np.char.compare_chararrays(a, b, ">", True)
1583 array([False, True, False])
1584
1585 """)
1586
1587add_newdoc('numpy._core.multiarray', 'fromiter',
1588 """
1589 fromiter(iter, dtype, count=-1, *, like=None)
1590 --
1591
1592 fromiter(iter, dtype, count=-1, *, like=None)
1593
1594 Create a new 1-dimensional array from an iterable object.
1595
1596 Parameters
1597 ----------
1598 iter : iterable object
1599 An iterable object providing data for the array.
1600 dtype : data-type
1601 The data-type of the returned array.
1602
1603 .. versionchanged:: 1.23
1604 Object and subarray dtypes are now supported (note that the final
1605 result is not 1-D for a subarray dtype).
1606
1607 count : int, optional
1608 The number of items to read from *iterable*. The default is -1,
1609 which means all data is read.
1610 ${ARRAY_FUNCTION_LIKE}
1611
1612 .. versionadded:: 1.20.0
1613
1614 Returns
1615 -------
1616 out : ndarray
1617 The output array.
1618
1619 Notes
1620 -----
1621 Specify `count` to improve performance. It allows ``fromiter`` to
1622 pre-allocate the output array, instead of resizing it on demand.
1623
1624 Examples
1625 --------
1626 >>> import numpy as np
1627 >>> iterable = (x*x for x in range(5))
1628 >>> np.fromiter(iterable, float)
1629 array([ 0., 1., 4., 9., 16.])
1630
1631 A carefully constructed subarray dtype will lead to higher dimensional
1632 results:
1633
1634 >>> iterable = ((x+1, x+2) for x in range(5))
1635 >>> np.fromiter(iterable, dtype=np.dtype((int, 2)))
1636 array([[1, 2],
1637 [2, 3],
1638 [3, 4],
1639 [4, 5],
1640 [5, 6]])
1641
1642
1643 """)
1644
1645add_newdoc('numpy._core.multiarray', 'fromfile',
1646 """
1647 fromfile(file, dtype=None, count=-1, sep='', offset=0, *, like=None)
1648 --
1649
1650 fromfile(file, dtype=float, count=-1, sep='', offset=0, *, like=None)
1651
1652 Construct an array from data in a text or binary file.
1653
1654 A highly efficient way of reading binary data with a known data-type,
1655 as well as parsing simply formatted text files. Data written using the
1656 `tofile` method can be read using this function.
1657
1658 Parameters
1659 ----------
1660 file : file or str or Path
1661 An open file object, a string containing the filename, or a Path object.
1662 When reading from a file object it must support random access
1663 (i.e. it must have tell and seek methods).
1664 dtype : data-type
1665 Data type of the returned array.
1666 For binary files, it is used to determine the size and byte-order
1667 of the items in the file.
1668 Most builtin numeric types are supported and extension types may be supported.
1669 count : int
1670 Number of items to read. ``-1`` means all items (i.e., the complete
1671 file).
1672 sep : str
1673 Separator between items if file is a text file.
1674 Empty ("") separator means the file should be treated as binary.
1675 Spaces (" ") in the separator match zero or more whitespace characters.
1676 A separator consisting only of spaces must match at least one
1677 whitespace.
1678 offset : int
1679 The offset (in bytes) from the file's current position. Defaults to 0.
1680 Only permitted for binary files.
1681 ${ARRAY_FUNCTION_LIKE}
1682
1683 .. versionadded:: 1.20.0
1684
1685 See also
1686 --------
1687 load, save
1688 ndarray.tofile
1689 loadtxt : More flexible way of loading data from a text file.
1690
1691 Notes
1692 -----
1693 Do not rely on the combination of `tofile` and `fromfile` for
1694 data storage, as the binary files generated are not platform
1695 independent. In particular, no byte-order or data-type information is
1696 saved. Data can be stored in the platform independent ``.npy`` format
1697 using `save` and `load` instead.
1698
1699 Examples
1700 --------
1701 Construct an ndarray:
1702
1703 >>> import numpy as np
1704 >>> dt = np.dtype([('time', [('min', np.int64), ('sec', np.int64)]),
1705 ... ('temp', float)])
1706 >>> x = np.zeros((1,), dtype=dt)
1707 >>> x['time']['min'] = 10; x['temp'] = 98.25
1708 >>> x
1709 array([((10, 0), 98.25)],
1710 dtype=[('time', [('min', '<i8'), ('sec', '<i8')]), ('temp', '<f8')])
1711
1712 Save the raw data to disk:
1713
1714 >>> import tempfile
1715 >>> fname = tempfile.mkstemp()[1]
1716 >>> x.tofile(fname)
1717
1718 Read the raw data from disk:
1719
1720 >>> np.fromfile(fname, dtype=dt)
1721 array([((10, 0), 98.25)],
1722 dtype=[('time', [('min', '<i8'), ('sec', '<i8')]), ('temp', '<f8')])
1723
1724 The recommended way to store and load data:
1725
1726 >>> np.save(fname, x)
1727 >>> np.load(fname + '.npy')
1728 array([((10, 0), 98.25)],
1729 dtype=[('time', [('min', '<i8'), ('sec', '<i8')]), ('temp', '<f8')])
1730
1731 """)
1732
1733add_newdoc('numpy._core.multiarray', 'frombuffer',
1734 """
1735 frombuffer(buffer, dtype=None, count=-1, offset=0, *, like=None)
1736 --
1737
1738 frombuffer(buffer, dtype=float, count=-1, offset=0, *, like=None)
1739
1740 Interpret a buffer as a 1-dimensional array.
1741
1742 Parameters
1743 ----------
1744 buffer : buffer_like
1745 An object that exposes the buffer interface.
1746 dtype : data-type, optional
1747 Data-type of the returned array. Default is `numpy.float64`.
1748 count : int, optional
1749 Number of items to read. ``-1`` means all data in the buffer.
1750 offset : int, optional
1751 Start reading the buffer from this offset (in bytes); default: 0.
1752 ${ARRAY_FUNCTION_LIKE}
1753
1754 .. versionadded:: 1.20.0
1755
1756 Returns
1757 -------
1758 out : ndarray
1759
1760 See also
1761 --------
1762 ndarray.tobytes
1763 Inverse of this operation, construct Python bytes from the raw data
1764 bytes in the array.
1765
1766 Notes
1767 -----
1768 If the buffer has data that is not in machine byte-order, this should
1769 be specified as part of the data-type, e.g.::
1770
1771 >>> dt = np.dtype(int)
1772 >>> dt = dt.newbyteorder('>')
1773 >>> np.frombuffer(buf, dtype=dt) # doctest: +SKIP
1774
1775 The data of the resulting array will not be byteswapped, but will be
1776 interpreted correctly.
1777
1778 This function creates a view into the original object. This should be safe
1779 in general, but it may make sense to copy the result when the original
1780 object is mutable or untrusted.
1781
1782 Examples
1783 --------
1784 >>> import numpy as np
1785 >>> s = b'hello world'
1786 >>> np.frombuffer(s, dtype='S1', count=5, offset=6)
1787 array([b'w', b'o', b'r', b'l', b'd'], dtype='|S1')
1788
1789 >>> np.frombuffer(b'\\x01\\x02', dtype=np.uint8)
1790 array([1, 2], dtype=uint8)
1791 >>> np.frombuffer(b'\\x01\\x02\\x03\\x04\\x05', dtype=np.uint8, count=3)
1792 array([1, 2, 3], dtype=uint8)
1793
1794 """)
1795
1796add_newdoc('numpy._core.multiarray', 'from_dlpack',
1797 """
1798 from_dlpack(x, /, *, device=None, copy=None)
1799 --
1800
1801 from_dlpack(x, /, *, device=None, copy=None)
1802
1803 Create a NumPy array from an object implementing the ``__dlpack__``
1804 protocol. Generally, the returned NumPy array is a view of the input
1805 object. See [1]_ and [2]_ for more details.
1806
1807 Parameters
1808 ----------
1809 x : object
1810 A Python object that implements the ``__dlpack__`` and
1811 ``__dlpack_device__`` methods.
1812 device : device, optional
1813 Device on which to place the created array. Default: ``None``.
1814 Must be ``"cpu"`` if passed which may allow importing an array
1815 that is not already CPU available.
1816 copy : bool, optional
1817 Boolean indicating whether or not to copy the input. If ``True``,
1818 the copy will be made. If ``False``, the function will never copy,
1819 and will raise ``BufferError`` in case a copy is deemed necessary.
1820 Passing it requests a copy from the exporter who may or may not
1821 implement the capability.
1822 If ``None``, the function will reuse the existing memory buffer if
1823 possible and copy otherwise. Default: ``None``.
1824
1825
1826 Returns
1827 -------
1828 out : ndarray
1829
1830 References
1831 ----------
1832 .. [1] Array API documentation,
1833 https://data-apis.org/array-api/latest/design_topics/data_interchange.html#syntax-for-data-interchange-with-dlpack
1834
1835 .. [2] Python specification for DLPack,
1836 https://dmlc.github.io/dlpack/latest/python_spec.html
1837
1838 Examples
1839 --------
1840 >>> import torch # doctest: +SKIP
1841 >>> x = torch.arange(10) # doctest: +SKIP
1842 >>> # create a view of the torch tensor "x" in NumPy
1843 >>> y = np.from_dlpack(x) # doctest: +SKIP
1844 """)
1845
1846add_newdoc('numpy._core.multiarray', 'correlate',
1847 """cross_correlate(a,v, mode=0)""")
1848
1849add_newdoc('numpy._core.multiarray', 'arange',
1850 """
1851 arange(start_or_stop, /, stop=None, step=1, *, dtype=None, device=None, like=None)
1852 --
1853
1854 arange([start,] stop[, step,], dtype=None, *, device=None, like=None)
1855
1856 Return evenly spaced values within a given interval.
1857
1858 ``arange`` can be called with a varying number of positional arguments:
1859
1860 * ``arange(stop)``: Values are generated within the half-open interval
1861 ``[0, stop)`` (in other words, the interval including `start` but
1862 excluding `stop`).
1863 * ``arange(start, stop)``: Values are generated within the half-open
1864 interval ``[start, stop)``.
1865 * ``arange(start, stop, step)`` Values are generated within the half-open
1866 interval ``[start, stop)``, with spacing between values given by
1867 ``step``.
1868
1869 For integer arguments the function is roughly equivalent to the Python
1870 built-in :py:class:`range`, but returns an ndarray rather than a ``range``
1871 instance.
1872
1873 When using a non-integer step, such as 0.1, it is often better to use
1874 `numpy.linspace`.
1875
1876 See the Warning sections below for more information.
1877
1878 Parameters
1879 ----------
1880 start : integer or real, optional
1881 Start of interval. The interval includes this value. The default
1882 start value is 0.
1883 stop : integer or real
1884 End of interval. The interval does not include this value, except
1885 in some cases where `step` is not an integer and floating point
1886 round-off affects the length of `out`.
1887 step : integer or real, optional
1888 Spacing between values. For any output `out`, this is the distance
1889 between two adjacent values, ``out[i+1] - out[i]``. The default
1890 step size is 1. If `step` is specified as a position argument,
1891 `start` must also be given.
1892 dtype : dtype, optional
1893 The type of the output array. If `dtype` is not given, infer the data
1894 type from the other input arguments.
1895 device : str, optional
1896 The device on which to place the created array. Default: ``None``.
1897 For Array-API interoperability only, so must be ``"cpu"`` if passed.
1898
1899 .. versionadded:: 2.0.0
1900 ${ARRAY_FUNCTION_LIKE}
1901
1902 .. versionadded:: 1.20.0
1903
1904 Returns
1905 -------
1906 arange : ndarray
1907 Array of evenly spaced values.
1908
1909 For floating point arguments, the length of the result is
1910 ``ceil((stop - start)/step)``. Because of floating point overflow,
1911 this rule may result in the last element of `out` being greater
1912 than `stop`.
1913
1914 Warnings
1915 --------
1916 The length of the output might not be numerically stable.
1917
1918 Another stability issue is due to the internal implementation of
1919 `numpy.arange`.
1920 The actual step value used to populate the array is
1921 ``dtype(start + step) - dtype(start)`` and not `step`. Precision loss
1922 can occur here, due to casting or due to using floating points when
1923 `start` is much larger than `step`. This can lead to unexpected
1924 behaviour. For example::
1925
1926 >>> np.arange(0, 5, 0.5, dtype=int)
1927 array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
1928 >>> np.arange(-3, 3, 0.5, dtype=int)
1929 array([-3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8])
1930
1931 In such cases, the use of `numpy.linspace` should be preferred.
1932
1933 The built-in :py:class:`range` generates :std:doc:`Python built-in integers
1934 that have arbitrary size <python:c-api/long>`, while `numpy.arange`
1935 produces `numpy.int32` or `numpy.int64` numbers. This may result in
1936 incorrect results for large integer values::
1937
1938 >>> power = 40
1939 >>> modulo = 10000
1940 >>> x1 = [(n ** power) % modulo for n in range(8)]
1941 >>> x2 = [(n ** power) % modulo for n in np.arange(8)]
1942 >>> print(x1)
1943 [0, 1, 7776, 8801, 6176, 625, 6576, 4001] # correct
1944 >>> print(x2)
1945 [0, 1, 7776, 7185, 0, 5969, 4816, 3361] # incorrect
1946
1947 See Also
1948 --------
1949 numpy.linspace : Evenly spaced numbers with careful handling of endpoints.
1950 numpy.ogrid: Arrays of evenly spaced numbers in N-dimensions.
1951 numpy.mgrid: Grid-shaped arrays of evenly spaced numbers in N-dimensions.
1952 :ref:`how-to-partition`
1953
1954 Examples
1955 --------
1956 >>> import numpy as np
1957 >>> np.arange(3)
1958 array([0, 1, 2])
1959 >>> np.arange(3.0)
1960 array([ 0., 1., 2.])
1961 >>> np.arange(3,7)
1962 array([3, 4, 5, 6])
1963 >>> np.arange(3,7,2)
1964 array([3, 5])
1965
1966 """)
1967
1968add_newdoc('numpy._core.multiarray', '_get_ndarray_c_version',
1969 """_get_ndarray_c_version()
1970
1971 Return the compile time NPY_VERSION (formerly called NDARRAY_VERSION) number.
1972
1973 """)
1974
1975add_newdoc('numpy._core.multiarray', '_reconstruct',
1976 """_reconstruct(subtype, shape, dtype)
1977
1978 Construct an empty array. Used by Pickle.
1979
1980 """)
1981
1982add_newdoc('numpy._core.multiarray', 'promote_types',
1983 """
1984 promote_types(type1, type2, /)
1985 --
1986
1987 promote_types(type1, type2, /)
1988
1989 Returns the data type with the smallest size and smallest scalar
1990 kind to which both ``type1`` and ``type2`` may be safely cast.
1991 The returned data type is always considered "canonical", this mainly
1992 means that the promoted dtype will always be in native byte order.
1993
1994 This function is symmetric, but rarely associative.
1995
1996 Parameters
1997 ----------
1998 type1 : dtype or dtype specifier
1999 First data type.
2000 type2 : dtype or dtype specifier
2001 Second data type.
2002
2003 Returns
2004 -------
2005 out : dtype
2006 The promoted data type.
2007
2008 Notes
2009 -----
2010 Please see `numpy.result_type` for additional information about promotion.
2011
2012 Starting in NumPy 1.9, promote_types function now returns a valid string
2013 length when given an integer or float dtype as one argument and a string
2014 dtype as another argument. Previously it always returned the input string
2015 dtype, even if it wasn't long enough to store the max integer/float value
2016 converted to a string.
2017
2018 .. versionchanged:: 1.23.0
2019
2020 NumPy now supports promotion for more structured dtypes. It will now
2021 remove unnecessary padding from a structure dtype and promote included
2022 fields individually.
2023
2024 See Also
2025 --------
2026 result_type, dtype, can_cast
2027
2028 Examples
2029 --------
2030 >>> import numpy as np
2031 >>> np.promote_types('f4', 'f8')
2032 dtype('float64')
2033
2034 >>> np.promote_types('i8', 'f4')
2035 dtype('float64')
2036
2037 >>> np.promote_types('>i8', '<c8')
2038 dtype('complex128')
2039
2040 >>> np.promote_types('i4', 'S8')
2041 dtype('S11')
2042
2043 An example of a non-associative case:
2044
2045 >>> p = np.promote_types
2046 >>> p('S', p('i1', 'u1'))
2047 dtype('S6')
2048 >>> p(p('S', 'i1'), 'u1')
2049 dtype('S4')
2050
2051 """)
2052
2053add_newdoc('numpy._core.multiarray', 'c_einsum',
2054 """
2055 c_einsum(subscripts, *operands, out=None, dtype=None, order='K',
2056 casting='safe')
2057
2058 *This documentation shadows that of the native python implementation of the `einsum` function,
2059 except all references and examples related to the `optimize` argument (v 0.12.0) have been removed.*
2060
2061 Evaluates the Einstein summation convention on the operands.
2062
2063 Using the Einstein summation convention, many common multi-dimensional,
2064 linear algebraic array operations can be represented in a simple fashion.
2065 In *implicit* mode `einsum` computes these values.
2066
2067 In *explicit* mode, `einsum` provides further flexibility to compute
2068 other array operations that might not be considered classical Einstein
2069 summation operations, by disabling, or forcing summation over specified
2070 subscript labels.
2071
2072 See the notes and examples for clarification.
2073
2074 Parameters
2075 ----------
2076 subscripts : str
2077 Specifies the subscripts for summation as comma separated list of
2078 subscript labels. An implicit (classical Einstein summation)
2079 calculation is performed unless the explicit indicator '->' is
2080 included as well as subscript labels of the precise output form.
2081 operands : list of array_like
2082 These are the arrays for the operation.
2083 out : ndarray, optional
2084 If provided, the calculation is done into this array.
2085 dtype : {data-type, None}, optional
2086 If provided, forces the calculation to use the data type specified.
2087 Note that you may have to also give a more liberal `casting`
2088 parameter to allow the conversions. Default is None.
2089 order : {'C', 'F', 'A', 'K'}, optional
2090 Controls the memory layout of the output. 'C' means it should
2091 be C contiguous. 'F' means it should be Fortran contiguous,
2092 'A' means it should be 'F' if the inputs are all 'F', 'C' otherwise.
2093 'K' means it should be as close to the layout of the inputs as
2094 is possible, including arbitrarily permuted axes.
2095 Default is 'K'.
2096 casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional
2097 Controls what kind of data casting may occur. Setting this to
2098 'unsafe' is not recommended, as it can adversely affect accumulations.
2099
2100 * 'no' means the data types should not be cast at all.
2101 * 'equiv' means only byte-order changes are allowed.
2102 * 'safe' means only casts which can preserve values are allowed.
2103 * 'same_kind' means only safe casts or casts within a kind,
2104 like float64 to float32, are allowed.
2105 * 'unsafe' means any data conversions may be done.
2106
2107 Default is 'safe'.
2108 optimize : {False, True, 'greedy', 'optimal'}, optional
2109 Controls if intermediate optimization should occur. No optimization
2110 will occur if False and True will default to the 'greedy' algorithm.
2111 Also accepts an explicit contraction list from the ``np.einsum_path``
2112 function. See ``np.einsum_path`` for more details. Defaults to False.
2113
2114 Returns
2115 -------
2116 output : ndarray
2117 The calculation based on the Einstein summation convention.
2118
2119 See Also
2120 --------
2121 einsum_path, dot, inner, outer, tensordot, linalg.multi_dot
2122
2123 Notes
2124 -----
2125 The Einstein summation convention can be used to compute
2126 many multi-dimensional, linear algebraic array operations. `einsum`
2127 provides a succinct way of representing these.
2128
2129 A non-exhaustive list of these operations,
2130 which can be computed by `einsum`, is shown below along with examples:
2131
2132 * Trace of an array, :py:func:`numpy.trace`.
2133 * Return a diagonal, :py:func:`numpy.diag`.
2134 * Array axis summations, :py:func:`numpy.sum`.
2135 * Transpositions and permutations, :py:func:`numpy.transpose`.
2136 * Matrix multiplication and dot product, :py:func:`numpy.matmul` :py:func:`numpy.dot`.
2137 * Vector inner and outer products, :py:func:`numpy.inner` :py:func:`numpy.outer`.
2138 * Broadcasting, element-wise and scalar multiplication, :py:func:`numpy.multiply`.
2139 * Tensor contractions, :py:func:`numpy.tensordot`.
2140 * Chained array operations, in efficient calculation order, :py:func:`numpy.einsum_path`.
2141
2142 The subscripts string is a comma-separated list of subscript labels,
2143 where each label refers to a dimension of the corresponding operand.
2144 Whenever a label is repeated it is summed, so ``np.einsum('i,i', a, b)``
2145 is equivalent to :py:func:`np.inner(a,b) <numpy.inner>`. If a label
2146 appears only once, it is not summed, so ``np.einsum('i', a)`` produces a
2147 view of ``a`` with no changes. A further example ``np.einsum('ij,jk', a, b)``
2148 describes traditional matrix multiplication and is equivalent to
2149 :py:func:`np.matmul(a,b) <numpy.matmul>`. Repeated subscript labels in one
2150 operand take the diagonal. For example, ``np.einsum('ii', a)`` is equivalent
2151 to :py:func:`np.trace(a) <numpy.trace>`.
2152
2153 In *implicit mode*, the chosen subscripts are important
2154 since the axes of the output are reordered alphabetically. This
2155 means that ``np.einsum('ij', a)`` doesn't affect a 2D array, while
2156 ``np.einsum('ji', a)`` takes its transpose. Additionally,
2157 ``np.einsum('ij,jk', a, b)`` returns a matrix multiplication, while,
2158 ``np.einsum('ij,jh', a, b)`` returns the transpose of the
2159 multiplication since subscript 'h' precedes subscript 'i'.
2160
2161 In *explicit mode* the output can be directly controlled by
2162 specifying output subscript labels. This requires the
2163 identifier '->' as well as the list of output subscript labels.
2164 This feature increases the flexibility of the function since
2165 summing can be disabled or forced when required. The call
2166 ``np.einsum('i->', a)`` is like :py:func:`np.sum(a) <numpy.sum>`
2167 if ``a`` is a 1-D array, and ``np.einsum('ii->i', a)``
2168 is like :py:func:`np.diag(a) <numpy.diag>` if ``a`` is a square 2-D array.
2169 The difference is that `einsum` does not allow broadcasting by default.
2170 Additionally ``np.einsum('ij,jh->ih', a, b)`` directly specifies the
2171 order of the output subscript labels and therefore returns matrix
2172 multiplication, unlike the example above in implicit mode.
2173
2174 To enable and control broadcasting, use an ellipsis. Default
2175 NumPy-style broadcasting is done by adding an ellipsis
2176 to the left of each term, like ``np.einsum('...ii->...i', a)``.
2177 ``np.einsum('...i->...', a)`` is like
2178 :py:func:`np.sum(a, axis=-1) <numpy.sum>` for array ``a`` of any shape.
2179 To take the trace along the first and last axes,
2180 you can do ``np.einsum('i...i', a)``, or to do a matrix-matrix
2181 product with the left-most indices instead of rightmost, one can do
2182 ``np.einsum('ij...,jk...->ik...', a, b)``.
2183
2184 When there is only one operand, no axes are summed, and no output
2185 parameter is provided, a view into the operand is returned instead
2186 of a new array. Thus, taking the diagonal as ``np.einsum('ii->i', a)``
2187 produces a view (changed in version 1.10.0).
2188
2189 `einsum` also provides an alternative way to provide the subscripts
2190 and operands as ``einsum(op0, sublist0, op1, sublist1, ..., [sublistout])``.
2191 If the output shape is not provided in this format `einsum` will be
2192 calculated in implicit mode, otherwise it will be performed explicitly.
2193 The examples below have corresponding `einsum` calls with the two
2194 parameter methods.
2195
2196 Views returned from einsum are now writeable whenever the input array
2197 is writeable. For example, ``np.einsum('ijk...->kji...', a)`` will now
2198 have the same effect as :py:func:`np.swapaxes(a, 0, 2) <numpy.swapaxes>`
2199 and ``np.einsum('ii->i', a)`` will return a writeable view of the diagonal
2200 of a 2D array.
2201
2202 Examples
2203 --------
2204 >>> import numpy as np
2205 >>> a = np.arange(25).reshape(5,5)
2206 >>> b = np.arange(5)
2207 >>> c = np.arange(6).reshape(2,3)
2208
2209 Trace of a matrix:
2210
2211 >>> np.einsum('ii', a)
2212 60
2213 >>> np.einsum(a, [0,0])
2214 60
2215 >>> np.trace(a)
2216 60
2217
2218 Extract the diagonal (requires explicit form):
2219
2220 >>> np.einsum('ii->i', a)
2221 array([ 0, 6, 12, 18, 24])
2222 >>> np.einsum(a, [0,0], [0])
2223 array([ 0, 6, 12, 18, 24])
2224 >>> np.diag(a)
2225 array([ 0, 6, 12, 18, 24])
2226
2227 Sum over an axis (requires explicit form):
2228
2229 >>> np.einsum('ij->i', a)
2230 array([ 10, 35, 60, 85, 110])
2231 >>> np.einsum(a, [0,1], [0])
2232 array([ 10, 35, 60, 85, 110])
2233 >>> np.sum(a, axis=1)
2234 array([ 10, 35, 60, 85, 110])
2235
2236 For higher dimensional arrays summing a single axis can be done with ellipsis:
2237
2238 >>> np.einsum('...j->...', a)
2239 array([ 10, 35, 60, 85, 110])
2240 >>> np.einsum(a, [Ellipsis,1], [Ellipsis])
2241 array([ 10, 35, 60, 85, 110])
2242
2243 Compute a matrix transpose, or reorder any number of axes:
2244
2245 >>> np.einsum('ji', c)
2246 array([[0, 3],
2247 [1, 4],
2248 [2, 5]])
2249 >>> np.einsum('ij->ji', c)
2250 array([[0, 3],
2251 [1, 4],
2252 [2, 5]])
2253 >>> np.einsum(c, [1,0])
2254 array([[0, 3],
2255 [1, 4],
2256 [2, 5]])
2257 >>> np.transpose(c)
2258 array([[0, 3],
2259 [1, 4],
2260 [2, 5]])
2261
2262 Vector inner products:
2263
2264 >>> np.einsum('i,i', b, b)
2265 30
2266 >>> np.einsum(b, [0], b, [0])
2267 30
2268 >>> np.inner(b,b)
2269 30
2270
2271 Matrix vector multiplication:
2272
2273 >>> np.einsum('ij,j', a, b)
2274 array([ 30, 80, 130, 180, 230])
2275 >>> np.einsum(a, [0,1], b, [1])
2276 array([ 30, 80, 130, 180, 230])
2277 >>> np.dot(a, b)
2278 array([ 30, 80, 130, 180, 230])
2279 >>> np.einsum('...j,j', a, b)
2280 array([ 30, 80, 130, 180, 230])
2281
2282 Broadcasting and scalar multiplication:
2283
2284 >>> np.einsum('..., ...', 3, c)
2285 array([[ 0, 3, 6],
2286 [ 9, 12, 15]])
2287 >>> np.einsum(',ij', 3, c)
2288 array([[ 0, 3, 6],
2289 [ 9, 12, 15]])
2290 >>> np.einsum(3, [Ellipsis], c, [Ellipsis])
2291 array([[ 0, 3, 6],
2292 [ 9, 12, 15]])
2293 >>> np.multiply(3, c)
2294 array([[ 0, 3, 6],
2295 [ 9, 12, 15]])
2296
2297 Vector outer product:
2298
2299 >>> np.einsum('i,j', np.arange(2)+1, b)
2300 array([[0, 1, 2, 3, 4],
2301 [0, 2, 4, 6, 8]])
2302 >>> np.einsum(np.arange(2)+1, [0], b, [1])
2303 array([[0, 1, 2, 3, 4],
2304 [0, 2, 4, 6, 8]])
2305 >>> np.outer(np.arange(2)+1, b)
2306 array([[0, 1, 2, 3, 4],
2307 [0, 2, 4, 6, 8]])
2308
2309 Tensor contraction:
2310
2311 >>> a = np.arange(60.).reshape(3,4,5)
2312 >>> b = np.arange(24.).reshape(4,3,2)
2313 >>> np.einsum('ijk,jil->kl', a, b)
2314 array([[ 4400., 4730.],
2315 [ 4532., 4874.],
2316 [ 4664., 5018.],
2317 [ 4796., 5162.],
2318 [ 4928., 5306.]])
2319 >>> np.einsum(a, [0,1,2], b, [1,0,3], [2,3])
2320 array([[ 4400., 4730.],
2321 [ 4532., 4874.],
2322 [ 4664., 5018.],
2323 [ 4796., 5162.],
2324 [ 4928., 5306.]])
2325 >>> np.tensordot(a,b, axes=([1,0],[0,1]))
2326 array([[ 4400., 4730.],
2327 [ 4532., 4874.],
2328 [ 4664., 5018.],
2329 [ 4796., 5162.],
2330 [ 4928., 5306.]])
2331
2332 Writeable returned arrays (since version 1.10.0):
2333
2334 >>> a = np.zeros((3, 3))
2335 >>> np.einsum('ii->i', a)[:] = 1
2336 >>> a
2337 array([[ 1., 0., 0.],
2338 [ 0., 1., 0.],
2339 [ 0., 0., 1.]])
2340
2341 Example of ellipsis use:
2342
2343 >>> a = np.arange(6).reshape((3,2))
2344 >>> b = np.arange(12).reshape((4,3))
2345 >>> np.einsum('ki,jk->ij', a, b)
2346 array([[10, 28, 46, 64],
2347 [13, 40, 67, 94]])
2348 >>> np.einsum('ki,...k->i...', a, b)
2349 array([[10, 28, 46, 64],
2350 [13, 40, 67, 94]])
2351 >>> np.einsum('k...,jk', a, b)
2352 array([[10, 28, 46, 64],
2353 [13, 40, 67, 94]])
2354
2355 """)
2356
2357
2358##############################################################################
2359#
2360# Documentation for ndarray attributes and methods
2361#
2362##############################################################################
2363
2364
2365##############################################################################
2366#
2367# ndarray object
2368#
2369##############################################################################
2370
2371
2372add_newdoc('numpy._core.multiarray', 'ndarray',
2373 """
2374 ndarray(shape, dtype=None, buffer=None, offset=0, strides=None, order=None)
2375 --
2376
2377 ndarray(shape, dtype=float, buffer=None, offset=0, strides=None, order=None)
2378
2379 An array object represents a multidimensional, homogeneous array
2380 of fixed-size items. An associated data-type object describes the
2381 format of each element in the array (its byte-order, how many bytes it
2382 occupies in memory, whether it is an integer, a floating point number,
2383 or something else, etc.)
2384
2385 Arrays should be constructed using `array`, `zeros` or `empty` (refer
2386 to the See Also section below). The parameters given here refer to
2387 a low-level method (`ndarray(...)`) for instantiating an array.
2388
2389 For more information, refer to the `numpy` module and examine the
2390 methods and attributes of an array.
2391
2392 Parameters
2393 ----------
2394 (for the __new__ method; see Notes below)
2395
2396 shape : tuple of ints
2397 Shape of created array.
2398 dtype : data-type, optional
2399 Any object that can be interpreted as a numpy data type.
2400 Default is `numpy.float64`.
2401 buffer : object exposing buffer interface, optional
2402 Used to fill the array with data.
2403 offset : int, optional
2404 Offset of array data in buffer.
2405 strides : tuple of ints, optional
2406 Strides of data in memory.
2407 order : {'C', 'F'}, optional
2408 Row-major (C-style) or column-major (Fortran-style) order.
2409
2410 Attributes
2411 ----------
2412 T : ndarray
2413 Transpose of the array.
2414 data : buffer
2415 The array's elements, in memory.
2416 dtype : dtype object
2417 Describes the format of the elements in the array.
2418 flags : dict
2419 Dictionary containing information related to memory use, e.g.,
2420 'C_CONTIGUOUS', 'OWNDATA', 'WRITEABLE', etc.
2421 flat : numpy.flatiter object
2422 Flattened version of the array as an iterator. The iterator
2423 allows assignments, e.g., ``x.flat = 3`` (See `ndarray.flat` for
2424 assignment examples; TODO).
2425 imag : ndarray
2426 Imaginary part of the array.
2427 real : ndarray
2428 Real part of the array.
2429 size : int
2430 Number of elements in the array.
2431 itemsize : int
2432 The memory use of each array element in bytes.
2433 nbytes : int
2434 The total number of bytes required to store the array data,
2435 i.e., ``itemsize * size``.
2436 ndim : int
2437 The array's number of dimensions.
2438 shape : tuple of ints
2439 Shape of the array.
2440 strides : tuple of ints
2441 The step-size required to move from one element to the next in
2442 memory. For example, a contiguous ``(3, 4)`` array of type
2443 ``int16`` in C-order has strides ``(8, 2)``. This implies that
2444 to move from element to element in memory requires jumps of 2 bytes.
2445 To move from row-to-row, one needs to jump 8 bytes at a time
2446 (``2 * 4``).
2447 ctypes : ctypes object
2448 Class containing properties of the array needed for interaction
2449 with ctypes.
2450 base : ndarray
2451 If the array is a view into another array, that array is its `base`
2452 (unless that array is also a view). The `base` array is where the
2453 array data is actually stored.
2454
2455 See Also
2456 --------
2457 array : Construct an array.
2458 zeros : Create an array, each element of which is zero.
2459 empty : Create an array, but leave its allocated memory unchanged (i.e.,
2460 it contains "garbage").
2461 dtype : Create a data-type.
2462 numpy.typing.NDArray : An ndarray alias :term:`generic <generic type>`
2463 w.r.t. its `dtype.type <numpy.dtype.type>`.
2464
2465 Notes
2466 -----
2467 There are two modes of creating an array using ``__new__``:
2468
2469 1. If `buffer` is None, then only `shape`, `dtype`, and `order`
2470 are used.
2471 2. If `buffer` is an object exposing the buffer interface, then
2472 all keywords are interpreted.
2473
2474 No ``__init__`` method is needed because the array is fully initialized
2475 after the ``__new__`` method.
2476
2477 Examples
2478 --------
2479 These examples illustrate the low-level `ndarray` constructor. Refer
2480 to the `See Also` section above for easier ways of constructing an
2481 ndarray.
2482
2483 First mode, `buffer` is None:
2484
2485 >>> import numpy as np
2486 >>> np.ndarray(shape=(2,2), dtype=float, order='F')
2487 array([[0.0e+000, 0.0e+000], # random
2488 [ nan, 2.5e-323]])
2489
2490 Second mode:
2491
2492 >>> np.ndarray((2,), buffer=np.array([1,2,3]),
2493 ... offset=np.int_().itemsize,
2494 ... dtype=int) # offset = 1*itemsize, i.e. skip first element
2495 array([2, 3])
2496
2497 """)
2498
2499
2500##############################################################################
2501#
2502# ndarray attributes
2503#
2504##############################################################################
2505
2506
2507add_newdoc('numpy._core.multiarray', 'ndarray', ('__array_interface__',
2508 """Array protocol: Python side."""))
2509
2510
2511add_newdoc('numpy._core.multiarray', 'ndarray', ('__array_priority__',
2512 """Array priority."""))
2513
2514
2515add_newdoc('numpy._core.multiarray', 'ndarray', ('__array_struct__',
2516 """Array protocol: C-struct side."""))
2517
2518
2519add_newdoc('numpy._core.multiarray', 'ndarray', ('base',
2520 """
2521 Base object if memory is from some other object.
2522
2523 Examples
2524 --------
2525 The base of an array that owns its memory is None:
2526
2527 >>> import numpy as np
2528 >>> x = np.array([1,2,3,4])
2529 >>> x.base is None
2530 True
2531
2532 Slicing creates a view, whose memory is shared with x:
2533
2534 >>> y = x[2:]
2535 >>> y.base is x
2536 True
2537
2538 """))
2539
2540
2541add_newdoc('numpy._core.multiarray', 'ndarray', ('ctypes',
2542 """
2543 An object to simplify the interaction of the array with the ctypes
2544 module.
2545
2546 This attribute creates an object that makes it easier to use arrays
2547 when calling shared libraries with the ctypes module. The returned
2548 object has, among others, data, shape, and strides attributes (see
2549 Notes below) which themselves return ctypes objects that can be used
2550 as arguments to a shared library.
2551
2552 Parameters
2553 ----------
2554 None
2555
2556 Returns
2557 -------
2558 c : Python object
2559 Possessing attributes data, shape, strides, etc.
2560
2561 See Also
2562 --------
2563 numpy.ctypeslib
2564
2565 Notes
2566 -----
2567 Below are the public attributes of this object which were documented
2568 in "Guide to NumPy" (we have omitted undocumented public attributes,
2569 as well as documented private attributes):
2570
2571 .. autoattribute:: numpy._core._internal._ctypes.data
2572 :noindex:
2573
2574 .. autoattribute:: numpy._core._internal._ctypes.shape
2575 :noindex:
2576
2577 .. autoattribute:: numpy._core._internal._ctypes.strides
2578 :noindex:
2579
2580 .. automethod:: numpy._core._internal._ctypes.data_as
2581 :noindex:
2582
2583 .. automethod:: numpy._core._internal._ctypes.shape_as
2584 :noindex:
2585
2586 .. automethod:: numpy._core._internal._ctypes.strides_as
2587 :noindex:
2588
2589 If the ctypes module is not available, then the ctypes attribute
2590 of array objects still returns something useful, but ctypes objects
2591 are not returned and errors may be raised instead. In particular,
2592 the object will still have the ``as_parameter`` attribute which will
2593 return an integer equal to the data attribute.
2594
2595 Examples
2596 --------
2597 >>> import numpy as np
2598 >>> import ctypes
2599 >>> x = np.array([[0, 1], [2, 3]], dtype=np.int32)
2600 >>> x
2601 array([[0, 1],
2602 [2, 3]], dtype=int32)
2603 >>> x.ctypes.data
2604 31962608 # may vary
2605 >>> x.ctypes.data_as(ctypes.POINTER(ctypes.c_uint32))
2606 <__main__.LP_c_uint object at 0x7ff2fc1fc200> # may vary
2607 >>> x.ctypes.data_as(ctypes.POINTER(ctypes.c_uint32)).contents
2608 c_uint(0)
2609 >>> x.ctypes.data_as(ctypes.POINTER(ctypes.c_uint64)).contents
2610 c_ulong(4294967296)
2611 >>> x.ctypes.shape
2612 <numpy._core._internal.c_long_Array_2 object at 0x7ff2fc1fce60> # may vary
2613 >>> x.ctypes.strides
2614 <numpy._core._internal.c_long_Array_2 object at 0x7ff2fc1ff320> # may vary
2615
2616 """))
2617
2618
2619add_newdoc('numpy._core.multiarray', 'ndarray', ('data',
2620 """Python buffer object pointing to the start of the array's data."""))
2621
2622
2623add_newdoc('numpy._core.multiarray', 'ndarray', ('dtype',
2624 """
2625 Data-type of the array's elements.
2626
2627 .. warning::
2628
2629 Setting ``arr.dtype`` is discouraged and may be deprecated in the
2630 future. Setting will replace the ``dtype`` without modifying the
2631 memory (see also `ndarray.view` and `ndarray.astype`).
2632
2633 Parameters
2634 ----------
2635 None
2636
2637 Returns
2638 -------
2639 d : numpy dtype object
2640
2641 See Also
2642 --------
2643 ndarray.astype : Cast the values contained in the array to a new data-type.
2644 ndarray.view : Create a view of the same data but a different data-type.
2645 numpy.dtype
2646
2647 Examples
2648 --------
2649 >>> import numpy as np
2650 >>> x = np.arange(4).reshape((2, 2))
2651 >>> x
2652 array([[0, 1],
2653 [2, 3]])
2654 >>> x.dtype
2655 dtype('int64') # may vary (OS, bitness)
2656 >>> isinstance(x.dtype, np.dtype)
2657 True
2658
2659 """))
2660
2661
2662add_newdoc('numpy._core.multiarray', 'ndarray', ('imag',
2663 """
2664 The imaginary part of the array.
2665
2666 Examples
2667 --------
2668 >>> import numpy as np
2669 >>> x = np.sqrt([1+0j, 0+1j])
2670 >>> x.imag
2671 array([ 0. , 0.70710678])
2672 >>> x.imag.dtype
2673 dtype('float64')
2674
2675 """))
2676
2677
2678add_newdoc('numpy._core.multiarray', 'ndarray', ('itemsize',
2679 """
2680 Length of one array element in bytes.
2681
2682 Examples
2683 --------
2684 >>> import numpy as np
2685 >>> x = np.array([1,2,3], dtype=np.float64)
2686 >>> x.itemsize
2687 8
2688 >>> x = np.array([1,2,3], dtype=np.complex128)
2689 >>> x.itemsize
2690 16
2691
2692 """))
2693
2694
2695add_newdoc('numpy._core.multiarray', 'ndarray', ('flags',
2696 """
2697 Information about the memory layout of the array.
2698
2699 Attributes
2700 ----------
2701 C_CONTIGUOUS (C)
2702 The data is in a single, C-style contiguous segment.
2703 F_CONTIGUOUS (F)
2704 The data is in a single, Fortran-style contiguous segment.
2705 OWNDATA (O)
2706 The array owns the memory it uses or borrows it from another object.
2707 WRITEABLE (W)
2708 The data area can be written to. Setting this to False locks
2709 the data, making it read-only. A view (slice, etc.) inherits WRITEABLE
2710 from its base array at creation time, but a view of a writeable
2711 array may be subsequently locked while the base array remains writeable.
2712 (The opposite is not true, in that a view of a locked array may not
2713 be made writeable. However, currently, locking a base object does not
2714 lock any views that already reference it, so under that circumstance it
2715 is possible to alter the contents of a locked array via a previously
2716 created writeable view onto it.) Attempting to change a non-writeable
2717 array raises a RuntimeError exception.
2718 ALIGNED (A)
2719 The data and all elements are aligned appropriately for the hardware.
2720 WRITEBACKIFCOPY (X)
2721 This array is a copy of some other array. The C-API function
2722 PyArray_ResolveWritebackIfCopy must be called before deallocating
2723 to the base array will be updated with the contents of this array.
2724 FNC
2725 F_CONTIGUOUS and not C_CONTIGUOUS.
2726 FORC
2727 F_CONTIGUOUS or C_CONTIGUOUS (one-segment test).
2728 BEHAVED (B)
2729 ALIGNED and WRITEABLE.
2730 CARRAY (CA)
2731 BEHAVED and C_CONTIGUOUS.
2732 FARRAY (FA)
2733 BEHAVED and F_CONTIGUOUS and not C_CONTIGUOUS.
2734
2735 Notes
2736 -----
2737 The `flags` object can be accessed dictionary-like (as in ``a.flags['WRITEABLE']``),
2738 or by using lowercased attribute names (as in ``a.flags.writeable``). Short flag
2739 names are only supported in dictionary access.
2740
2741 Only the WRITEBACKIFCOPY, WRITEABLE, and ALIGNED flags can be
2742 changed by the user, via direct assignment to the attribute or dictionary
2743 entry, or by calling `ndarray.setflags`.
2744
2745 The array flags cannot be set arbitrarily:
2746
2747 - WRITEBACKIFCOPY can only be set ``False``.
2748 - ALIGNED can only be set ``True`` if the data is truly aligned.
2749 - WRITEABLE can only be set ``True`` if the array owns its own memory
2750 or the ultimate owner of the memory exposes a writeable buffer
2751 interface or is a string.
2752
2753 Arrays can be both C-style and Fortran-style contiguous simultaneously.
2754 This is clear for 1-dimensional arrays, but can also be true for higher
2755 dimensional arrays.
2756
2757 Even for contiguous arrays a stride for a given dimension
2758 ``arr.strides[dim]`` may be *arbitrary* if ``arr.shape[dim] == 1``
2759 or the array has no elements.
2760 It does *not* generally hold that ``self.strides[-1] == self.itemsize``
2761 for C-style contiguous arrays or ``self.strides[0] == self.itemsize`` for
2762 Fortran-style contiguous arrays is true.
2763 """))
2764
2765
2766add_newdoc('numpy._core.multiarray', 'ndarray', ('flat',
2767 """
2768 A 1-D iterator over the array.
2769
2770 This is a `numpy.flatiter` instance, which acts similarly to, but is not
2771 a subclass of, Python's built-in iterator object.
2772
2773 See Also
2774 --------
2775 flatten : Return a copy of the array collapsed into one dimension.
2776
2777 flatiter
2778
2779 Examples
2780 --------
2781 >>> import numpy as np
2782 >>> x = np.arange(1, 7).reshape(2, 3)
2783 >>> x
2784 array([[1, 2, 3],
2785 [4, 5, 6]])
2786 >>> x.flat[3]
2787 4
2788 >>> x.T
2789 array([[1, 4],
2790 [2, 5],
2791 [3, 6]])
2792 >>> x.T.flat[3]
2793 5
2794 >>> type(x.flat)
2795 <class 'numpy.flatiter'>
2796
2797 An assignment example:
2798
2799 >>> x.flat = 3; x
2800 array([[3, 3, 3],
2801 [3, 3, 3]])
2802 >>> x.flat[[1,4]] = 1; x
2803 array([[3, 1, 3],
2804 [3, 1, 3]])
2805
2806 """))
2807
2808
2809add_newdoc('numpy._core.multiarray', 'ndarray', ('nbytes',
2810 """
2811 Total bytes consumed by the elements of the array.
2812
2813 Notes
2814 -----
2815 Does not include memory consumed by non-element attributes of the
2816 array object.
2817
2818 See Also
2819 --------
2820 sys.getsizeof
2821 Memory consumed by the object itself without parents in case view.
2822 This does include memory consumed by non-element attributes.
2823
2824 Examples
2825 --------
2826 >>> import numpy as np
2827 >>> x = np.zeros((3,5,2), dtype=np.complex128)
2828 >>> x.nbytes
2829 480
2830 >>> np.prod(x.shape) * x.itemsize
2831 480
2832
2833 """))
2834
2835
2836add_newdoc('numpy._core.multiarray', 'ndarray', ('ndim',
2837 """
2838 Number of array dimensions.
2839
2840 Examples
2841 --------
2842 >>> import numpy as np
2843 >>> x = np.array([1, 2, 3])
2844 >>> x.ndim
2845 1
2846 >>> y = np.zeros((2, 3, 4))
2847 >>> y.ndim
2848 3
2849
2850 """))
2851
2852
2853add_newdoc('numpy._core.multiarray', 'ndarray', ('real',
2854 """
2855 The real part of the array.
2856
2857 Examples
2858 --------
2859 >>> import numpy as np
2860 >>> x = np.sqrt([1+0j, 0+1j])
2861 >>> x.real
2862 array([ 1. , 0.70710678])
2863 >>> x.real.dtype
2864 dtype('float64')
2865
2866 See Also
2867 --------
2868 numpy.real : equivalent function
2869
2870 """))
2871
2872
2873add_newdoc('numpy._core.multiarray', 'ndarray', ('shape',
2874 """
2875 Tuple of array dimensions.
2876
2877 The shape property is usually used to get the current shape of an array,
2878 but may also be used to reshape the array in-place by assigning a tuple of
2879 array dimensions to it. As with `numpy.reshape`, one of the new shape
2880 dimensions can be -1, in which case its value is inferred from the size of
2881 the array and the remaining dimensions. Reshaping an array in-place will
2882 fail if a copy is required.
2883
2884 .. warning::
2885
2886 Setting ``arr.shape`` is discouraged and may be deprecated in the
2887 future. Using `ndarray.reshape` is the preferred approach.
2888
2889 Examples
2890 --------
2891 >>> import numpy as np
2892 >>> x = np.array([1, 2, 3, 4])
2893 >>> x.shape
2894 (4,)
2895 >>> y = np.zeros((2, 3, 4))
2896 >>> y.shape
2897 (2, 3, 4)
2898 >>> y.shape = (3, 8)
2899 >>> y
2900 array([[ 0., 0., 0., 0., 0., 0., 0., 0.],
2901 [ 0., 0., 0., 0., 0., 0., 0., 0.],
2902 [ 0., 0., 0., 0., 0., 0., 0., 0.]])
2903 >>> y.shape = (3, 6)
2904 Traceback (most recent call last):
2905 File "<stdin>", line 1, in <module>
2906 ValueError: cannot reshape array of size 24 into shape (3,6)
2907 >>> np.zeros((4,2))[::2].shape = (-1,)
2908 Traceback (most recent call last):
2909 File "<stdin>", line 1, in <module>
2910 AttributeError: Incompatible shape for in-place modification. Use
2911 `.reshape()` to make a copy with the desired shape.
2912
2913 See Also
2914 --------
2915 numpy.shape : Equivalent getter function.
2916 numpy.reshape : Function similar to setting ``shape``.
2917 ndarray.reshape : Method similar to setting ``shape``.
2918
2919 """))
2920
2921
2922add_newdoc('numpy._core.multiarray', 'ndarray', ('size',
2923 """
2924 Number of elements in the array.
2925
2926 Equal to ``np.prod(a.shape)``, i.e., the product of the array's
2927 dimensions.
2928
2929 Notes
2930 -----
2931 `a.size` returns a standard arbitrary precision Python integer. This
2932 may not be the case with other methods of obtaining the same value
2933 (like the suggested ``np.prod(a.shape)``, which returns an instance
2934 of ``np.int_``), and may be relevant if the value is used further in
2935 calculations that may overflow a fixed size integer type.
2936
2937 Examples
2938 --------
2939 >>> import numpy as np
2940 >>> x = np.zeros((3, 5, 2), dtype=np.complex128)
2941 >>> x.size
2942 30
2943 >>> np.prod(x.shape)
2944 30
2945
2946 """))
2947
2948
2949add_newdoc('numpy._core.multiarray', 'ndarray', ('strides',
2950 """
2951 Tuple of bytes to step in each dimension when traversing an array.
2952
2953 The byte offset of element ``(i[0], i[1], ..., i[n])`` in an array `a`
2954 is::
2955
2956 offset = sum(np.array(i) * a.strides)
2957
2958 A more detailed explanation of strides can be found in
2959 :ref:`arrays.ndarray`.
2960
2961 .. warning::
2962
2963 Setting ``arr.strides`` is discouraged and may be deprecated in the
2964 future. `numpy.lib.stride_tricks.as_strided` should be preferred
2965 to create a new view of the same data in a safer way.
2966
2967 Notes
2968 -----
2969 Imagine an array of 32-bit integers (each 4 bytes)::
2970
2971 x = np.array([[0, 1, 2, 3, 4],
2972 [5, 6, 7, 8, 9]], dtype=np.int32)
2973
2974 This array is stored in memory as 40 bytes, one after the other
2975 (known as a contiguous block of memory). The strides of an array tell
2976 us how many bytes we have to skip in memory to move to the next position
2977 along a certain axis. For example, we have to skip 4 bytes (1 value) to
2978 move to the next column, but 20 bytes (5 values) to get to the same
2979 position in the next row. As such, the strides for the array `x` will be
2980 ``(20, 4)``.
2981
2982 See Also
2983 --------
2984 numpy.lib.stride_tricks.as_strided
2985
2986 Examples
2987 --------
2988 >>> import numpy as np
2989 >>> y = np.reshape(np.arange(2 * 3 * 4, dtype=np.int32), (2, 3, 4))
2990 >>> y
2991 array([[[ 0, 1, 2, 3],
2992 [ 4, 5, 6, 7],
2993 [ 8, 9, 10, 11]],
2994 [[12, 13, 14, 15],
2995 [16, 17, 18, 19],
2996 [20, 21, 22, 23]]], dtype=np.int32)
2997 >>> y.strides
2998 (48, 16, 4)
2999 >>> y[1, 1, 1]
3000 np.int32(17)
3001 >>> offset = sum(y.strides * np.array((1, 1, 1)))
3002 >>> offset // y.itemsize
3003 np.int64(17)
3004
3005 >>> x = np.reshape(np.arange(5*6*7*8, dtype=np.int32), (5, 6, 7, 8))
3006 >>> x = x.transpose(2, 3, 1, 0)
3007 >>> x.strides
3008 (32, 4, 224, 1344)
3009 >>> i = np.array([3, 5, 2, 2], dtype=np.int32)
3010 >>> offset = sum(i * x.strides)
3011 >>> x[3, 5, 2, 2]
3012 np.int32(813)
3013 >>> offset // x.itemsize
3014 np.int64(813)
3015
3016 """))
3017
3018
3019add_newdoc('numpy._core.multiarray', 'ndarray', ('T',
3020 """
3021 View of the transposed array.
3022
3023 Same as ``self.transpose()``.
3024
3025 Examples
3026 --------
3027 >>> import numpy as np
3028 >>> a = np.array([[1, 2], [3, 4]])
3029 >>> a
3030 array([[1, 2],
3031 [3, 4]])
3032 >>> a.T
3033 array([[1, 3],
3034 [2, 4]])
3035
3036 >>> a = np.array([1, 2, 3, 4])
3037 >>> a
3038 array([1, 2, 3, 4])
3039 >>> a.T
3040 array([1, 2, 3, 4])
3041
3042 See Also
3043 --------
3044 transpose
3045
3046 """))
3047
3048
3049add_newdoc('numpy._core.multiarray', 'ndarray', ('mT',
3050 """
3051 View of the matrix transposed array.
3052
3053 The matrix transpose is the transpose of the last two dimensions, even
3054 if the array is of higher dimension.
3055
3056 .. versionadded:: 2.0
3057
3058 Raises
3059 ------
3060 ValueError
3061 If the array is of dimension less than 2.
3062
3063 Examples
3064 --------
3065 >>> import numpy as np
3066 >>> a = np.array([[1, 2], [3, 4]])
3067 >>> a
3068 array([[1, 2],
3069 [3, 4]])
3070 >>> a.mT
3071 array([[1, 3],
3072 [2, 4]])
3073
3074 >>> a = np.arange(8).reshape((2, 2, 2))
3075 >>> a
3076 array([[[0, 1],
3077 [2, 3]],
3078 <BLANKLINE>
3079 [[4, 5],
3080 [6, 7]]])
3081 >>> a.mT
3082 array([[[0, 2],
3083 [1, 3]],
3084 <BLANKLINE>
3085 [[4, 6],
3086 [5, 7]]])
3087
3088 """))
3089
3090##############################################################################
3091#
3092# ndarray methods
3093#
3094##############################################################################
3095
3096
3097add_newdoc('numpy._core.multiarray', 'ndarray', ('__array__',
3098 """
3099 __array__($self, dtype=None, /, *, copy=None)
3100 --
3101
3102 a.__array__([dtype], *, copy=None)
3103
3104 For ``dtype`` parameter it returns a new reference to self if
3105 ``dtype`` is not given or it matches array's data type.
3106 A new array of provided data type is returned if ``dtype``
3107 is different from the current data type of the array.
3108 For ``copy`` parameter it returns a new reference to self if
3109 ``copy=False`` or ``copy=None`` and copying isn't enforced by ``dtype``
3110 parameter. The method returns a new array for ``copy=True``, regardless of
3111 ``dtype`` parameter.
3112
3113 A more detailed explanation of the ``__array__`` interface
3114 can be found in :ref:`dunder_array.interface`.
3115
3116 """))
3117
3118
3119add_newdoc('numpy._core.multiarray', 'ndarray', ('__array_finalize__',
3120 """
3121 __array_finalize__($self, obj, /)
3122 --
3123
3124 a.__array_finalize__(obj, /)
3125
3126 Present so subclasses can call super. Does nothing.
3127
3128 """))
3129
3130
3131add_newdoc('numpy._core.multiarray', 'ndarray', ('__array_function__',
3132 """
3133 __array_function__($self, /, func, types, args, kwargs)
3134 --
3135
3136 a.__array_function__(func, types, args, kwargs)
3137
3138 See :ref:`NEP 18 <NEP18>` and :ref:`NEP 35 <NEP35>` for details.
3139
3140 """))
3141
3142
3143add_newdoc('numpy._core.multiarray', 'ndarray', ('__array_ufunc__',
3144 """
3145 __array_ufunc__($self, ufunc, method, /, *inputs, **kwargs)
3146 --
3147
3148 a.__array_ufunc__(ufunc, method, /, *inputs, **kwargs)
3149
3150 See :ref:`NEP 13 <NEP13>` for details.
3151
3152 """))
3153
3154
3155add_newdoc('numpy._core.multiarray', 'ndarray', ('__array_wrap__',
3156 """
3157 __array_wrap__($self, array, context=None, return_scalar=True, /)
3158 --
3159
3160 a.__array_wrap__(array[, context[, return_scalar]], /)
3161
3162 Returns a view of `array` with the same type as self.
3163
3164 """))
3165
3166
3167add_newdoc('numpy._core.multiarray', 'ndarray', ('__class_getitem__',
3168 """
3169 __class_getitem__($cls, item, /)
3170 --
3171
3172 ndarray[shape, dtype]
3173
3174 Return a parametrized wrapper around the `~numpy.ndarray` type.
3175
3176 .. versionadded:: 1.22
3177
3178 Returns
3179 -------
3180 alias : types.GenericAlias
3181 A parametrized `~numpy.ndarray` type.
3182
3183 Examples
3184 --------
3185 >>> import numpy as np
3186
3187 >>> np.ndarray[tuple[int], np.dtype[np.uint8]]
3188 numpy.ndarray[tuple[int], numpy.dtype[numpy.uint8]]
3189
3190 See Also
3191 --------
3192 :pep:`585` : Type hinting generics in standard collections.
3193 numpy.typing.NDArray : An ndarray alias :term:`generic <generic type>`
3194 w.r.t. its `dtype.type <numpy.dtype.type>`.
3195
3196 """))
3197
3198
3199add_newdoc('numpy._core.multiarray', 'ndarray', ('__dlpack__',
3200 """
3201 __dlpack__($self, /, *, stream=None, max_version=None, dl_device=None, copy=None)
3202 --
3203
3204 a.__dlpack__(*, stream=None, max_version=None, dl_device=None, copy=None)
3205
3206 Exports the array for consumption by ``from_dlpack()`` as a DLPack capsule.
3207
3208 """))
3209
3210
3211add_newdoc('numpy._core.multiarray', 'ndarray', ('__dlpack_device__',
3212 """
3213 __dlpack_device__($self, /)
3214 --
3215
3216 a.__dlpack_device__()
3217
3218 Returns device type (``1``) and device ID (``0``) in DLPack format.
3219 Meant for use within ``from_dlpack()``.
3220
3221 """))
3222
3223
3224add_newdoc('numpy._core.multiarray', 'ndarray', ('__reduce__',
3225 """
3226 __reduce__($self, /)
3227 --
3228
3229 a.__reduce__()
3230
3231 For pickling.
3232
3233 """))
3234
3235
3236add_newdoc('numpy._core.multiarray', 'ndarray', ('__reduce_ex__',
3237 """
3238 __reduce_ex__($self, protocol, /)
3239 --
3240
3241 a.__reduce_ex__(protocol, /)
3242
3243 For pickling.
3244
3245 """))
3246
3247
3248add_newdoc('numpy._core.multiarray', 'ndarray', ('__setstate__',
3249 """
3250 __setstate__($self, state, /)
3251 --
3252
3253 a.__setstate__(state, /)
3254
3255 For unpickling.
3256
3257 The `state` argument must be a sequence that contains the following
3258 elements:
3259
3260 Parameters
3261 ----------
3262 version : int
3263 optional pickle version. If omitted defaults to 0.
3264 shape : tuple
3265 dtype : data-type
3266 isFortran : bool
3267 rawdata : string or list
3268 a binary string with the data (or a list if 'a' is an object array)
3269
3270 """))
3271
3272
3273add_newdoc('numpy._core.multiarray', 'ndarray', ('dot',
3274 """
3275 dot($self, other, /, out=None)
3276 --
3277
3278 a.dot(other, /, out=None)
3279
3280 Refer to :func:`numpy.dot` for full documentation.
3281
3282 See Also
3283 --------
3284 numpy.dot : equivalent function
3285
3286 """))
3287
3288
3289add_newdoc('numpy._core.multiarray', 'ndarray', ('argpartition',
3290 """
3291 argpartition($self, kth, /, axis=-1, kind='introselect', order=None)
3292 --
3293
3294 a.argpartition(kth, axis=-1, kind='introselect', order=None)
3295
3296 Returns the indices that would partition this array.
3297
3298 Refer to `numpy.argpartition` for full documentation.
3299
3300 See Also
3301 --------
3302 numpy.argpartition : equivalent function
3303
3304 """))
3305
3306
3307add_newdoc('numpy._core.multiarray', 'ndarray', ('partition',
3308 """
3309 partition($self, kth, /, axis=-1, kind='introselect', order=None)
3310 --
3311
3312 a.partition(kth, axis=-1, kind='introselect', order=None)
3313
3314 Partially sorts the elements in the array in such a way that the value of
3315 the element in k-th position is in the position it would be in a sorted
3316 array. In the output array, all elements smaller than the k-th element
3317 are located to the left of this element and all equal or greater are
3318 located to its right. The ordering of the elements in the two partitions
3319 on the either side of the k-th element in the output array is undefined.
3320
3321 Parameters
3322 ----------
3323 kth : int or sequence of ints
3324 Element index to partition by. The kth element value will be in its
3325 final sorted position and all smaller elements will be moved before it
3326 and all equal or greater elements behind it.
3327 The order of all elements in the partitions is undefined.
3328 If provided with a sequence of kth it will partition all elements
3329 indexed by kth of them into their sorted position at once.
3330
3331 .. deprecated:: 1.22.0
3332 Passing booleans as index is deprecated.
3333 axis : int, optional
3334 Axis along which to sort. Default is -1, which means sort along the
3335 last axis.
3336 kind : {'introselect'}, optional
3337 Selection algorithm. Default is 'introselect'.
3338 order : str or list of str, optional
3339 When `a` is an array with fields defined, this argument specifies
3340 which fields to compare first, second, etc. A single field can
3341 be specified as a string, and not all fields need to be specified,
3342 but unspecified fields will still be used, in the order in which
3343 they come up in the dtype, to break ties.
3344
3345 See Also
3346 --------
3347 numpy.partition : Return a partitioned copy of an array.
3348 argpartition : Indirect partition.
3349 sort : Full sort.
3350
3351 Notes
3352 -----
3353 See ``np.partition`` for notes on the different algorithms.
3354
3355 Examples
3356 --------
3357 >>> import numpy as np
3358 >>> a = np.array([3, 4, 2, 1])
3359 >>> a.partition(3)
3360 >>> a
3361 array([2, 1, 3, 4]) # may vary
3362
3363 >>> a.partition((1, 3))
3364 >>> a
3365 array([1, 2, 3, 4])
3366
3367 """))
3368
3369
3370##############################################################################
3371#
3372# methods from both `ndarray` and `generic`
3373#
3374##############################################################################
3375
3376_METHOD_DOC_TEMPLATE = """{name}({params})
3377--
3378
3379{doc}"""
3380
3381def _array_method_doc(name: str, params: str, doc: str) -> None:
3382 """
3383 Interenal helper function for adding docstrings to a common method of
3384 `numpy.ndarray` and `numpy.generic`.
3385
3386 The provided docstring will be added to the given `numpy.ndarray` method.
3387 For the `numpy.generic` method, a shorter docstring indicating that it is
3388 identical to the `ndarray` method will be created.
3389 Both methods will have a proper and identical `__text_signature__`.
3390
3391 Parameters
3392 ----------
3393 name : str
3394 Name of the method.
3395 params : str
3396 Parameter signature for the method without parentheses, for example,
3397 ``"a, /, dtype=None, *, copy=False"``.
3398 Parameter defaults must be understood by `ast.literal_eval`, i.e. strings,
3399 bytes, numbers, tuples, lists, dicts, sets, booleans, or None.
3400 doc : str
3401 The full docstring for the `ndarray` method.
3402 """
3403
3404 # prepend the pos-only `$self` parameter to the method signature
3405 if "/" not in params:
3406 params = f"/, {params}" if params else "/"
3407 params = f"$self, {params}"
3408
3409 # add docstring to `np.ndarray.{name}`
3410 doc = textwrap.dedent(doc).strip()
3411 doc_array = _METHOD_DOC_TEMPLATE.format(name=name, params=params, doc=doc)
3412 add_newdoc("numpy._core.multiarray", "ndarray", (name, doc_array))
3413
3414 # add docstring to `np.generic.{name}`
3415 doc_scalar = f"Scalar method identical to `ndarray.{name}`."
3416 doc_scalar = _METHOD_DOC_TEMPLATE.format(name=name, params=params, doc=doc_scalar)
3417 add_newdoc("numpy._core.numerictypes", "generic", (name, doc_scalar))
3418
3419
3420_array_method_doc('__array_namespace__', "*, api_version=None",
3421 """
3422 a.__array_namespace__(*, api_version=None)
3423
3424 For Array API compatibility.
3425 """)
3426
3427_array_method_doc('__copy__', "",
3428 """
3429 a.__copy__()
3430
3431 Used if :func:`copy.copy` is called on an array. Returns a copy of the array.
3432
3433 Equivalent to ``a.copy(order='K')``.
3434 """)
3435
3436_array_method_doc('__deepcopy__', "memo, /",
3437 """
3438 a.__deepcopy__(memo, /)
3439
3440 Used if :func:`copy.deepcopy` is called on an array.
3441 """)
3442
3443_array_method_doc('all', "axis=None, out=None, keepdims=False, *, where=True",
3444 """
3445 a.all(axis=None, out=None, *, keepdims=<no value>, where=<no value>)
3446
3447 Returns True if all elements evaluate to True.
3448
3449 Refer to `numpy.all` for full documentation.
3450
3451 See Also
3452 --------
3453 numpy.all : equivalent function
3454 """)
3455
3456_array_method_doc('any', "axis=None, out=None, keepdims=False, *, where=True",
3457 """
3458 a.any(axis=None, out=None, *, keepdims=<no value>, where=<no value>)
3459
3460 Returns True if any of the elements of `a` evaluate to True.
3461
3462 Refer to `numpy.any` for full documentation.
3463
3464 See Also
3465 --------
3466 numpy.any : equivalent function
3467 """)
3468
3469_array_method_doc('argmax', "axis=None, out=None, *, keepdims=False",
3470 """
3471 a.argmax(axis=None, out=None, *, keepdims=False)
3472
3473 Return indices of the maximum values along the given axis.
3474
3475 Refer to `numpy.argmax` for full documentation.
3476
3477 See Also
3478 --------
3479 numpy.argmax : equivalent function
3480 """)
3481
3482_array_method_doc('argmin', "axis=None, out=None, *, keepdims=False",
3483 """
3484 a.argmin(axis=None, out=None, *, keepdims=False)
3485
3486 Return indices of the minimum values along the given axis.
3487
3488 Refer to `numpy.argmin` for detailed documentation.
3489
3490 See Also
3491 --------
3492 numpy.argmin : equivalent function
3493 """)
3494
3495_array_method_doc('argsort', "axis=-1, kind=None, order=None, *, stable=None",
3496 """
3497 a.argsort(axis=-1, kind=None, order=None, *, stable=None)
3498
3499 Returns the indices that would sort this array.
3500
3501 Refer to `numpy.argsort` for full documentation.
3502
3503 See Also
3504 --------
3505 numpy.argsort : equivalent function
3506 """)
3507
3508_array_method_doc('astype', "dtype, order='K', casting='unsafe', subok=True, copy=True",
3509 """
3510 a.astype(dtype, order='K', casting='unsafe', subok=True, copy=True)
3511
3512 Copy of the array, cast to a specified type.
3513
3514 Parameters
3515 ----------
3516 dtype : str or dtype
3517 Typecode or data-type to which the array is cast.
3518 order : {'C', 'F', 'A', 'K'}, optional
3519 Controls the memory layout order of the result.
3520 'C' means C order, 'F' means Fortran order, 'A'
3521 means 'F' order if all the arrays are Fortran contiguous,
3522 'C' order otherwise, and 'K' means as close to the
3523 order the array elements appear in memory as possible.
3524 Default is 'K'.
3525 casting : {'no', 'equiv', 'safe', 'same_kind', 'same_value', 'unsafe'}, optional
3526 Controls what kind of data casting may occur. Defaults to 'unsafe'
3527 for backwards compatibility.
3528
3529 * 'no' means the data types should not be cast at all.
3530 * 'equiv' means only byte-order changes are allowed.
3531 * 'safe' means only casts which can preserve values are allowed.
3532 * 'same_kind' means only safe casts or casts within a kind,
3533 like float64 to float32, are allowed.
3534 * 'unsafe' means any data conversions may be done.
3535 * 'same_value' means any data conversions may be done, but the values
3536 must not change, including rounding of floats or overflow of ints
3537
3538 .. versionadded:: 2.4
3539 Support for ``'same_value'`` was added.
3540
3541 subok : bool, optional
3542 If True, then sub-classes will be passed-through (default), otherwise
3543 the returned array will be forced to be a base-class array.
3544 copy : bool, optional
3545 By default, astype always returns a newly allocated array. If this
3546 is set to false, and the `dtype`, `order`, and `subok`
3547 requirements are satisfied, the input array is returned instead
3548 of a copy.
3549
3550 Returns
3551 -------
3552 arr_t : ndarray
3553 Unless `copy` is False and the other conditions for returning the input
3554 array are satisfied (see description for `copy` input parameter), `arr_t`
3555 is a new array of the same shape as the input array, with dtype, order
3556 given by `dtype`, `order`.
3557
3558 Raises
3559 ------
3560 ComplexWarning
3561 When casting from complex to float or int. To avoid this,
3562 one should use ``a.real.astype(t)``.
3563 ValueError
3564 When casting using ``'same_value'`` and the values change or would
3565 overflow
3566
3567 Examples
3568 --------
3569 >>> import numpy as np
3570 >>> x = np.array([1, 2, 2.5])
3571 >>> x
3572 array([1. , 2. , 2.5])
3573
3574 >>> x.astype(int)
3575 array([1, 2, 2])
3576
3577 >>> x.astype(int, casting="same_value")
3578 Traceback (most recent call last):
3579 ...
3580 ValueError: could not cast 'same_value' double to long
3581
3582 >>> x[:2].astype(int, casting="same_value")
3583 array([1, 2])
3584 """)
3585
3586_array_method_doc('byteswap', "inplace=False",
3587 """
3588 a.byteswap(inplace=False)
3589
3590 Swap the bytes of the array elements
3591
3592 Toggle between low-endian and big-endian data representation by
3593 returning a byteswapped array, optionally swapped in-place.
3594 Arrays of byte-strings are not swapped. The real and imaginary
3595 parts of a complex number are swapped individually.
3596
3597 Parameters
3598 ----------
3599 inplace : bool, optional
3600 If ``True``, swap bytes in-place, default is ``False``.
3601
3602 Returns
3603 -------
3604 out : ndarray
3605 The byteswapped array. If `inplace` is ``True``, this is
3606 a view to self.
3607
3608 Examples
3609 --------
3610 >>> import numpy as np
3611 >>> A = np.array([1, 256, 8755], dtype=np.int16)
3612 >>> list(map(hex, A))
3613 ['0x1', '0x100', '0x2233']
3614 >>> A.byteswap(inplace=True)
3615 array([ 256, 1, 13090], dtype=int16)
3616 >>> list(map(hex, A))
3617 ['0x100', '0x1', '0x3322']
3618
3619 Arrays of byte-strings are not swapped
3620
3621 >>> A = np.array([b'ceg', b'fac'])
3622 >>> A.byteswap()
3623 array([b'ceg', b'fac'], dtype='|S3')
3624
3625 ``A.view(A.dtype.newbyteorder()).byteswap()`` produces an array with
3626 the same values but different representation in memory
3627
3628 >>> A = np.array([1, 2, 3],dtype=np.int64)
3629 >>> A.view(np.uint8)
3630 array([1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0,
3631 0, 0], dtype=uint8)
3632 >>> A.view(A.dtype.newbyteorder()).byteswap(inplace=True)
3633 array([1, 2, 3], dtype='>i8')
3634 >>> A.view(np.uint8)
3635 array([0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0,
3636 0, 3], dtype=uint8)
3637 """)
3638
3639_array_method_doc('choose', "choices, out=None, mode='raise'",
3640 """
3641 a.choose(choices, out=None, mode='raise')
3642
3643 Use an index array to construct a new array from a set of choices.
3644
3645 Refer to `numpy.choose` for full documentation.
3646
3647 See Also
3648 --------
3649 numpy.choose : equivalent function
3650 """)
3651
3652_array_method_doc('clip', "min=None, max=None, out=None, **kwargs",
3653 """
3654 a.clip(min=<no value>, max=<no value>, out=None, **kwargs)
3655
3656 Return an array whose values are limited to ``[min, max]``.
3657 One of max or min must be given.
3658
3659 Refer to `numpy.clip` for full documentation.
3660
3661 See Also
3662 --------
3663 numpy.clip : equivalent function
3664 """)
3665
3666_array_method_doc('compress', "condition, axis=None, out=None",
3667 """
3668 a.compress(condition, axis=None, out=None)
3669
3670 Return selected slices of this array along given axis.
3671
3672 Refer to `numpy.compress` for full documentation.
3673
3674 See Also
3675 --------
3676 numpy.compress : equivalent function
3677 """)
3678
3679_array_method_doc('conj', "",
3680 """
3681 a.conj()
3682
3683 Complex-conjugate all elements.
3684
3685 Refer to `numpy.conjugate` for full documentation.
3686
3687 See Also
3688 --------
3689 numpy.conjugate : equivalent function
3690 """)
3691
3692_array_method_doc('conjugate', "",
3693 """
3694 a.conjugate()
3695
3696 Return the complex conjugate, element-wise.
3697
3698 Refer to `numpy.conjugate` for full documentation.
3699
3700 See Also
3701 --------
3702 numpy.conjugate : equivalent function
3703 """)
3704
3705_array_method_doc('copy', "order='C'",
3706 """
3707 a.copy(order='C')
3708
3709 Return a copy of the array.
3710
3711 Parameters
3712 ----------
3713 order : {'C', 'F', 'A', 'K'}, optional
3714 Controls the memory layout of the copy. 'C' means C-order,
3715 'F' means F-order, 'A' means 'F' if `a` is Fortran contiguous,
3716 'C' otherwise. 'K' means match the layout of `a` as closely
3717 as possible. (Note that this function and :func:`numpy.copy` are very
3718 similar but have different default values for their order=
3719 arguments, and this function always passes sub-classes through.)
3720
3721 See also
3722 --------
3723 numpy.copy : Similar function with different default behavior
3724 numpy.copyto
3725
3726 Notes
3727 -----
3728 This function is the preferred method for creating an array copy. The
3729 function :func:`numpy.copy` is similar, but it defaults to using order 'K',
3730 and will not pass sub-classes through by default.
3731
3732 Examples
3733 --------
3734 >>> import numpy as np
3735 >>> x = np.array([[1,2,3],[4,5,6]], order='F')
3736
3737 >>> y = x.copy()
3738
3739 >>> x.fill(0)
3740
3741 >>> x
3742 array([[0, 0, 0],
3743 [0, 0, 0]])
3744
3745 >>> y
3746 array([[1, 2, 3],
3747 [4, 5, 6]])
3748
3749 >>> y.flags['C_CONTIGUOUS']
3750 True
3751
3752 For arrays containing Python objects (e.g. dtype=object),
3753 the copy is a shallow one. The new array will contain the
3754 same object which may lead to surprises if that object can
3755 be modified (is mutable):
3756
3757 >>> a = np.array([1, 'm', [2, 3, 4]], dtype=object)
3758 >>> b = a.copy()
3759 >>> b[2][0] = 10
3760 >>> a
3761 array([1, 'm', list([10, 3, 4])], dtype=object)
3762
3763 To ensure all elements within an ``object`` array are copied,
3764 use `copy.deepcopy`:
3765
3766 >>> import copy
3767 >>> a = np.array([1, 'm', [2, 3, 4]], dtype=object)
3768 >>> c = copy.deepcopy(a)
3769 >>> c[2][0] = 10
3770 >>> c
3771 array([1, 'm', list([10, 3, 4])], dtype=object)
3772 >>> a
3773 array([1, 'm', list([2, 3, 4])], dtype=object)
3774 """)
3775
3776_array_method_doc('cumprod', "axis=None, dtype=None, out=None",
3777 """
3778 a.cumprod(axis=None, dtype=None, out=None)
3779
3780 Return the cumulative product of the elements along the given axis.
3781
3782 Refer to `numpy.cumprod` for full documentation.
3783
3784 See Also
3785 --------
3786 numpy.cumprod : equivalent function
3787 """)
3788
3789_array_method_doc('cumsum', "axis=None, dtype=None, out=None",
3790 """
3791 a.cumsum(axis=None, dtype=None, out=None)
3792
3793 Return the cumulative sum of the elements along the given axis.
3794
3795 Refer to `numpy.cumsum` for full documentation.
3796
3797 See Also
3798 --------
3799 numpy.cumsum : equivalent function
3800 """)
3801
3802_array_method_doc('diagonal', "offset=0, axis1=0, axis2=1",
3803 """
3804 a.diagonal(offset=0, axis1=0, axis2=1)
3805
3806 Return specified diagonals. In NumPy 1.9 the returned array is a
3807 read-only view instead of a copy as in previous NumPy versions. In
3808 a future version the read-only restriction will be removed.
3809
3810 Refer to :func:`numpy.diagonal` for full documentation.
3811
3812 See Also
3813 --------
3814 numpy.diagonal : equivalent function
3815 """)
3816
3817_array_method_doc('dump', "file",
3818 """
3819 a.dump(file)
3820
3821 Dump a pickle of the array to the specified file.
3822 The array can be read back with pickle.load or numpy.load.
3823
3824 Parameters
3825 ----------
3826 file : str or Path
3827 A string naming the dump file.
3828 """)
3829
3830_array_method_doc('dumps', "",
3831 """
3832 a.dumps()
3833
3834 Returns the pickle of the array as a string.
3835 ``pickle.loads`` will convert the string back to an array.
3836
3837 Parameters
3838 ----------
3839 None
3840 """)
3841
3842_array_method_doc('fill', "value",
3843 """
3844 a.fill(value)
3845
3846 Fill the array with a scalar value.
3847
3848 Parameters
3849 ----------
3850 value : scalar
3851 All elements of `a` will be assigned this value.
3852
3853 Examples
3854 --------
3855 >>> import numpy as np
3856 >>> a = np.array([1, 2])
3857 >>> a.fill(0)
3858 >>> a
3859 array([0, 0])
3860 >>> a = np.empty(2)
3861 >>> a.fill(1)
3862 >>> a
3863 array([1., 1.])
3864
3865 Fill expects a scalar value and always behaves the same as assigning
3866 to a single array element. The following is a rare example where this
3867 distinction is important:
3868
3869 >>> a = np.array([None, None], dtype=object)
3870 >>> a[0] = np.array(3)
3871 >>> a
3872 array([array(3), None], dtype=object)
3873 >>> a.fill(np.array(3))
3874 >>> a
3875 array([array(3), array(3)], dtype=object)
3876
3877 Where other forms of assignments will unpack the array being assigned:
3878
3879 >>> a[...] = np.array(3)
3880 >>> a
3881 array([3, 3], dtype=object)
3882 """)
3883
3884_array_method_doc('flatten', "order='C'",
3885 """
3886 a.flatten(order='C')
3887
3888 Return a copy of the array collapsed into one dimension.
3889
3890 Parameters
3891 ----------
3892 order : {'C', 'F', 'A', 'K'}, optional
3893 'C' means to flatten in row-major (C-style) order.
3894 'F' means to flatten in column-major (Fortran-
3895 style) order. 'A' means to flatten in column-major
3896 order if `a` is Fortran *contiguous* in memory,
3897 row-major order otherwise. 'K' means to flatten
3898 `a` in the order the elements occur in memory.
3899 The default is 'C'.
3900
3901 Returns
3902 -------
3903 y : ndarray
3904 A copy of the input array, flattened to one dimension.
3905
3906 See Also
3907 --------
3908 ravel : Return a flattened array.
3909 flat : A 1-D flat iterator over the array.
3910
3911 Examples
3912 --------
3913 >>> import numpy as np
3914 >>> a = np.array([[1,2], [3,4]])
3915 >>> a.flatten()
3916 array([1, 2, 3, 4])
3917 >>> a.flatten('F')
3918 array([1, 3, 2, 4])
3919 """)
3920
3921_array_method_doc('getfield', "dtype, offset=0",
3922 """
3923 a.getfield(dtype, offset=0)
3924
3925 Returns a field of the given array as a certain type.
3926
3927 A field is a view of the array data with a given data-type. The values in
3928 the view are determined by the given type and the offset into the current
3929 array in bytes. The offset needs to be such that the view dtype fits in the
3930 array dtype; for example an array of dtype complex128 has 16-byte elements.
3931 If taking a view with a 32-bit integer (4 bytes), the offset needs to be
3932 between 0 and 12 bytes.
3933
3934 Parameters
3935 ----------
3936 dtype : str or dtype
3937 The data type of the view. The dtype size of the view can not be larger
3938 than that of the array itself.
3939 offset : int
3940 Number of bytes to skip before beginning the element view.
3941
3942 Examples
3943 --------
3944 >>> import numpy as np
3945 >>> x = np.diag([1.+1.j]*2)
3946 >>> x[1, 1] = 2 + 4.j
3947 >>> x
3948 array([[1.+1.j, 0.+0.j],
3949 [0.+0.j, 2.+4.j]])
3950 >>> x.getfield(np.float64)
3951 array([[1., 0.],
3952 [0., 2.]])
3953
3954 By choosing an offset of 8 bytes we can select the complex part of the
3955 array for our view:
3956
3957 >>> x.getfield(np.float64, offset=8)
3958 array([[1., 0.],
3959 [0., 4.]])
3960 """)
3961
3962_array_method_doc('item', "*args",
3963 """
3964 a.item(*args)
3965
3966 Copy an element of an array to a standard Python scalar and return it.
3967
3968 Parameters
3969 ----------
3970 \\*args : Arguments (variable number and type)
3971
3972 * none: in this case, the method only works for arrays
3973 with one element (`a.size == 1`), which element is
3974 copied into a standard Python scalar object and returned.
3975
3976 * int_type: this argument is interpreted as a flat index into
3977 the array, specifying which element to copy and return.
3978
3979 * tuple of int_types: functions as does a single int_type argument,
3980 except that the argument is interpreted as an nd-index into the
3981 array.
3982
3983 Returns
3984 -------
3985 z : Standard Python scalar object
3986 A copy of the specified element of the array as a suitable
3987 Python scalar
3988
3989 Notes
3990 -----
3991 When the data type of `a` is longdouble or clongdouble, item() returns
3992 a scalar array object because there is no available Python scalar that
3993 would not lose information. Void arrays return a buffer object for item(),
3994 unless fields are defined, in which case a tuple is returned.
3995
3996 `item` is very similar to a[args], except, instead of an array scalar,
3997 a standard Python scalar is returned. This can be useful for speeding up
3998 access to elements of the array and doing arithmetic on elements of the
3999 array using Python's optimized math.
4000
4001 Examples
4002 --------
4003 >>> import numpy as np
4004 >>> np.random.seed(123)
4005 >>> x = np.random.randint(9, size=(3, 3))
4006 >>> x
4007 array([[2, 2, 6],
4008 [1, 3, 6],
4009 [1, 0, 1]])
4010 >>> x.item(3)
4011 1
4012 >>> x.item(7)
4013 0
4014 >>> x.item((0, 1))
4015 2
4016 >>> x.item((2, 2))
4017 1
4018
4019 For an array with object dtype, elements are returned as-is.
4020
4021 >>> a = np.array([np.int64(1)], dtype=object)
4022 >>> a.item() #return np.int64
4023 np.int64(1)
4024 """)
4025
4026_KWARGS_REDUCE = "keepdims=<no value>, initial=<no value>, where=<no value>"
4027
4028_array_method_doc('max', "axis=None, out=None, **kwargs",
4029 f"""
4030 a.max(axis=None, out=None, *, {_KWARGS_REDUCE})
4031
4032 Return the maximum along a given axis.
4033
4034 Refer to `numpy.amax` for full documentation.
4035
4036 See Also
4037 --------
4038 numpy.amax : equivalent function
4039 """)
4040
4041_array_method_doc('min', "axis=None, out=None, **kwargs",
4042 f"""
4043 a.min(axis=None, out=None, *, {_KWARGS_REDUCE})
4044
4045 Return the minimum along a given axis.
4046
4047 Refer to `numpy.amin` for full documentation.
4048
4049 See Also
4050 --------
4051 numpy.amin : equivalent function
4052 """)
4053
4054_array_method_doc('prod', "axis=None, dtype=None, out=None, **kwargs",
4055 f"""
4056 a.prod(axis=None, dtype=None, out=None, *, {_KWARGS_REDUCE})
4057
4058 Return the product of the array elements over the given axis
4059
4060 Refer to `numpy.prod` for full documentation.
4061
4062 See Also
4063 --------
4064 numpy.prod : equivalent function
4065 """)
4066
4067_array_method_doc('sum', "axis=None, dtype=None, out=None, **kwargs",
4068 f"""
4069 a.sum(axis=None, dtype=None, out=None, *, {_KWARGS_REDUCE})
4070
4071 Return the sum of the array elements over the given axis.
4072
4073 Refer to `numpy.sum` for full documentation.
4074
4075 See Also
4076 --------
4077 numpy.sum : equivalent function
4078 """)
4079
4080_array_method_doc('mean', "axis=None, dtype=None, out=None, **kwargs",
4081 """
4082 a.mean(axis=None, dtype=None, out=None, *, keepdims=<no value>, where=<no value>)
4083
4084 Returns the average of the array elements along given axis.
4085
4086 Refer to `numpy.mean` for full documentation.
4087
4088 See Also
4089 --------
4090 numpy.mean : equivalent function
4091 """)
4092
4093_array_method_doc('nonzero', "",
4094 """
4095 a.nonzero()
4096
4097 Return the indices of the elements that are non-zero.
4098
4099 Refer to `numpy.nonzero` for full documentation.
4100
4101 See Also
4102 --------
4103 numpy.nonzero : equivalent function
4104 """)
4105
4106_array_method_doc('put', "indices, values, /, mode='raise'",
4107 """
4108 a.put(indices, values, mode='raise')
4109
4110 Set ``a.flat[n] = values[n]`` for all ``n`` in indices.
4111
4112 Refer to `numpy.put` for full documentation.
4113
4114 See Also
4115 --------
4116 numpy.put : equivalent function
4117 """)
4118
4119_array_method_doc('ravel', "order='C'",
4120 """
4121 a.ravel(order='C')
4122
4123 Return a flattened array.
4124
4125 Refer to `numpy.ravel` for full documentation.
4126
4127 See Also
4128 --------
4129 numpy.ravel : equivalent function
4130 ndarray.flat : a flat iterator on the array.
4131 """)
4132
4133_array_method_doc('repeat', "repeats, /, axis=None",
4134 """
4135 a.repeat(repeats, axis=None)
4136
4137 Repeat elements of an array.
4138
4139 Refer to `numpy.repeat` for full documentation.
4140
4141 See Also
4142 --------
4143 numpy.repeat : equivalent function
4144 """)
4145
4146_array_method_doc('reshape', "*shape, order='C', copy=None",
4147 """
4148 a.reshape(shape, /, *, order='C', copy=None)
4149 a.reshape(*shape, order='C', copy=None)
4150
4151 Returns an array containing the same data with a new shape.
4152
4153 Refer to `numpy.reshape` for full documentation.
4154
4155 See Also
4156 --------
4157 numpy.reshape : equivalent function
4158
4159 Notes
4160 -----
4161 Unlike the free function `numpy.reshape`, this method on `ndarray` allows
4162 the elements of the shape parameter to be passed in as separate arguments.
4163 For example, ``a.reshape(4, 2)`` is equivalent to ``a.reshape((4, 2))``.
4164 """)
4165
4166_array_method_doc('resize', "*new_shape, refcheck=True",
4167 """
4168 a.resize(new_shape, /, *, refcheck=True)
4169 a.resize(*new_shape, refcheck=True)
4170
4171 Change shape and size of array in-place.
4172
4173 Parameters
4174 ----------
4175 new_shape : tuple of ints, or `n` ints
4176 Shape of resized array.
4177 refcheck : bool, optional
4178 If False, reference count will not be checked. Default is True.
4179 See Notes below for more explanation.
4180
4181 Returns
4182 -------
4183 None
4184
4185 Raises
4186 ------
4187 ValueError
4188 If `a` does not own its own data or references or views to may exist.
4189
4190 See Also
4191 --------
4192 resize : Return a new array with the specified shape.
4193
4194 Notes
4195 -----
4196 This reallocates space for the data area if necessary.
4197
4198 Only contiguous arrays (data elements consecutive in memory) can be
4199 resized.
4200
4201 Reallocating arrays in-place can often lead to memory fragmentation and
4202 should be avoided. If the goal is to reclaim over-allocated memory,
4203 alternatives are to create a view or a copy of just the desired data, or
4204 using two passes to build the array: one to cheaply determine the shape and
4205 another to allocate and fill. Benchmark your use case to determine what is
4206 optimum. You may be surprised to find ``resize`` actually slows down or
4207 bloats your application.
4208
4209 The purpose of the reference count check is to make sure you
4210 do not use this array as a buffer for another Python object and then
4211 reallocate the memory.
4212
4213 On Python 3.13 and older, the check allows objects with exactly one
4214 reference to be reallocated in-place. On Python 3.14 and newer, the array
4215 must be uniquely referenced. See [1]_ for more details.
4216
4217 If you are sure that you have not shared the memory for this array with
4218 another Python object, then you may safely set `refcheck` to False.
4219
4220
4221 References
4222 ----------
4223 .. [1] Python 3.14 What's New, https://docs.python.org/3/whatsnew/3.14.html#whatsnew314-refcount
4224
4225 Examples
4226 --------
4227 Shrinking an array: array is flattened (in the order that the data are
4228 stored in memory), resized, and reshaped:
4229
4230 >>> import numpy as np
4231
4232 >>> a = np.array([[0, 1], [2, 3]], order='C')
4233 >>> a.resize((2, 1))
4234 >>> a
4235 array([[0],
4236 [1]])
4237
4238 >>> a = np.array([[0, 1], [2, 3]], order='F')
4239 >>> a.resize((2, 1))
4240 >>> a
4241 array([[0],
4242 [2]])
4243
4244 Enlarging an array: as above, but missing entries are filled with zeros:
4245
4246 >>> b = np.array([[0, 1], [2, 3]])
4247 >>> b.resize(2, 3) # new_shape parameter doesn't have to be a tuple
4248 >>> b
4249 array([[0, 1, 2],
4250 [3, 0, 0]])
4251
4252 Referencing an array prevents resizing...
4253
4254 >>> c = a
4255 >>> a.resize((1, 1))
4256 Traceback (most recent call last):
4257 ...
4258 ValueError: cannot resize an array that references or is referenced ...
4259
4260 Unless `refcheck` is False:
4261
4262 >>> a.resize((1, 1), refcheck=False)
4263 >>> a
4264 array([[0]])
4265 >>> c
4266 array([[0]])
4267 """)
4268
4269_array_method_doc('round', "decimals=0, out=None",
4270 """
4271 a.round(decimals=0, out=None)
4272
4273 Return `a` with each element rounded to the given number of decimals.
4274
4275 Refer to `numpy.around` for full documentation.
4276
4277 See Also
4278 --------
4279 numpy.around : equivalent function
4280 """)
4281
4282_array_method_doc('searchsorted', "v, /, side='left', sorter=None",
4283 """
4284 a.searchsorted(v, side='left', sorter=None)
4285
4286 Find indices where elements of `v` should be inserted in `a` to maintain order.
4287
4288 For full documentation, see `numpy.searchsorted`.
4289
4290 See Also
4291 --------
4292 numpy.searchsorted : equivalent function
4293 """)
4294
4295_array_method_doc('setfield', "val, /, dtype, offset=0",
4296 """
4297 a.setfield(val, dtype, offset=0)
4298
4299 Put a value into a specified place in a field defined by a data-type.
4300
4301 Place `val` into `a`'s field defined by `dtype` and beginning `offset`
4302 bytes into the field.
4303
4304 Parameters
4305 ----------
4306 val : object
4307 Value to be placed in field.
4308 dtype : dtype object
4309 Data-type of the field in which to place `val`.
4310 offset : int, optional
4311 The number of bytes into the field at which to place `val`.
4312
4313 Returns
4314 -------
4315 None
4316
4317 See Also
4318 --------
4319 getfield
4320
4321 Examples
4322 --------
4323 >>> import numpy as np
4324 >>> x = np.eye(3)
4325 >>> x.getfield(np.float64)
4326 array([[1., 0., 0.],
4327 [0., 1., 0.],
4328 [0., 0., 1.]])
4329 >>> x.setfield(3, np.int32)
4330 >>> x.getfield(np.int32)
4331 array([[3, 3, 3],
4332 [3, 3, 3],
4333 [3, 3, 3]], dtype=int32)
4334 >>> x
4335 array([[1.0e+000, 1.5e-323, 1.5e-323],
4336 [1.5e-323, 1.0e+000, 1.5e-323],
4337 [1.5e-323, 1.5e-323, 1.0e+000]])
4338 >>> x.setfield(np.eye(3), np.int32)
4339 >>> x
4340 array([[1., 0., 0.],
4341 [0., 1., 0.],
4342 [0., 0., 1.]])
4343 """)
4344
4345_array_method_doc('setflags', "*, write=None, align=None, uic=None",
4346 """
4347 a.setflags(write=None, align=None, uic=None)
4348
4349 Set array flags WRITEABLE, ALIGNED, WRITEBACKIFCOPY,
4350 respectively.
4351
4352 These Boolean-valued flags affect how numpy interprets the memory
4353 area used by `a` (see Notes below). The ALIGNED flag can only
4354 be set to True if the data is actually aligned according to the type.
4355 The WRITEBACKIFCOPY flag can never be set
4356 to True. The flag WRITEABLE can only be set to True if the array owns its
4357 own memory, or the ultimate owner of the memory exposes a writeable buffer
4358 interface, or is a string. (The exception for string is made so that
4359 unpickling can be done without copying memory.)
4360
4361 Parameters
4362 ----------
4363 write : bool, optional
4364 Describes whether or not `a` can be written to.
4365 align : bool, optional
4366 Describes whether or not `a` is aligned properly for its type.
4367 uic : bool, optional
4368 Describes whether or not `a` is a copy of another "base" array.
4369
4370 Notes
4371 -----
4372 Array flags provide information about how the memory area used
4373 for the array is to be interpreted. There are 7 Boolean flags
4374 in use, only three of which can be changed by the user:
4375 WRITEBACKIFCOPY, WRITEABLE, and ALIGNED.
4376
4377 WRITEABLE (W) the data area can be written to;
4378
4379 ALIGNED (A) the data and strides are aligned appropriately for the hardware
4380 (as determined by the compiler);
4381
4382 WRITEBACKIFCOPY (X) this array is a copy of some other array (referenced
4383 by .base). When the C-API function PyArray_ResolveWritebackIfCopy is
4384 called, the base array will be updated with the contents of this array.
4385
4386 All flags can be accessed using the single (upper case) letter as well
4387 as the full name.
4388
4389 Examples
4390 --------
4391 >>> import numpy as np
4392 >>> y = np.array([[3, 1, 7],
4393 ... [2, 0, 0],
4394 ... [8, 5, 9]])
4395 >>> y
4396 array([[3, 1, 7],
4397 [2, 0, 0],
4398 [8, 5, 9]])
4399 >>> y.flags
4400 C_CONTIGUOUS : True
4401 F_CONTIGUOUS : False
4402 OWNDATA : True
4403 WRITEABLE : True
4404 ALIGNED : True
4405 WRITEBACKIFCOPY : False
4406 >>> y.setflags(write=0, align=0)
4407 >>> y.flags
4408 C_CONTIGUOUS : True
4409 F_CONTIGUOUS : False
4410 OWNDATA : True
4411 WRITEABLE : False
4412 ALIGNED : False
4413 WRITEBACKIFCOPY : False
4414 >>> y.setflags(uic=1)
4415 Traceback (most recent call last):
4416 File "<stdin>", line 1, in <module>
4417 ValueError: cannot set WRITEBACKIFCOPY flag to True
4418 """)
4419
4420_array_method_doc('sort', "axis=-1, kind=None, order=None, *, stable=None",
4421 """
4422 a.sort(axis=-1, kind=None, order=None, *, stable=None)
4423
4424 Sort an array in-place. Refer to `numpy.sort` for full documentation.
4425
4426 Parameters
4427 ----------
4428 axis : int, optional
4429 Axis along which to sort. Default is -1, which means sort along the
4430 last axis.
4431 kind : {'quicksort', 'mergesort', 'heapsort', 'stable'}, optional
4432 Sorting algorithm. The default is 'quicksort'. Note that both 'stable'
4433 and 'mergesort' use timsort under the covers and, in general, the
4434 actual implementation will vary with datatype. The 'mergesort' option
4435 is retained for backwards compatibility.
4436 order : str or list of str, optional
4437 When `a` is an array with fields defined, this argument specifies
4438 which fields to compare first, second, etc. A single field can
4439 be specified as a string, and not all fields need be specified,
4440 but unspecified fields will still be used, in the order in which
4441 they come up in the dtype, to break ties.
4442 stable : bool, optional
4443 Sort stability. If ``True``, the returned array will maintain
4444 the relative order of ``a`` values which compare as equal.
4445 If ``False`` or ``None``, this is not guaranteed. Internally,
4446 this option selects ``kind='stable'``. Default: ``None``.
4447
4448 .. versionadded:: 2.0.0
4449
4450 See Also
4451 --------
4452 numpy.sort : Return a sorted copy of an array.
4453 numpy.argsort : Indirect sort.
4454 numpy.lexsort : Indirect stable sort on multiple keys.
4455 numpy.searchsorted : Find elements in sorted array.
4456 numpy.partition: Partial sort.
4457
4458 Notes
4459 -----
4460 See `numpy.sort` for notes on the different sorting algorithms.
4461
4462 Examples
4463 --------
4464 >>> import numpy as np
4465 >>> a = np.array([[1,4], [3,1]])
4466 >>> a.sort(axis=1)
4467 >>> a
4468 array([[1, 4],
4469 [1, 3]])
4470 >>> a.sort(axis=0)
4471 >>> a
4472 array([[1, 3],
4473 [1, 4]])
4474
4475 Use the `order` keyword to specify a field to use when sorting a
4476 structured array:
4477
4478 >>> a = np.array([('a', 2), ('c', 1)], dtype=[('x', 'S1'), ('y', int)])
4479 >>> a.sort(order='y')
4480 >>> a
4481 array([(b'c', 1), (b'a', 2)],
4482 dtype=[('x', 'S1'), ('y', '<i8')])
4483 """)
4484
4485_array_method_doc('squeeze', "axis=None",
4486 """
4487 a.squeeze(axis=None)
4488
4489 Remove axes of length one from `a`.
4490
4491 Refer to `numpy.squeeze` for full documentation.
4492
4493 See Also
4494 --------
4495 numpy.squeeze : equivalent function
4496 """)
4497
4498_KWARGS_STD = "*, keepdims=<no value>, where=<no value>, mean=<no value>"
4499
4500_array_method_doc('std', "axis=None, dtype=None, out=None, ddof=0, **kwargs",
4501 f"""
4502 a.std(axis=None, dtype=None, out=None, ddof=0, {_KWARGS_STD})
4503
4504 Returns the standard deviation of the array elements along given axis.
4505
4506 Refer to `numpy.std` for full documentation.
4507
4508 See Also
4509 --------
4510 numpy.std : equivalent function
4511 """)
4512
4513_array_method_doc('var', "axis=None, dtype=None, out=None, ddof=0, **kwargs",
4514 f"""
4515 a.var(axis=None, dtype=None, out=None, ddof=0, {_KWARGS_STD})
4516
4517 Returns the variance of the array elements, along given axis.
4518
4519 Refer to `numpy.var` for full documentation.
4520
4521 See Also
4522 --------
4523 numpy.var : equivalent function
4524 """)
4525
4526_array_method_doc('swapaxes', "axis1, axis2, /",
4527 """
4528 a.swapaxes(axis1, axis2, /)
4529
4530 Return a view of the array with `axis1` and `axis2` interchanged.
4531
4532 Refer to `numpy.swapaxes` for full documentation.
4533
4534 See Also
4535 --------
4536 numpy.swapaxes : equivalent function
4537 """)
4538
4539_array_method_doc('take', "indices, /, axis=None, out=None, mode='raise'",
4540 """
4541 a.take(indices, axis=None, out=None, mode='raise')
4542
4543 Return an array formed from the elements of `a` at the given indices.
4544
4545 Refer to `numpy.take` for full documentation.
4546
4547 See Also
4548 --------
4549 numpy.take : equivalent function
4550 """)
4551
4552_array_method_doc('to_device', "device, /, *, stream=None",
4553 """
4554 a.to_device(device, /, *, stream=None)
4555
4556 For Array API compatibility. Since NumPy only supports CPU arrays, this
4557 method is a no-op that returns the same array.
4558
4559 Parameters
4560 ----------
4561 device : "cpu"
4562 Must be ``"cpu"``.
4563 stream : None, optional
4564 Currently unsupported.
4565
4566 Returns
4567 -------
4568 out : Self
4569 Returns the same array.
4570 """)
4571
4572_array_method_doc('tofile', "fid, /, sep='', format='%s'",
4573 """
4574 a.tofile(fid, /, sep='', format='%s')
4575
4576 Write array to a file as text or binary (default).
4577
4578 Data is always written in 'C' order, independent of the order of `a`.
4579 The data produced by this method can be recovered using the function
4580 fromfile().
4581
4582 Parameters
4583 ----------
4584 fid : file or str or Path
4585 An open file object, or a string containing a filename.
4586 sep : str
4587 Separator between array items for text output.
4588 If "" (empty), a binary file is written, equivalent to
4589 ``file.write(a.tobytes())``.
4590 format : str
4591 Format string for text file output.
4592 Each entry in the array is formatted to text by first converting
4593 it to the closest Python type, and then using "format" % item.
4594
4595 Notes
4596 -----
4597 This is a convenience function for quick storage of array data.
4598 Information on endianness and precision is lost, so this method is not a
4599 good choice for files intended to archive data or transport data between
4600 machines with different endianness. Some of these problems can be overcome
4601 by outputting the data as text files, at the expense of speed and file
4602 size.
4603
4604 When fid is a file object, array contents are directly written to the
4605 file, bypassing the file object's ``write`` method. As a result, tofile
4606 cannot be used with files objects supporting compression (e.g., GzipFile)
4607 or file-like objects that do not support ``fileno()`` (e.g., BytesIO).
4608 """)
4609
4610_array_method_doc('tolist', "",
4611 """
4612 a.tolist()
4613
4614 Return the array as an ``a.ndim``-levels deep nested list of Python scalars.
4615
4616 Return a copy of the array data as a (nested) Python list.
4617 Data items are converted to the nearest compatible builtin Python type, via
4618 the `~numpy.ndarray.item` method.
4619
4620 If ``a.ndim`` is 0, then since the depth of the nested list is 0, it will
4621 not be a list at all, but a simple Python scalar.
4622
4623 Parameters
4624 ----------
4625 none
4626
4627 Returns
4628 -------
4629 y : object, or list of object, or list of list of object, or ...
4630 The possibly nested list of array elements.
4631
4632 Notes
4633 -----
4634 The array may be recreated via ``a = np.array(a.tolist())``, although this
4635 may sometimes lose precision.
4636
4637 Examples
4638 --------
4639 For a 1D array, ``a.tolist()`` is almost the same as ``list(a)``,
4640 except that ``tolist`` changes numpy scalars to Python scalars:
4641
4642 >>> import numpy as np
4643 >>> a = np.uint32([1, 2])
4644 >>> a_list = list(a)
4645 >>> a_list
4646 [np.uint32(1), np.uint32(2)]
4647 >>> type(a_list[0])
4648 <class 'numpy.uint32'>
4649 >>> a_tolist = a.tolist()
4650 >>> a_tolist
4651 [1, 2]
4652 >>> type(a_tolist[0])
4653 <class 'int'>
4654
4655 Additionally, for a 2D array, ``tolist`` applies recursively:
4656
4657 >>> a = np.array([[1, 2], [3, 4]])
4658 >>> list(a)
4659 [array([1, 2]), array([3, 4])]
4660 >>> a.tolist()
4661 [[1, 2], [3, 4]]
4662
4663 The base case for this recursion is a 0D array:
4664
4665 >>> a = np.array(1)
4666 >>> list(a)
4667 Traceback (most recent call last):
4668 ...
4669 TypeError: iteration over a 0-d array
4670 >>> a.tolist()
4671 1
4672 """)
4673
4674_array_method_doc('tobytes', "order='C'",
4675 """
4676 a.tobytes(order='C')
4677
4678 Construct Python bytes containing the raw data bytes in the array.
4679
4680 Constructs Python bytes showing a copy of the raw contents of
4681 data memory. The bytes object is produced in C-order by default.
4682 This behavior is controlled by the ``order`` parameter.
4683
4684 Parameters
4685 ----------
4686 order : {'C', 'F', 'A'}, optional
4687 Controls the memory layout of the bytes object. 'C' means C-order,
4688 'F' means F-order, 'A' (short for *Any*) means 'F' if `a` is
4689 Fortran contiguous, 'C' otherwise. Default is 'C'.
4690
4691 Returns
4692 -------
4693 s : bytes
4694 Python bytes exhibiting a copy of `a`'s raw data.
4695
4696 See also
4697 --------
4698 frombuffer
4699 Inverse of this operation, construct a 1-dimensional array from Python
4700 bytes.
4701
4702 Examples
4703 --------
4704 >>> import numpy as np
4705 >>> x = np.array([[0, 1], [2, 3]], dtype='<u2')
4706 >>> x.tobytes()
4707 b'\\x00\\x00\\x01\\x00\\x02\\x00\\x03\\x00'
4708 >>> x.tobytes('C') == x.tobytes()
4709 True
4710 >>> x.tobytes('F')
4711 b'\\x00\\x00\\x02\\x00\\x01\\x00\\x03\\x00'
4712 """)
4713
4714_array_method_doc('trace', "offset=0, axis1=0, axis2=1, dtype=None, out=None",
4715 """
4716 a.trace(offset=0, axis1=0, axis2=1, dtype=None, out=None)
4717
4718 Return the sum along diagonals of the array.
4719
4720 Refer to `numpy.trace` for full documentation.
4721
4722 See Also
4723 --------
4724 numpy.trace : equivalent function
4725 """)
4726
4727_array_method_doc('transpose', "*axes",
4728 """
4729 a.transpose(*axes)
4730
4731 Returns a view of the array with axes transposed.
4732
4733 Refer to `numpy.transpose` for full documentation.
4734
4735 Parameters
4736 ----------
4737 axes : None, tuple of ints, or `n` ints
4738
4739 * None or no argument: reverses the order of the axes.
4740
4741 * tuple of ints: `i` in the `j`-th place in the tuple means that the
4742 array's `i`-th axis becomes the transposed array's `j`-th axis.
4743
4744 * `n` ints: same as an n-tuple of the same ints (this form is
4745 intended simply as a "convenience" alternative to the tuple form).
4746
4747 Returns
4748 -------
4749 p : ndarray
4750 View of the array with its axes suitably permuted.
4751
4752 See Also
4753 --------
4754 transpose : Equivalent function.
4755 ndarray.T : Array property returning the array transposed.
4756 ndarray.reshape : Give a new shape to an array without changing its data.
4757
4758 Examples
4759 --------
4760 >>> import numpy as np
4761 >>> a = np.array([[1, 2], [3, 4]])
4762 >>> a
4763 array([[1, 2],
4764 [3, 4]])
4765 >>> a.transpose()
4766 array([[1, 3],
4767 [2, 4]])
4768 >>> a.transpose((1, 0))
4769 array([[1, 3],
4770 [2, 4]])
4771 >>> a.transpose(1, 0)
4772 array([[1, 3],
4773 [2, 4]])
4774
4775 >>> a = np.array([1, 2, 3, 4])
4776 >>> a
4777 array([1, 2, 3, 4])
4778 >>> a.transpose()
4779 array([1, 2, 3, 4])
4780 """)
4781
4782_array_method_doc('view', "*args, **kwargs",
4783 """
4784 a.view([dtype][, type])
4785
4786 New view of array with the same data.
4787
4788 .. note::
4789 Passing None for ``dtype`` is different from omitting the parameter,
4790 since the former invokes ``dtype(None)`` which is an alias for
4791 ``dtype('float64')``.
4792
4793 Parameters
4794 ----------
4795 dtype : data-type or ndarray sub-class, optional
4796 Data-type descriptor of the returned view, e.g., float32 or int16.
4797 Omitting it results in the view having the same data-type as `a`.
4798 This argument can also be specified as an ndarray sub-class, which
4799 then specifies the type of the returned object (this is equivalent to
4800 setting the ``type`` parameter).
4801 type : Python type, optional
4802 Type of the returned view, e.g., ndarray or matrix. Again, omission
4803 of the parameter results in type preservation.
4804
4805 Notes
4806 -----
4807 ``a.view()`` is used two different ways:
4808
4809 ``a.view(some_dtype)`` or ``a.view(dtype=some_dtype)`` constructs a view
4810 of the array's memory with a different data-type. This can cause a
4811 reinterpretation of the bytes of memory.
4812
4813 ``a.view(ndarray_subclass)`` or ``a.view(type=ndarray_subclass)`` just
4814 returns an instance of `ndarray_subclass` that looks at the same array
4815 (same shape, dtype, etc.) This does not cause a reinterpretation of the
4816 memory.
4817
4818 For ``a.view(some_dtype)``, if ``some_dtype`` has a different number of
4819 bytes per entry than the previous dtype (for example, converting a regular
4820 array to a structured array), then the last axis of ``a`` must be
4821 contiguous. This axis will be resized in the result.
4822
4823 .. versionchanged:: 1.23.0
4824 Only the last axis needs to be contiguous. Previously, the entire array
4825 had to be C-contiguous.
4826
4827 Examples
4828 --------
4829 >>> import numpy as np
4830 >>> x = np.array([(-1, 2)], dtype=[('a', np.int8), ('b', np.int8)])
4831
4832 Viewing array data using a different type and dtype:
4833
4834 >>> nonneg = np.dtype([("a", np.uint8), ("b", np.uint8)])
4835 >>> y = x.view(dtype=nonneg, type=np.recarray)
4836 >>> x["a"]
4837 array([-1], dtype=int8)
4838 >>> y.a
4839 array([255], dtype=uint8)
4840
4841 Creating a view on a structured array so it can be used in calculations
4842
4843 >>> x = np.array([(1, 2),(3,4)], dtype=[('a', np.int8), ('b', np.int8)])
4844 >>> xv = x.view(dtype=np.int8).reshape(-1,2)
4845 >>> xv
4846 array([[1, 2],
4847 [3, 4]], dtype=int8)
4848 >>> xv.mean(0)
4849 array([2., 3.])
4850
4851 Making changes to the view changes the underlying array
4852
4853 >>> xv[0,1] = 20
4854 >>> x
4855 array([(1, 20), (3, 4)], dtype=[('a', 'i1'), ('b', 'i1')])
4856
4857 Using a view to convert an array to a recarray:
4858
4859 >>> z = x.view(np.recarray)
4860 >>> z.a
4861 array([1, 3], dtype=int8)
4862
4863 Views share data:
4864
4865 >>> x[0] = (9, 10)
4866 >>> z[0]
4867 np.record((9, 10), dtype=[('a', 'i1'), ('b', 'i1')])
4868
4869 Views that change the dtype size (bytes per entry) should normally be
4870 avoided on arrays defined by slices, transposes, fortran-ordering, etc.:
4871
4872 >>> x = np.array([[1, 2, 3], [4, 5, 6]], dtype=np.int16)
4873 >>> y = x[:, ::2]
4874 >>> y
4875 array([[1, 3],
4876 [4, 6]], dtype=int16)
4877 >>> y.view(dtype=[('width', np.int16), ('length', np.int16)])
4878 Traceback (most recent call last):
4879 ...
4880 ValueError: To change to a dtype of a different size, the last axis must be contiguous
4881 >>> z = y.copy()
4882 >>> z.view(dtype=[('width', np.int16), ('length', np.int16)])
4883 array([[(1, 3)],
4884 [(4, 6)]], dtype=[('width', '<i2'), ('length', '<i2')])
4885
4886 However, views that change dtype are totally fine for arrays with a
4887 contiguous last axis, even if the rest of the axes are not C-contiguous:
4888
4889 >>> x = np.arange(2 * 3 * 4, dtype=np.int8).reshape(2, 3, 4)
4890 >>> x.transpose(1, 0, 2).view(np.int16)
4891 array([[[ 256, 770],
4892 [3340, 3854]],
4893 <BLANKLINE>
4894 [[1284, 1798],
4895 [4368, 4882]],
4896 <BLANKLINE>
4897 [[2312, 2826],
4898 [5396, 5910]]], dtype=int16)
4899 """)
4900
4901
4902##############################################################################
4903#
4904# umath functions
4905#
4906##############################################################################
4907
4908add_newdoc('numpy._core.umath', 'frompyfunc',
4909 """
4910 frompyfunc(func, /, nin, nout, **kwargs)
4911 --
4912
4913 frompyfunc(func, /, nin, nout, *[, identity])
4914
4915 Takes an arbitrary Python function and returns a NumPy ufunc.
4916
4917 Can be used, for example, to add broadcasting to a built-in Python
4918 function (see Examples section).
4919
4920 Parameters
4921 ----------
4922 func : Python function object
4923 An arbitrary Python function.
4924 nin : int
4925 The number of input arguments.
4926 nout : int
4927 The number of objects returned by `func`.
4928 identity : object, optional
4929 The value to use for the `~numpy.ufunc.identity` attribute of the resulting
4930 object. If specified, this is equivalent to setting the underlying
4931 C ``identity`` field to ``PyUFunc_IdentityValue``.
4932 If omitted, the identity is set to ``PyUFunc_None``. Note that this is
4933 _not_ equivalent to setting the identity to ``None``, which implies the
4934 operation is reorderable.
4935
4936 Returns
4937 -------
4938 out : ufunc
4939 Returns a NumPy universal function (``ufunc``) object.
4940
4941 See Also
4942 --------
4943 vectorize : Evaluates pyfunc over input arrays using broadcasting rules of numpy.
4944
4945 Notes
4946 -----
4947 The returned ufunc always returns PyObject arrays.
4948
4949 Examples
4950 --------
4951 Use frompyfunc to add broadcasting to the Python function ``oct``:
4952
4953 >>> import numpy as np
4954 >>> oct_array = np.frompyfunc(oct, 1, 1)
4955 >>> oct_array(np.array((10, 30, 100)))
4956 array(['0o12', '0o36', '0o144'], dtype=object)
4957 >>> np.array((oct(10), oct(30), oct(100))) # for comparison
4958 array(['0o12', '0o36', '0o144'], dtype='<U5')
4959
4960 """)
4961
4962
4963##############################################################################
4964#
4965# compiled_base functions
4966#
4967##############################################################################
4968
4969add_newdoc('numpy._core.multiarray', 'add_docstring',
4970 """
4971 add_docstring(obj, docstring)
4972
4973 Add a docstring to a built-in obj if possible.
4974 If the obj already has a docstring raise a RuntimeError
4975 If this routine does not know how to add a docstring to the object
4976 raise a TypeError
4977 """)
4978
4979add_newdoc('numpy._core.umath', '_add_newdoc_ufunc',
4980 """
4981 add_ufunc_docstring(ufunc, new_docstring)
4982
4983 Replace the docstring for a ufunc with new_docstring.
4984 This method will only work if the current docstring for
4985 the ufunc is NULL. (At the C level, i.e. when ufunc->doc is NULL.)
4986
4987 Parameters
4988 ----------
4989 ufunc : numpy.ufunc
4990 A ufunc whose current doc is NULL.
4991 new_docstring : string
4992 The new docstring for the ufunc.
4993
4994 Notes
4995 -----
4996 This method allocates memory for new_docstring on
4997 the heap. Technically this creates a memory leak, since this
4998 memory will not be reclaimed until the end of the program
4999 even if the ufunc itself is removed. However this will only
5000 be a problem if the user is repeatedly creating ufuncs with
5001 no documentation, adding documentation via add_newdoc_ufunc,
5002 and then throwing away the ufunc.
5003 """)
5004
5005add_newdoc('numpy._core.multiarray', 'get_handler_name',
5006 """
5007 get_handler_name(a: ndarray) -> str | None
5008
5009 Return the name of the memory handler used by `a`. If not provided, return
5010 the name of the memory handler that will be used to allocate data for the
5011 next `ndarray` in this context. May return None if `a` does not own its
5012 memory, in which case you can traverse ``a.base`` for a memory handler.
5013 """)
5014
5015add_newdoc('numpy._core.multiarray', 'get_handler_version',
5016 """
5017 get_handler_version(a: ndarray) -> int,None
5018
5019 Return the version of the memory handler used by `a`. If not provided,
5020 return the version of the memory handler that will be used to allocate data
5021 for the next `ndarray` in this context. May return None if `a` does not own
5022 its memory, in which case you can traverse ``a.base`` for a memory handler.
5023 """)
5024
5025add_newdoc('numpy._core._multiarray_umath', '_array_converter',
5026 """
5027 _array_converter(*array_likes)
5028
5029 Helper to convert one or more objects to arrays. Integrates machinery
5030 to deal with the ``result_type`` and ``__array_wrap__``.
5031
5032 The reason for this is that e.g. ``result_type`` needs to convert to arrays
5033 to find the ``dtype``. But converting to an array before calling
5034 ``result_type`` would incorrectly "forget" whether it was a Python int,
5035 float, or complex.
5036 """)
5037
5038add_newdoc(
5039 'numpy._core._multiarray_umath', '_array_converter', ('scalar_input',
5040 """
5041 A tuple which indicates for each input whether it was a scalar that
5042 was coerced to a 0-D array (and was not already an array or something
5043 converted via a protocol like ``__array__()``).
5044 """))
5045
5046add_newdoc('numpy._core._multiarray_umath', '_array_converter', ('as_arrays',
5047 """
5048 as_arrays(/, subok=True, pyscalars="convert_if_no_array")
5049
5050 Return the inputs as arrays or scalars.
5051
5052 Parameters
5053 ----------
5054 subok : True or False, optional
5055 Whether array subclasses are preserved.
5056 pyscalars : {"convert", "preserve", "convert_if_no_array"}, optional
5057 To allow NEP 50 weak promotion later, it may be desirable to preserve
5058 Python scalars. As default, these are preserved unless all inputs
5059 are Python scalars. "convert" enforces an array return.
5060 """))
5061
5062add_newdoc('numpy._core._multiarray_umath', '_array_converter', ('result_type',
5063 """result_type(/, extra_dtype=None, ensure_inexact=False)
5064
5065 Find the ``result_type`` just as ``np.result_type`` would, but taking
5066 into account that the original inputs (before converting to an array) may
5067 have been Python scalars with weak promotion.
5068
5069 Parameters
5070 ----------
5071 extra_dtype : dtype instance or class
5072 An additional DType or dtype instance to promote (e.g. could be used
5073 to ensure the result precision is at least float32).
5074 ensure_inexact : True or False
5075 When ``True``, ensures a floating point (or complex) result replacing
5076 the ``arr * 1.`` or ``result_type(..., 0.0)`` pattern.
5077 """))
5078
5079add_newdoc('numpy._core._multiarray_umath', '_array_converter', ('wrap',
5080 """
5081 wrap(arr, /, to_scalar=None)
5082
5083 Call ``__array_wrap__`` on ``arr`` if ``arr`` is not the same subclass
5084 as the input the ``__array_wrap__`` method was retrieved from.
5085
5086 Parameters
5087 ----------
5088 arr : ndarray
5089 The object to be wrapped. Normally an ndarray or subclass,
5090 although for backward compatibility NumPy scalars are also accepted
5091 (these will be converted to a NumPy array before being passed on to
5092 the ``__array_wrap__`` method).
5093 to_scalar : {True, False, None}, optional
5094 When ``True`` will convert a 0-d array to a scalar via ``result[()]``
5095 (with a fast-path for non-subclasses). If ``False`` the result should
5096 be an array-like (as ``__array_wrap__`` is free to return a non-array).
5097 By default (``None``), a scalar is returned if all inputs were scalar.
5098 """))
5099
5100
5101add_newdoc('numpy._core.multiarray', '_get_madvise_hugepage',
5102 """
5103 _get_madvise_hugepage() -> bool
5104
5105 Get use of ``madvise (2)`` MADV_HUGEPAGE support when
5106 allocating the array data. Returns the currently set value.
5107 See `global_state` for more information.
5108 """)
5109
5110add_newdoc('numpy._core.multiarray', '_set_madvise_hugepage',
5111 """
5112 _set_madvise_hugepage(enabled: bool) -> bool
5113
5114 Set or unset use of ``madvise (2)`` MADV_HUGEPAGE support when
5115 allocating the array data. Returns the previously set value.
5116 See `global_state` for more information.
5117 """)
5118
5119
5120##############################################################################
5121#
5122# Documentation for ufunc attributes and methods
5123#
5124##############################################################################
5125
5126
5127##############################################################################
5128#
5129# ufunc object
5130#
5131##############################################################################
5132
5133add_newdoc('numpy._core', 'ufunc',
5134 """
5135 Functions that operate element by element on whole arrays.
5136
5137 To see the documentation for a specific ufunc, use `info`. For
5138 example, ``np.info(np.sin)``. Because ufuncs are written in C
5139 (for speed) and linked into Python with NumPy's ufunc facility,
5140 Python's help() function finds this page whenever help() is called
5141 on a ufunc.
5142
5143 A detailed explanation of ufuncs can be found in the docs for :ref:`ufuncs`.
5144
5145 **Calling ufuncs:** ``op(*x[, out], where=True, **kwargs)``
5146
5147 Apply `op` to the arguments `*x` elementwise, broadcasting the arguments.
5148
5149 The broadcasting rules are:
5150
5151 * Dimensions of length 1 may be prepended to either array.
5152 * Arrays may be repeated along dimensions of length 1.
5153
5154 Parameters
5155 ----------
5156 *x : array_like
5157 Input arrays.
5158 out : ndarray, None, ..., or tuple of ndarray and None, optional
5159 Location(s) into which the result(s) are stored.
5160 If not provided or None, new array(s) are created by the ufunc.
5161 If passed as a keyword argument, can be Ellipses (``out=...``) to
5162 ensure an array is returned even if the result is 0-dimensional,
5163 or a tuple with length equal to the number of outputs (where None
5164 can be used for allocation by the ufunc).
5165
5166 .. versionadded:: 2.3
5167 Support for ``out=...`` was added.
5168
5169 where : array_like, optional
5170 This condition is broadcast over the input. At locations where the
5171 condition is True, the `out` array will be set to the ufunc result.
5172 Elsewhere, the `out` array will retain its original value.
5173 Note that if an uninitialized `out` array is created via the default
5174 ``out=None``, locations within it where the condition is False will
5175 remain uninitialized.
5176 **kwargs
5177 For other keyword-only arguments, see the :ref:`ufunc docs <ufuncs.kwargs>`.
5178
5179 Returns
5180 -------
5181 r : ndarray or tuple of ndarray
5182 `r` will have the shape that the arrays in `x` broadcast to; if `out` is
5183 provided, it will be returned. If not, `r` will be allocated and
5184 may contain uninitialized values. If the function has more than one
5185 output, then the result will be a tuple of arrays.
5186
5187 """)
5188
5189
5190##############################################################################
5191#
5192# ufunc attributes
5193#
5194##############################################################################
5195
5196add_newdoc('numpy._core', 'ufunc', ('identity',
5197 """
5198 The identity value.
5199
5200 Data attribute containing the identity element for the ufunc,
5201 if it has one. If it does not, the attribute value is None.
5202
5203 Examples
5204 --------
5205 >>> import numpy as np
5206 >>> np.add.identity
5207 0
5208 >>> np.multiply.identity
5209 1
5210 >>> print(np.power.identity)
5211 None
5212 >>> print(np.exp.identity)
5213 None
5214 """))
5215
5216add_newdoc('numpy._core', 'ufunc', ('nargs',
5217 """
5218 The number of arguments.
5219
5220 Data attribute containing the number of arguments the ufunc takes, including
5221 optional ones.
5222
5223 Notes
5224 -----
5225 Typically this value will be one more than what you might expect
5226 because all ufuncs take the optional "out" argument.
5227
5228 Examples
5229 --------
5230 >>> import numpy as np
5231 >>> np.add.nargs
5232 3
5233 >>> np.multiply.nargs
5234 3
5235 >>> np.power.nargs
5236 3
5237 >>> np.exp.nargs
5238 2
5239 """))
5240
5241add_newdoc('numpy._core', 'ufunc', ('nin',
5242 """
5243 The number of inputs.
5244
5245 Data attribute containing the number of arguments the ufunc treats as input.
5246
5247 Examples
5248 --------
5249 >>> import numpy as np
5250 >>> np.add.nin
5251 2
5252 >>> np.multiply.nin
5253 2
5254 >>> np.power.nin
5255 2
5256 >>> np.exp.nin
5257 1
5258 """))
5259
5260add_newdoc('numpy._core', 'ufunc', ('nout',
5261 """
5262 The number of outputs.
5263
5264 Data attribute containing the number of arguments the ufunc treats as output.
5265
5266 Notes
5267 -----
5268 Since all ufuncs can take output arguments, this will always be at least 1.
5269
5270 Examples
5271 --------
5272 >>> import numpy as np
5273 >>> np.add.nout
5274 1
5275 >>> np.multiply.nout
5276 1
5277 >>> np.power.nout
5278 1
5279 >>> np.exp.nout
5280 1
5281
5282 """))
5283
5284add_newdoc('numpy._core', 'ufunc', ('ntypes',
5285 """
5286 The number of types.
5287
5288 The number of numerical NumPy types - of which there are 18 total - on which
5289 the ufunc can operate.
5290
5291 See Also
5292 --------
5293 numpy.ufunc.types
5294
5295 Examples
5296 --------
5297 >>> import numpy as np
5298 >>> np.add.ntypes
5299 22
5300 >>> np.multiply.ntypes
5301 23
5302 >>> np.power.ntypes
5303 21
5304 >>> np.exp.ntypes
5305 10
5306 >>> np.remainder.ntypes
5307 16
5308
5309 """))
5310
5311add_newdoc('numpy._core', 'ufunc', ('types',
5312 """
5313 Returns a list with types grouped input->output.
5314
5315 Data attribute listing the data-type "Domain-Range" groupings the ufunc can
5316 deliver. The data-types are given using the character codes.
5317
5318 See Also
5319 --------
5320 numpy.ufunc.ntypes
5321
5322 Examples
5323 --------
5324 >>> import numpy as np
5325 >>> np.add.types
5326 ['??->?', 'bb->b', 'BB->B', 'hh->h', 'HH->H', 'ii->i', 'II->I', ...
5327
5328 >>> np.power.types
5329 ['bb->b', 'BB->B', 'hh->h', 'HH->H', 'ii->i', 'II->I', 'll->l', ...
5330
5331 >>> np.exp.types
5332 ['e->e', 'f->f', 'd->d', 'f->f', 'd->d', 'g->g', 'F->F', 'D->D', 'G->G', 'O->O']
5333
5334 >>> np.remainder.types
5335 ['bb->b', 'BB->B', 'hh->h', 'HH->H', 'ii->i', 'II->I', 'll->l', ...
5336
5337 """))
5338
5339add_newdoc('numpy._core', 'ufunc', ('signature',
5340 """
5341 Definition of the core elements a generalized ufunc operates on.
5342
5343 The signature determines how the dimensions of each input/output array
5344 are split into core and loop dimensions:
5345
5346 1. Each dimension in the signature is matched to a dimension of the
5347 corresponding passed-in array, starting from the end of the shape tuple.
5348 2. Core dimensions assigned to the same label in the signature must have
5349 exactly matching sizes, no broadcasting is performed.
5350 3. The core dimensions are removed from all inputs and the remaining
5351 dimensions are broadcast together, defining the loop dimensions.
5352
5353 Notes
5354 -----
5355 Generalized ufuncs are used internally in many linalg functions, and in
5356 the testing suite; the examples below are taken from these.
5357 For ufuncs that operate on scalars, the signature is None, which is
5358 equivalent to '()' for every argument.
5359
5360 Examples
5361 --------
5362 >>> import numpy as np
5363 >>> np.linalg._umath_linalg.det.signature
5364 '(m,m)->()'
5365 >>> np.matmul.signature
5366 '(n?,k),(k,m?)->(n?,m?)'
5367 >>> np.add.signature is None
5368 True # equivalent to '(),()->()'
5369 """))
5370
5371##############################################################################
5372#
5373# ufunc methods
5374#
5375##############################################################################
5376
5377add_newdoc('numpy._core', 'ufunc', ('reduce',
5378 """
5379 reduce($self, array, /, axis=0, dtype=None, out=None, **kwargs)
5380 --
5381
5382 reduce(array, axis=0, dtype=None, out=None, keepdims=False, initial=<no value>, where=True)
5383
5384 Reduces `array`'s dimension by one, by applying ufunc along one axis.
5385
5386 Let :math:`array.shape = (N_0, ..., N_i, ..., N_{M-1})`. Then
5387 :math:`ufunc.reduce(array, axis=i)[k_0, ..,k_{i-1}, k_{i+1}, .., k_{M-1}]` =
5388 the result of iterating `j` over :math:`range(N_i)`, cumulatively applying
5389 ufunc to each :math:`array[k_0, ..,k_{i-1}, j, k_{i+1}, .., k_{M-1}]`.
5390 For a one-dimensional array, reduce produces results equivalent to:
5391 ::
5392
5393 r = op.identity # op = ufunc
5394 for i in range(len(A)):
5395 r = op(r, A[i])
5396 return r
5397
5398 For example, add.reduce() is equivalent to sum().
5399
5400 Parameters
5401 ----------
5402 array : array_like
5403 The array to act on.
5404 axis : None or int or tuple of ints, optional
5405 Axis or axes along which a reduction is performed.
5406 The default (`axis` = 0) is perform a reduction over the first
5407 dimension of the input array. `axis` may be negative, in
5408 which case it counts from the last to the first axis.
5409
5410 If this is None, a reduction is performed over all the axes.
5411 If this is a tuple of ints, a reduction is performed on multiple
5412 axes, instead of a single axis or all the axes as before.
5413
5414 For operations which are either not commutative or not associative,
5415 doing a reduction over multiple axes is not well-defined. The
5416 ufuncs do not currently raise an exception in this case, but will
5417 likely do so in the future.
5418 dtype : data-type code, optional
5419 The data type used to perform the operation. Defaults to that of
5420 ``out`` if given, and the data type of ``array`` otherwise (though
5421 upcast to conserve precision for some cases, such as
5422 ``numpy.add.reduce`` for integer or boolean input).
5423 out : ndarray, None, ..., or tuple of ndarray and None, optional
5424 Location into which the result is stored.
5425 If not provided or None, a freshly-allocated array is returned.
5426 If passed as a keyword argument, can be Ellipses (``out=...``) to
5427 ensure an array is returned even if the result is 0-dimensional
5428 (which is useful especially for object dtype), or a 1-element tuple
5429 (latter for consistency with ``ufunc.__call__``).
5430
5431 .. versionadded:: 2.3
5432 Support for ``out=...`` was added.
5433
5434 keepdims : bool, optional
5435 If this is set to True, the axes which are reduced are left
5436 in the result as dimensions with size one. With this option,
5437 the result will broadcast correctly against the original `array`.
5438 initial : scalar, optional
5439 The value with which to start the reduction.
5440 If the ufunc has no identity or the dtype is object, this defaults
5441 to None - otherwise it defaults to ufunc.identity.
5442 If ``None`` is given, the first element of the reduction is used,
5443 and an error is thrown if the reduction is empty.
5444 where : array_like of bool, optional
5445 A boolean array which is broadcasted to match the dimensions
5446 of `array`, and selects elements to include in the reduction. Note
5447 that for ufuncs like ``minimum`` that do not have an identity
5448 defined, one has to pass in also ``initial``.
5449
5450 Returns
5451 -------
5452 r : ndarray
5453 The reduced array. If `out` was supplied, `r` is a reference to it.
5454
5455 Examples
5456 --------
5457 >>> import numpy as np
5458 >>> np.multiply.reduce([2,3,5])
5459 30
5460
5461 A multi-dimensional array example:
5462
5463 >>> X = np.arange(8).reshape((2,2,2))
5464 >>> X
5465 array([[[0, 1],
5466 [2, 3]],
5467 [[4, 5],
5468 [6, 7]]])
5469 >>> np.add.reduce(X, 0)
5470 array([[ 4, 6],
5471 [ 8, 10]])
5472 >>> np.add.reduce(X) # confirm: default axis value is 0
5473 array([[ 4, 6],
5474 [ 8, 10]])
5475 >>> np.add.reduce(X, 1)
5476 array([[ 2, 4],
5477 [10, 12]])
5478 >>> np.add.reduce(X, 2)
5479 array([[ 1, 5],
5480 [ 9, 13]])
5481
5482 You can use the ``initial`` keyword argument to initialize the reduction
5483 with a different value, and ``where`` to select specific elements to include:
5484
5485 >>> np.add.reduce([10], initial=5)
5486 15
5487 >>> np.add.reduce(np.ones((2, 2, 2)), axis=(0, 2), initial=10)
5488 array([14., 14.])
5489 >>> a = np.array([10., np.nan, 10])
5490 >>> np.add.reduce(a, where=~np.isnan(a))
5491 20.0
5492
5493 Allows reductions of empty arrays where they would normally fail, i.e.
5494 for ufuncs without an identity.
5495
5496 >>> np.minimum.reduce([], initial=np.inf)
5497 inf
5498 >>> np.minimum.reduce([[1., 2.], [3., 4.]], initial=10., where=[True, False])
5499 array([ 1., 10.])
5500 >>> np.minimum.reduce([])
5501 Traceback (most recent call last):
5502 ...
5503 ValueError: zero-size array to reduction operation minimum which has no identity
5504 """))
5505
5506add_newdoc('numpy._core', 'ufunc', ('accumulate',
5507 """
5508 accumulate($self, array, /, axis=0, dtype=None, out=None)
5509 --
5510
5511 accumulate(array, axis=0, dtype=None, out=None)
5512
5513 Accumulate the result of applying the operator to all elements.
5514
5515 For a one-dimensional array, accumulate produces results equivalent to::
5516
5517 r = np.empty(len(A))
5518 t = op.identity # op = the ufunc being applied to A's elements
5519 for i in range(len(A)):
5520 t = op(t, A[i])
5521 r[i] = t
5522 return r
5523
5524 For example, add.accumulate() is equivalent to np.cumsum().
5525
5526 For a multi-dimensional array, accumulate is applied along only one
5527 axis (axis zero by default; see Examples below) so repeated use is
5528 necessary if one wants to accumulate over multiple axes.
5529
5530 Parameters
5531 ----------
5532 array : array_like
5533 The array to act on.
5534 axis : int, optional
5535 The axis along which to apply the accumulation; default is zero.
5536 dtype : data-type code, optional
5537 The data-type used to represent the intermediate results. Defaults
5538 to the data-type of the output array if such is provided, or the
5539 data-type of the input array if no output array is provided.
5540 out : ndarray, None, or tuple of ndarray and None, optional
5541 Location into which the result is stored.
5542 If not provided or None, a freshly-allocated array is returned.
5543 For consistency with ``ufunc.__call__``, if passed as a keyword
5544 argument, can be Ellipses (``out=...``, which has the same effect
5545 as None as an array is always returned), or a 1-element tuple.
5546
5547 Returns
5548 -------
5549 r : ndarray
5550 The accumulated values. If `out` was supplied, `r` is a reference to
5551 `out`.
5552
5553 Examples
5554 --------
5555 1-D array examples:
5556
5557 >>> import numpy as np
5558 >>> np.add.accumulate([2, 3, 5])
5559 array([ 2, 5, 10])
5560 >>> np.multiply.accumulate([2, 3, 5])
5561 array([ 2, 6, 30])
5562
5563 2-D array examples:
5564
5565 >>> I = np.eye(2)
5566 >>> I
5567 array([[1., 0.],
5568 [0., 1.]])
5569
5570 Accumulate along axis 0 (rows), down columns:
5571
5572 >>> np.add.accumulate(I, 0)
5573 array([[1., 0.],
5574 [1., 1.]])
5575 >>> np.add.accumulate(I) # no axis specified = axis zero
5576 array([[1., 0.],
5577 [1., 1.]])
5578
5579 Accumulate along axis 1 (columns), through rows:
5580
5581 >>> np.add.accumulate(I, 1)
5582 array([[1., 1.],
5583 [0., 1.]])
5584
5585 """))
5586
5587add_newdoc('numpy._core', 'ufunc', ('reduceat',
5588 """
5589 reduceat($self, array, /, indices, axis=0, dtype=None, out=None)
5590 --
5591
5592 reduceat(array, indices, axis=0, dtype=None, out=None)
5593
5594 Performs a (local) reduce with specified slices over a single axis.
5595
5596 For i in ``range(len(indices))``, `reduceat` computes
5597 ``ufunc.reduce(array[indices[i]:indices[i+1]])``, which becomes the i-th
5598 generalized "row" parallel to `axis` in the final result (i.e., in a
5599 2-D array, for example, if `axis = 0`, it becomes the i-th row, but if
5600 `axis = 1`, it becomes the i-th column). There are three exceptions to this:
5601
5602 * when ``i = len(indices) - 1`` (so for the last index),
5603 ``indices[i+1] = array.shape[axis]``.
5604 * if ``indices[i] >= indices[i + 1]``, the i-th generalized "row" is
5605 simply ``array[indices[i]]``.
5606 * if ``indices[i] >= len(array)`` or ``indices[i] < 0``, an error is raised.
5607
5608 The shape of the output depends on the size of `indices`, and may be
5609 larger than `array` (this happens if ``len(indices) > array.shape[axis]``).
5610
5611 Parameters
5612 ----------
5613 array : array_like
5614 The array to act on.
5615 indices : array_like
5616 Paired indices, comma separated (not colon), specifying slices to
5617 reduce.
5618 axis : int, optional
5619 The axis along which to apply the reduceat.
5620 dtype : data-type code, optional
5621 The data type used to perform the operation. Defaults to that of
5622 ``out`` if given, and the data type of ``array`` otherwise (though
5623 upcast to conserve precision for some cases, such as
5624 ``numpy.add.reduce`` for integer or boolean input).
5625 out : ndarray, None, or tuple of ndarray and None, optional
5626 Location into which the result is stored.
5627 If not provided or None, a freshly-allocated array is returned.
5628 For consistency with ``ufunc.__call__``, if passed as a keyword
5629 argument, can be Ellipses (``out=...``, which has the same effect
5630 as None as an array is always returned), or a 1-element tuple.
5631
5632 Returns
5633 -------
5634 r : ndarray
5635 The reduced values. If `out` was supplied, `r` is a reference to
5636 `out`.
5637
5638 Notes
5639 -----
5640 A descriptive example:
5641
5642 If `array` is 1-D, the function `ufunc.accumulate(array)` is the same as
5643 ``ufunc.reduceat(array, indices)[::2]`` where `indices` is
5644 ``range(len(array) - 1)`` with a zero placed
5645 in every other element:
5646 ``indices = zeros(2 * len(array) - 1)``,
5647 ``indices[1::2] = range(1, len(array))``.
5648
5649 Don't be fooled by this attribute's name: `reduceat(array)` is not
5650 necessarily smaller than `array`.
5651
5652 Examples
5653 --------
5654 To take the running sum of four successive values:
5655
5656 >>> import numpy as np
5657 >>> np.add.reduceat(np.arange(8),[0,4, 1,5, 2,6, 3,7])[::2]
5658 array([ 6, 10, 14, 18])
5659
5660 A 2-D example:
5661
5662 >>> x = np.linspace(0, 15, 16).reshape(4,4)
5663 >>> x
5664 array([[ 0., 1., 2., 3.],
5665 [ 4., 5., 6., 7.],
5666 [ 8., 9., 10., 11.],
5667 [12., 13., 14., 15.]])
5668
5669 ::
5670
5671 # reduce such that the result has the following five rows:
5672 # [row1 + row2 + row3]
5673 # [row4]
5674 # [row2]
5675 # [row3]
5676 # [row1 + row2 + row3 + row4]
5677
5678 >>> np.add.reduceat(x, [0, 3, 1, 2, 0])
5679 array([[12., 15., 18., 21.],
5680 [12., 13., 14., 15.],
5681 [ 4., 5., 6., 7.],
5682 [ 8., 9., 10., 11.],
5683 [24., 28., 32., 36.]])
5684
5685 ::
5686
5687 # reduce such that result has the following two columns:
5688 # [col1 * col2 * col3, col4]
5689
5690 >>> np.multiply.reduceat(x, [0, 3], 1)
5691 array([[ 0., 3.],
5692 [ 120., 7.],
5693 [ 720., 11.],
5694 [2184., 15.]])
5695
5696 """))
5697
5698add_newdoc('numpy._core', 'ufunc', ('outer',
5699 r"""
5700 outer($self, A, B, /, **kwargs)
5701 --
5702
5703 outer(A, B, /, **kwargs)
5704
5705 Apply the ufunc `op` to all pairs (a, b) with a in `A` and b in `B`.
5706
5707 Let ``M = A.ndim``, ``N = B.ndim``. Then the result, `C`, of
5708 ``op.outer(A, B)`` is an array of dimension M + N such that:
5709
5710 .. math:: C[i_0, ..., i_{M-1}, j_0, ..., j_{N-1}] =
5711 op(A[i_0, ..., i_{M-1}], B[j_0, ..., j_{N-1}])
5712
5713 For `A` and `B` one-dimensional, this is equivalent to::
5714
5715 r = empty(len(A),len(B))
5716 for i in range(len(A)):
5717 for j in range(len(B)):
5718 r[i,j] = op(A[i], B[j]) # op = ufunc in question
5719
5720 Parameters
5721 ----------
5722 A : array_like
5723 First array
5724 B : array_like
5725 Second array
5726 kwargs : any
5727 Arguments to pass on to the ufunc. Typically `dtype` or `out`.
5728 See `ufunc` for a comprehensive overview of all available arguments.
5729
5730 Returns
5731 -------
5732 r : ndarray
5733 Output array
5734
5735 See Also
5736 --------
5737 numpy.outer : A less powerful version of ``np.multiply.outer``
5738 that `ravel`\ s all inputs to 1D. This exists
5739 primarily for compatibility with old code.
5740
5741 tensordot : ``np.tensordot(a, b, axes=((), ()))`` and
5742 ``np.multiply.outer(a, b)`` behave same for all
5743 dimensions of a and b.
5744
5745 Examples
5746 --------
5747 >>> np.multiply.outer([1, 2, 3], [4, 5, 6])
5748 array([[ 4, 5, 6],
5749 [ 8, 10, 12],
5750 [12, 15, 18]])
5751
5752 A multi-dimensional example:
5753
5754 >>> A = np.array([[1, 2, 3], [4, 5, 6]])
5755 >>> A.shape
5756 (2, 3)
5757 >>> B = np.array([[1, 2, 3, 4]])
5758 >>> B.shape
5759 (1, 4)
5760 >>> C = np.multiply.outer(A, B)
5761 >>> C.shape; C
5762 (2, 3, 1, 4)
5763 array([[[[ 1, 2, 3, 4]],
5764 [[ 2, 4, 6, 8]],
5765 [[ 3, 6, 9, 12]]],
5766 [[[ 4, 8, 12, 16]],
5767 [[ 5, 10, 15, 20]],
5768 [[ 6, 12, 18, 24]]]])
5769
5770 """))
5771
5772add_newdoc('numpy._core', 'ufunc', ('at',
5773 """
5774 at($self, a, indices, b=None, /)
5775 --
5776
5777 at(a, indices, b=None, /)
5778
5779 Performs unbuffered in place operation on operand 'a' for elements
5780 specified by 'indices'. For addition ufunc, this method is equivalent to
5781 ``a[indices] += b``, except that results are accumulated for elements that
5782 are indexed more than once. For example, ``a[[0,0]] += 1`` will only
5783 increment the first element once because of buffering, whereas
5784 ``add.at(a, [0,0], 1)`` will increment the first element twice.
5785
5786 Parameters
5787 ----------
5788 a : array_like
5789 The array to perform in place operation on.
5790 indices : array_like or tuple
5791 Array like index object or slice object for indexing into first
5792 operand. If first operand has multiple dimensions, indices can be a
5793 tuple of array like index objects or slice objects.
5794 b : array_like
5795 Second operand for ufuncs requiring two operands. Operand must be
5796 broadcastable over first operand after indexing or slicing.
5797
5798 Examples
5799 --------
5800 Set items 0 and 1 to their negative values:
5801
5802 >>> import numpy as np
5803 >>> a = np.array([1, 2, 3, 4])
5804 >>> np.negative.at(a, [0, 1])
5805 >>> a
5806 array([-1, -2, 3, 4])
5807
5808 Increment items 0 and 1, and increment item 2 twice:
5809
5810 >>> a = np.array([1, 2, 3, 4])
5811 >>> np.add.at(a, [0, 1, 2, 2], 1)
5812 >>> a
5813 array([2, 3, 5, 4])
5814
5815 Add items 0 and 1 in first array to second array,
5816 and store results in first array:
5817
5818 >>> a = np.array([1, 2, 3, 4])
5819 >>> b = np.array([1, 2])
5820 >>> np.add.at(a, [0, 1], b)
5821 >>> a
5822 array([2, 4, 3, 4])
5823
5824 """))
5825
5826add_newdoc('numpy._core', 'ufunc', ('resolve_dtypes',
5827 """
5828 resolve_dtypes($self, dtypes, *, signature=None, casting=None, reduction=False)
5829 --
5830
5831 resolve_dtypes(dtypes, *, signature=None, casting=None, reduction=False)
5832
5833 Find the dtypes NumPy will use for the operation. Both input and
5834 output dtypes are returned and may differ from those provided.
5835
5836 .. note::
5837
5838 This function always applies NEP 50 rules since it is not provided
5839 any actual values. The Python types ``int``, ``float``, and
5840 ``complex`` thus behave weak and should be passed for "untyped"
5841 Python input.
5842
5843 Parameters
5844 ----------
5845 dtypes : tuple of dtypes, None, or literal int, float, complex
5846 The input dtypes for each operand. Output operands can be
5847 None, indicating that the dtype must be found.
5848 signature : tuple of DTypes or None, optional
5849 If given, enforces exact DType (classes) of the specific operand.
5850 The ufunc ``dtype`` argument is equivalent to passing a tuple with
5851 only output dtypes set.
5852 casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional
5853 The casting mode when casting is necessary. This is identical to
5854 the ufunc call casting modes.
5855 reduction : boolean
5856 If given, the resolution assumes a reduce operation is happening
5857 which slightly changes the promotion and type resolution rules.
5858 `dtypes` is usually something like ``(None, np.dtype("i2"), None)``
5859 for reductions (first input is also the output).
5860
5861 .. note::
5862
5863 The default casting mode is "same_kind", however, as of
5864 NumPy 1.24, NumPy uses "unsafe" for reductions.
5865
5866 Returns
5867 -------
5868 dtypes : tuple of dtypes
5869 The dtypes which NumPy would use for the calculation. Note that
5870 dtypes may not match the passed in ones (casting is necessary).
5871
5872
5873 Examples
5874 --------
5875 This API requires passing dtypes, define them for convenience:
5876
5877 >>> import numpy as np
5878 >>> int32 = np.dtype("int32")
5879 >>> float32 = np.dtype("float32")
5880
5881 The typical ufunc call does not pass an output dtype. `numpy.add` has two
5882 inputs and one output, so leave the output as ``None`` (not provided):
5883
5884 >>> np.add.resolve_dtypes((int32, float32, None))
5885 (dtype('float64'), dtype('float64'), dtype('float64'))
5886
5887 The loop found uses "float64" for all operands (including the output), the
5888 first input would be cast.
5889
5890 ``resolve_dtypes`` supports "weak" handling for Python scalars by passing
5891 ``int``, ``float``, or ``complex``:
5892
5893 >>> np.add.resolve_dtypes((float32, float, None))
5894 (dtype('float32'), dtype('float32'), dtype('float32'))
5895
5896 Where the Python ``float`` behaves similar to a Python value ``0.0``
5897 in a ufunc call. (See :ref:`NEP 50 <NEP50>` for details.)
5898
5899 """))
5900
5901add_newdoc('numpy._core', 'ufunc', ('_resolve_dtypes_and_context',
5902 """
5903 _resolve_dtypes_and_context($self, dtypes, *, signature=None, casting=None, reduction=False)
5904 --
5905
5906 _resolve_dtypes_and_context(dtypes, *, signature=None, casting=None, reduction=False)
5907
5908 See `numpy.ufunc.resolve_dtypes` for parameter information. This
5909 function is considered *unstable*. You may use it, but the returned
5910 information is NumPy version specific and expected to change.
5911 Large API/ABI changes are not expected, but a new NumPy version is
5912 expected to require updating code using this functionality.
5913
5914 This function is designed to be used in conjunction with
5915 `numpy.ufunc._get_strided_loop`. The calls are split to mirror the C API
5916 and allow future improvements.
5917
5918 Returns
5919 -------
5920 dtypes : tuple of dtypes
5921 call_info :
5922 PyCapsule with all necessary information to get access to low level
5923 C calls. See `numpy.ufunc._get_strided_loop` for more information.
5924
5925 """))
5926
5927add_newdoc('numpy._core', 'ufunc', ('_get_strided_loop',
5928 """
5929 _get_strided_loop($self, call_info, /, *, fixed_strides=None)
5930 --
5931
5932 _get_strided_loop(call_info, /, *, fixed_strides=None)
5933
5934 This function fills in the ``call_info`` capsule to include all
5935 information necessary to call the low-level strided loop from NumPy.
5936
5937 See notes for more information.
5938
5939 Parameters
5940 ----------
5941 call_info : PyCapsule
5942 The PyCapsule returned by `numpy.ufunc._resolve_dtypes_and_context`.
5943 fixed_strides : tuple of int or None, optional
5944 A tuple with fixed byte strides of all input arrays. NumPy may use
5945 this information to find specialized loops, so any call must follow
5946 the given stride. Use ``None`` to indicate that the stride is not
5947 known (or not fixed) for all calls.
5948
5949 Notes
5950 -----
5951 Together with `numpy.ufunc._resolve_dtypes_and_context` this function
5952 gives low-level access to the NumPy ufunc loops.
5953 The first function does general preparation and returns the required
5954 information. It returns this as a C capsule with the version specific
5955 name ``numpy_1.24_ufunc_call_info``.
5956 The NumPy 1.24 ufunc call info capsule has the following layout::
5957
5958 typedef struct {
5959 PyArrayMethod_StridedLoop *strided_loop;
5960 PyArrayMethod_Context *context;
5961 NpyAuxData *auxdata;
5962
5963 /* Flag information (expected to change) */
5964 npy_bool requires_pyapi; /* GIL is required by loop */
5965
5966 /* Loop doesn't set FPE flags; if not set check FPE flags */
5967 npy_bool no_floatingpoint_errors;
5968 } ufunc_call_info;
5969
5970 Note that the first call only fills in the ``context``. The call to
5971 ``_get_strided_loop`` fills in all other data. The main thing to note is
5972 that the new-style loops return 0 on success, -1 on failure. They are
5973 passed context as new first input and ``auxdata`` as (replaced) last.
5974
5975 Only the ``strided_loop``signature is considered guaranteed stable
5976 for NumPy bug-fix releases. All other API is tied to the experimental
5977 API versioning.
5978
5979 The reason for the split call is that cast information is required to
5980 decide what the fixed-strides will be.
5981
5982 NumPy ties the lifetime of the ``auxdata`` information to the capsule.
5983
5984 """))
5985
5986
5987##############################################################################
5988#
5989# Documentation for dtype attributes and methods
5990#
5991##############################################################################
5992
5993##############################################################################
5994#
5995# dtype object
5996#
5997##############################################################################
5998
5999add_newdoc('numpy._core.multiarray', 'dtype',
6000 """
6001 dtype(dtype, align=False, copy=False, **kwargs)
6002 --
6003
6004 dtype(dtype, align=False, copy=False, [metadata])
6005
6006 Create a data type object.
6007
6008 A numpy array is homogeneous, and contains elements described by a
6009 dtype object. A dtype object can be constructed from different
6010 combinations of fundamental numeric types.
6011
6012 Parameters
6013 ----------
6014 dtype
6015 Object to be converted to a data type object.
6016 align : bool, optional
6017 Add padding to the fields to match what a C compiler would output
6018 for a similar C-struct. Can be ``True`` only if `obj` is a dictionary
6019 or a comma-separated string. If a struct dtype is being created,
6020 this also sets a sticky alignment flag ``isalignedstruct``.
6021 copy : bool, optional
6022 Make a new copy of the data-type object. If ``False``, the result
6023 may just be a reference to a built-in data-type object.
6024 metadata : dict, optional
6025 An optional dictionary with dtype metadata.
6026
6027 See also
6028 --------
6029 result_type
6030
6031 Examples
6032 --------
6033 Using array-scalar type:
6034
6035 >>> import numpy as np
6036 >>> np.dtype(np.int16)
6037 dtype('int16')
6038
6039 Structured type, one field name 'f1', containing int16:
6040
6041 >>> np.dtype([('f1', np.int16)])
6042 dtype([('f1', '<i2')])
6043
6044 Structured type, one field named 'f1', in itself containing a structured
6045 type with one field:
6046
6047 >>> np.dtype([('f1', [('f1', np.int16)])])
6048 dtype([('f1', [('f1', '<i2')])])
6049
6050 Structured type, two fields: the first field contains an unsigned int, the
6051 second an int32:
6052
6053 >>> np.dtype([('f1', np.uint64), ('f2', np.int32)])
6054 dtype([('f1', '<u8'), ('f2', '<i4')])
6055
6056 Using array-protocol type strings:
6057
6058 >>> np.dtype([('a','f8'),('b','S10')])
6059 dtype([('a', '<f8'), ('b', 'S10')])
6060
6061 Using comma-separated field formats. The shape is (2,3):
6062
6063 >>> np.dtype("i4, (2,3)f8")
6064 dtype([('f0', '<i4'), ('f1', '<f8', (2, 3))])
6065
6066 Using tuples. ``int`` is a fixed type, 3 the field's shape. ``void``
6067 is a flexible type, here of size 10:
6068
6069 >>> np.dtype([('hello',(np.int64,3)),('world',np.void,10)])
6070 dtype([('hello', '<i8', (3,)), ('world', 'V10')])
6071
6072 Subdivide ``int16`` into 2 ``int8``'s, called x and y. 0 and 1 are
6073 the offsets in bytes:
6074
6075 >>> np.dtype((np.int16, {'x':(np.int8,0), 'y':(np.int8,1)}))
6076 dtype((numpy.int16, [('x', 'i1'), ('y', 'i1')]))
6077
6078 Using dictionaries. Two fields named 'gender' and 'age':
6079
6080 >>> np.dtype({'names':['gender','age'], 'formats':['S1',np.uint8]})
6081 dtype([('gender', 'S1'), ('age', 'u1')])
6082
6083 Offsets in bytes, here 0 and 25:
6084
6085 >>> np.dtype({'surname':('S25',0),'age':(np.uint8,25)})
6086 dtype([('surname', 'S25'), ('age', 'u1')])
6087
6088 """)
6089
6090##############################################################################
6091#
6092# dtype attributes
6093#
6094##############################################################################
6095
6096add_newdoc('numpy._core.multiarray', 'dtype', ('alignment',
6097 """
6098 The required alignment (bytes) of this data-type according to the compiler.
6099
6100 More information is available in the C-API section of the manual.
6101
6102 Examples
6103 --------
6104
6105 >>> import numpy as np
6106 >>> x = np.dtype('i4')
6107 >>> x.alignment
6108 4
6109
6110 >>> x = np.dtype(float)
6111 >>> x.alignment
6112 8
6113
6114 """))
6115
6116add_newdoc('numpy._core.multiarray', 'dtype', ('byteorder',
6117 """
6118 A character indicating the byte-order of this data-type object.
6119
6120 One of:
6121
6122 === ==============
6123 '=' native
6124 '<' little-endian
6125 '>' big-endian
6126 '|' not applicable
6127 === ==============
6128
6129 All built-in data-type objects have byteorder either '=' or '|'.
6130
6131 Examples
6132 --------
6133
6134 >>> import numpy as np
6135 >>> dt = np.dtype('i2')
6136 >>> dt.byteorder
6137 '='
6138 >>> # endian is not relevant for 8 bit numbers
6139 >>> np.dtype('i1').byteorder
6140 '|'
6141 >>> # or ASCII strings
6142 >>> np.dtype('S2').byteorder
6143 '|'
6144 >>> # Even if specific code is given, and it is native
6145 >>> # '=' is the byteorder
6146 >>> import sys
6147 >>> sys_is_le = sys.byteorder == 'little'
6148 >>> native_code = '<' if sys_is_le else '>'
6149 >>> swapped_code = '>' if sys_is_le else '<'
6150 >>> dt = np.dtype(native_code + 'i2')
6151 >>> dt.byteorder
6152 '='
6153 >>> # Swapped code shows up as itself
6154 >>> dt = np.dtype(swapped_code + 'i2')
6155 >>> dt.byteorder == swapped_code
6156 True
6157
6158 """))
6159
6160add_newdoc('numpy._core.multiarray', 'dtype', ('char',
6161 """A unique character code for each of the 21 different built-in types.
6162
6163 Examples
6164 --------
6165
6166 >>> import numpy as np
6167 >>> x = np.dtype(float)
6168 >>> x.char
6169 'd'
6170
6171 """))
6172
6173add_newdoc('numpy._core.multiarray', 'dtype', ('descr',
6174 """
6175 `__array_interface__` description of the data-type.
6176
6177 The format is that required by the 'descr' key in the
6178 `__array_interface__` attribute.
6179
6180 Warning: This attribute exists specifically for `__array_interface__`,
6181 and passing it directly to `numpy.dtype` will not accurately reconstruct
6182 some dtypes (e.g., scalar and subarray dtypes).
6183
6184 Examples
6185 --------
6186
6187 >>> import numpy as np
6188 >>> x = np.dtype(float)
6189 >>> x.descr
6190 [('', '<f8')]
6191
6192 >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
6193 >>> dt.descr
6194 [('name', '<U16'), ('grades', '<f8', (2,))]
6195
6196 """))
6197
6198add_newdoc('numpy._core.multiarray', 'dtype', ('fields',
6199 """
6200 Dictionary of named fields defined for this data type, or ``None``.
6201
6202 The dictionary is indexed by keys that are the names of the fields.
6203 Each entry in the dictionary is a tuple fully describing the field::
6204
6205 (dtype, offset[, title])
6206
6207 Offset is limited to C int, which is signed and usually 32 bits.
6208 If present, the optional title can be any object (if it is a string
6209 or unicode then it will also be a key in the fields dictionary,
6210 otherwise it's meta-data). Notice also that the first two elements
6211 of the tuple can be passed directly as arguments to the
6212 ``ndarray.getfield`` and ``ndarray.setfield`` methods.
6213
6214 See Also
6215 --------
6216 ndarray.getfield, ndarray.setfield
6217
6218 Examples
6219 --------
6220
6221 >>> import numpy as np
6222 >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
6223 >>> print(dt.fields)
6224 {'name': (dtype('<U16'), 0), 'grades': (dtype(('<f8', (2,))), 64)}
6225
6226 """))
6227
6228add_newdoc('numpy._core.multiarray', 'dtype', ('flags',
6229 """
6230 Bit-flags describing how this data type is to be interpreted.
6231
6232 Bit-masks are in ``numpy._core.multiarray`` as the constants
6233 `ITEM_HASOBJECT`, `LIST_PICKLE`, `ITEM_IS_POINTER`, `NEEDS_INIT`,
6234 `NEEDS_PYAPI`, `USE_GETITEM`, `USE_SETITEM`. A full explanation
6235 of these flags is in C-API documentation; they are largely useful
6236 for user-defined data-types.
6237
6238 The following example demonstrates that operations on this particular
6239 dtype requires Python C-API.
6240
6241 Examples
6242 --------
6243
6244 >>> import numpy as np
6245 >>> x = np.dtype([('a', np.int32, 8), ('b', np.float64, 6)])
6246 >>> x.flags
6247 16
6248 >>> np._core.multiarray.NEEDS_PYAPI
6249 16
6250
6251 """))
6252
6253add_newdoc('numpy._core.multiarray', 'dtype', ('hasobject',
6254 """
6255 Boolean indicating whether this dtype contains any reference-counted
6256 objects in any fields or sub-dtypes.
6257
6258 Recall that what is actually in the ndarray memory representing
6259 the Python object is the memory address of that object (a pointer).
6260 Special handling may be required, and this attribute is useful for
6261 distinguishing data types that may contain arbitrary Python objects
6262 and data-types that won't.
6263
6264 """))
6265
6266add_newdoc('numpy._core.multiarray', 'dtype', ('isbuiltin',
6267 """
6268 Integer indicating how this dtype relates to the built-in dtypes.
6269
6270 Read-only.
6271
6272 = ========================================================================
6273 0 if this is a structured array type, with fields
6274 1 if this is a dtype compiled into numpy (such as ints, floats etc)
6275 2 if the dtype is for a user-defined numpy type
6276 A user-defined type uses the numpy C-API machinery to extend
6277 numpy to handle a new array type. See
6278 :ref:`user.user-defined-data-types` in the NumPy manual.
6279 = ========================================================================
6280
6281 Examples
6282 --------
6283
6284 >>> import numpy as np
6285 >>> dt = np.dtype('i2')
6286 >>> dt.isbuiltin
6287 1
6288 >>> dt = np.dtype('f8')
6289 >>> dt.isbuiltin
6290 1
6291 >>> dt = np.dtype([('field1', 'f8')])
6292 >>> dt.isbuiltin
6293 0
6294
6295 """))
6296
6297add_newdoc('numpy._core.multiarray', 'dtype', ('isnative',
6298 """
6299 Boolean indicating whether the byte order of this dtype is native
6300 to the platform.
6301
6302 """))
6303
6304add_newdoc('numpy._core.multiarray', 'dtype', ('isalignedstruct',
6305 """
6306 Boolean indicating whether the dtype is a struct which maintains
6307 field alignment. This flag is sticky, so when combining multiple
6308 structs together, it is preserved and produces new dtypes which
6309 are also aligned.
6310
6311 """))
6312
6313add_newdoc('numpy._core.multiarray', 'dtype', ('itemsize',
6314 """
6315 The element size of this data-type object.
6316
6317 For 18 of the 21 types this number is fixed by the data-type.
6318 For the flexible data-types, this number can be anything.
6319
6320 Examples
6321 --------
6322
6323 >>> import numpy as np
6324 >>> arr = np.array([[1, 2], [3, 4]])
6325 >>> arr.dtype
6326 dtype('int64')
6327 >>> arr.itemsize
6328 8
6329
6330 >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
6331 >>> dt.itemsize
6332 80
6333
6334 """))
6335
6336add_newdoc('numpy._core.multiarray', 'dtype', ('kind',
6337 """
6338 A character code (one of 'biufcmMOSTUV') identifying the general kind of data.
6339
6340 = ======================
6341 b boolean
6342 i signed integer
6343 u unsigned integer
6344 f floating-point
6345 c complex floating-point
6346 m timedelta
6347 M datetime
6348 O object
6349 S (byte-)string
6350 T string (StringDType)
6351 U Unicode
6352 V void
6353 = ======================
6354
6355 Examples
6356 --------
6357
6358 >>> import numpy as np
6359 >>> dt = np.dtype('i4')
6360 >>> dt.kind
6361 'i'
6362 >>> dt = np.dtype('f8')
6363 >>> dt.kind
6364 'f'
6365 >>> dt = np.dtype([('field1', 'f8')])
6366 >>> dt.kind
6367 'V'
6368
6369 """))
6370
6371add_newdoc('numpy._core.multiarray', 'dtype', ('metadata',
6372 """
6373 Either ``None`` or a readonly dictionary of metadata (mappingproxy).
6374
6375 The metadata field can be set using any dictionary at data-type
6376 creation. NumPy currently has no uniform approach to propagating
6377 metadata; although some array operations preserve it, there is no
6378 guarantee that others will.
6379
6380 .. warning::
6381
6382 Although used in certain projects, this feature was long undocumented
6383 and is not well supported. Some aspects of metadata propagation
6384 are expected to change in the future.
6385
6386 Examples
6387 --------
6388
6389 >>> import numpy as np
6390 >>> dt = np.dtype(float, metadata={"key": "value"})
6391 >>> dt.metadata["key"]
6392 'value'
6393 >>> arr = np.array([1, 2, 3], dtype=dt)
6394 >>> arr.dtype.metadata
6395 mappingproxy({'key': 'value'})
6396
6397 Adding arrays with identical datatypes currently preserves the metadata:
6398
6399 >>> (arr + arr).dtype.metadata
6400 mappingproxy({'key': 'value'})
6401
6402 If the arrays have different dtype metadata, the first one wins:
6403
6404 >>> dt2 = np.dtype(float, metadata={"key2": "value2"})
6405 >>> arr2 = np.array([3, 2, 1], dtype=dt2)
6406 >>> print((arr + arr2).dtype.metadata)
6407 {'key': 'value'}
6408 """))
6409
6410add_newdoc('numpy._core.multiarray', 'dtype', ('name',
6411 """
6412 A bit-width name for this data-type.
6413
6414 Un-sized flexible data-type objects do not have this attribute.
6415
6416 Examples
6417 --------
6418
6419 >>> import numpy as np
6420 >>> x = np.dtype(float)
6421 >>> x.name
6422 'float64'
6423 >>> x = np.dtype([('a', np.int32, 8), ('b', np.float64, 6)])
6424 >>> x.name
6425 'void640'
6426
6427 """))
6428
6429add_newdoc('numpy._core.multiarray', 'dtype', ('names',
6430 """
6431 Ordered list of field names, or ``None`` if there are no fields.
6432
6433 The names are ordered according to increasing byte offset. This can be
6434 used, for example, to walk through all of the named fields in offset order.
6435
6436 Examples
6437 --------
6438 >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
6439 >>> dt.names
6440 ('name', 'grades')
6441
6442 """))
6443
6444add_newdoc('numpy._core.multiarray', 'dtype', ('num',
6445 """
6446 A unique number for each of the 21 different built-in types.
6447
6448 These are roughly ordered from least-to-most precision.
6449
6450 Examples
6451 --------
6452
6453 >>> import numpy as np
6454 >>> dt = np.dtype(str)
6455 >>> dt.num
6456 19
6457
6458 >>> dt = np.dtype(float)
6459 >>> dt.num
6460 12
6461
6462 """))
6463
6464add_newdoc('numpy._core.multiarray', 'dtype', ('shape',
6465 """
6466 Shape tuple of the sub-array if this data type describes a sub-array,
6467 and ``()`` otherwise.
6468
6469 Examples
6470 --------
6471
6472 >>> import numpy as np
6473 >>> dt = np.dtype(('i4', 4))
6474 >>> dt.shape
6475 (4,)
6476
6477 >>> dt = np.dtype(('i4', (2, 3)))
6478 >>> dt.shape
6479 (2, 3)
6480
6481 """))
6482
6483add_newdoc('numpy._core.multiarray', 'dtype', ('ndim',
6484 """
6485 Number of dimensions of the sub-array if this data type describes a
6486 sub-array, and ``0`` otherwise.
6487
6488 Examples
6489 --------
6490 >>> import numpy as np
6491 >>> x = np.dtype(float)
6492 >>> x.ndim
6493 0
6494
6495 >>> x = np.dtype((float, 8))
6496 >>> x.ndim
6497 1
6498
6499 >>> x = np.dtype(('i4', (3, 4)))
6500 >>> x.ndim
6501 2
6502
6503 """))
6504
6505add_newdoc('numpy._core.multiarray', 'dtype', ('str',
6506 """The array-protocol typestring of this data-type object."""))
6507
6508add_newdoc('numpy._core.multiarray', 'dtype', ('subdtype',
6509 """
6510 Tuple ``(item_dtype, shape)`` if this `dtype` describes a sub-array, and
6511 None otherwise.
6512
6513 The *shape* is the fixed shape of the sub-array described by this
6514 data type, and *item_dtype* the data type of the array.
6515
6516 If a field whose dtype object has this attribute is retrieved,
6517 then the extra dimensions implied by *shape* are tacked on to
6518 the end of the retrieved array.
6519
6520 See Also
6521 --------
6522 dtype.base
6523
6524 Examples
6525 --------
6526 >>> import numpy as np
6527 >>> x = np.dtype('8f')
6528 >>> x.subdtype
6529 (dtype('float32'), (8,))
6530
6531 >>> x = np.dtype('i2')
6532 >>> x.subdtype
6533 >>>
6534
6535 """))
6536
6537add_newdoc('numpy._core.multiarray', 'dtype', ('base',
6538 """
6539 Returns dtype for the base element of the subarrays,
6540 regardless of their dimension or shape.
6541
6542 See Also
6543 --------
6544 dtype.subdtype
6545
6546 Examples
6547 --------
6548 >>> import numpy as np
6549 >>> x = np.dtype('8f')
6550 >>> x.base
6551 dtype('float32')
6552
6553 >>> x = np.dtype('i2')
6554 >>> x.base
6555 dtype('int16')
6556
6557 """))
6558
6559add_newdoc('numpy._core.multiarray', 'dtype', ('type',
6560 """The type object used to instantiate a scalar of this data-type."""))
6561
6562##############################################################################
6563#
6564# dtype methods
6565#
6566##############################################################################
6567
6568add_newdoc('numpy._core.multiarray', 'dtype', ('newbyteorder',
6569 """
6570 newbyteorder($self, new_order='S', /)
6571 --
6572
6573 newbyteorder(new_order='S', /)
6574
6575 Return a new dtype with a different byte order.
6576
6577 Changes are also made in all fields and sub-arrays of the data type.
6578
6579 Parameters
6580 ----------
6581 new_order : string, optional
6582 Byte order to force; a value from the byte order specifications
6583 below. The default value ('S') results in swapping the current
6584 byte order. `new_order` codes can be any of:
6585
6586 * 'S' - swap dtype from current to opposite endian
6587 * {'<', 'little'} - little endian
6588 * {'>', 'big'} - big endian
6589 * {'=', 'native'} - native order
6590 * {'|', 'I'} - ignore (no change to byte order)
6591
6592 Returns
6593 -------
6594 new_dtype : dtype
6595 New dtype object with the given change to the byte order.
6596
6597 Notes
6598 -----
6599 Changes are also made in all fields and sub-arrays of the data type.
6600
6601 Examples
6602 --------
6603 >>> import sys
6604 >>> sys_is_le = sys.byteorder == 'little'
6605 >>> native_code = '<' if sys_is_le else '>'
6606 >>> swapped_code = '>' if sys_is_le else '<'
6607 >>> import numpy as np
6608 >>> native_dt = np.dtype(native_code+'i2')
6609 >>> swapped_dt = np.dtype(swapped_code+'i2')
6610 >>> native_dt.newbyteorder('S') == swapped_dt
6611 True
6612 >>> native_dt.newbyteorder() == swapped_dt
6613 True
6614 >>> native_dt == swapped_dt.newbyteorder('S')
6615 True
6616 >>> native_dt == swapped_dt.newbyteorder('=')
6617 True
6618 >>> native_dt == swapped_dt.newbyteorder('N')
6619 True
6620 >>> native_dt == native_dt.newbyteorder('|')
6621 True
6622 >>> np.dtype('<i2') == native_dt.newbyteorder('<')
6623 True
6624 >>> np.dtype('<i2') == native_dt.newbyteorder('L')
6625 True
6626 >>> np.dtype('>i2') == native_dt.newbyteorder('>')
6627 True
6628 >>> np.dtype('>i2') == native_dt.newbyteorder('B')
6629 True
6630
6631 """))
6632
6633add_newdoc('numpy._core.multiarray', 'dtype', ('__class_getitem__',
6634 """
6635 __class_getitem__(item, /)
6636
6637 Return a parametrized wrapper around the `~numpy.dtype` type.
6638
6639 .. versionadded:: 1.22
6640
6641 Returns
6642 -------
6643 alias : types.GenericAlias
6644 A parametrized `~numpy.dtype` type.
6645
6646 Examples
6647 --------
6648 >>> import numpy as np
6649
6650 >>> np.dtype[np.int64]
6651 numpy.dtype[numpy.int64]
6652
6653 See Also
6654 --------
6655 :pep:`585` : Type hinting generics in standard collections.
6656
6657 """))
6658
6659add_newdoc('numpy._core.multiarray', 'dtype', ('__ge__',
6660 """
6661 __ge__(value, /)
6662
6663 Return ``self >= value``.
6664
6665 Equivalent to ``np.can_cast(value, self, casting="safe")``.
6666
6667 See Also
6668 --------
6669 can_cast : Returns True if cast between data types can occur according to
6670 the casting rule.
6671
6672 """))
6673
6674add_newdoc('numpy._core.multiarray', 'dtype', ('__le__',
6675 """
6676 __le__(value, /)
6677
6678 Return ``self <= value``.
6679
6680 Equivalent to ``np.can_cast(self, value, casting="safe")``.
6681
6682 See Also
6683 --------
6684 can_cast : Returns True if cast between data types can occur according to
6685 the casting rule.
6686
6687 """))
6688
6689add_newdoc('numpy._core.multiarray', 'dtype', ('__gt__',
6690 """
6691 __gt__(value, /)
6692
6693 Return ``self > value``.
6694
6695 Equivalent to
6696 ``self != value and np.can_cast(value, self, casting="safe")``.
6697
6698 See Also
6699 --------
6700 can_cast : Returns True if cast between data types can occur according to
6701 the casting rule.
6702
6703 """))
6704
6705add_newdoc('numpy._core.multiarray', 'dtype', ('__lt__',
6706 """
6707 __lt__(value, /)
6708
6709 Return ``self < value``.
6710
6711 Equivalent to
6712 ``self != value and np.can_cast(self, value, casting="safe")``.
6713
6714 See Also
6715 --------
6716 can_cast : Returns True if cast between data types can occur according to
6717 the casting rule.
6718
6719 """))
6720
6721##############################################################################
6722#
6723# Datetime-related Methods
6724#
6725##############################################################################
6726
6727add_newdoc('numpy._core.multiarray', 'busdaycalendar',
6728 """
6729 busdaycalendar(weekmask='1111100', holidays=None)
6730 --
6731
6732 busdaycalendar(weekmask='1111100', holidays=None)
6733
6734 A business day calendar object that efficiently stores information
6735 defining valid days for the busday family of functions.
6736
6737 The default valid days are Monday through Friday ("business days").
6738 A busdaycalendar object can be specified with any set of weekly
6739 valid days, plus an optional "holiday" dates that always will be invalid.
6740
6741 Once a busdaycalendar object is created, the weekmask and holidays
6742 cannot be modified.
6743
6744 Parameters
6745 ----------
6746 weekmask : str or array_like of bool, optional
6747 A seven-element array indicating which of Monday through Sunday are
6748 valid days. May be specified as a length-seven list or array, like
6749 [1,1,1,1,1,0,0]; a length-seven string, like '1111100'; or a string
6750 like "Mon Tue Wed Thu Fri", made up of 3-character abbreviations for
6751 weekdays, optionally separated by white space. Valid abbreviations
6752 are: Mon Tue Wed Thu Fri Sat Sun
6753 holidays : array_like of datetime64[D], optional
6754 An array of dates to consider as invalid dates, no matter which
6755 weekday they fall upon. Holiday dates may be specified in any
6756 order, and NaT (not-a-time) dates are ignored. This list is
6757 saved in a normalized form that is suited for fast calculations
6758 of valid days.
6759
6760 Returns
6761 -------
6762 out : busdaycalendar
6763 A business day calendar object containing the specified
6764 weekmask and holidays values.
6765
6766 See Also
6767 --------
6768 is_busday : Returns a boolean array indicating valid days.
6769 busday_offset : Applies an offset counted in valid days.
6770 busday_count : Counts how many valid days are in a half-open date range.
6771
6772 Attributes
6773 ----------
6774 weekmask : (copy) seven-element array of bool
6775 holidays : (copy) sorted array of datetime64[D]
6776
6777 Notes
6778 -----
6779 Once a busdaycalendar object is created, you cannot modify the
6780 weekmask or holidays. The attributes return copies of internal data.
6781
6782 Examples
6783 --------
6784 >>> import numpy as np
6785 >>> # Some important days in July
6786 ... bdd = np.busdaycalendar(
6787 ... holidays=['2011-07-01', '2011-07-04', '2011-07-17'])
6788 >>> # Default is Monday to Friday weekdays
6789 ... bdd.weekmask
6790 array([ True, True, True, True, True, False, False])
6791 >>> # Any holidays already on the weekend are removed
6792 ... bdd.holidays
6793 array(['2011-07-01', '2011-07-04'], dtype='datetime64[D]')
6794 """)
6795
6796add_newdoc('numpy._core.multiarray', 'busdaycalendar', ('weekmask',
6797 """A copy of the seven-element boolean mask indicating valid days."""))
6798
6799add_newdoc('numpy._core.multiarray', 'busdaycalendar', ('holidays',
6800 """A copy of the holiday array indicating additional invalid days."""))
6801
6802add_newdoc('numpy._core.multiarray', 'normalize_axis_index',
6803 """
6804 normalize_axis_index(axis, ndim, msg_prefix=None)
6805
6806 Normalizes an axis index, `axis`, such that is a valid positive index into
6807 the shape of array with `ndim` dimensions. Raises an AxisError with an
6808 appropriate message if this is not possible.
6809
6810 Used internally by all axis-checking logic.
6811
6812 Parameters
6813 ----------
6814 axis : int
6815 The un-normalized index of the axis. Can be negative
6816 ndim : int
6817 The number of dimensions of the array that `axis` should be normalized
6818 against
6819 msg_prefix : str
6820 A prefix to put before the message, typically the name of the argument
6821
6822 Returns
6823 -------
6824 normalized_axis : int
6825 The normalized axis index, such that `0 <= normalized_axis < ndim`
6826
6827 Raises
6828 ------
6829 AxisError
6830 If the axis index is invalid, when `-ndim <= axis < ndim` is false.
6831
6832 Examples
6833 --------
6834 >>> import numpy as np
6835 >>> from numpy.lib.array_utils import normalize_axis_index
6836 >>> normalize_axis_index(0, ndim=3)
6837 0
6838 >>> normalize_axis_index(1, ndim=3)
6839 1
6840 >>> normalize_axis_index(-1, ndim=3)
6841 2
6842
6843 >>> normalize_axis_index(3, ndim=3)
6844 Traceback (most recent call last):
6845 ...
6846 numpy.exceptions.AxisError: axis 3 is out of bounds for array ...
6847 >>> normalize_axis_index(-4, ndim=3, msg_prefix='axes_arg')
6848 Traceback (most recent call last):
6849 ...
6850 numpy.exceptions.AxisError: axes_arg: axis -4 is out of bounds ...
6851 """)
6852
6853add_newdoc('numpy._core.multiarray', 'datetime_data',
6854 """
6855 datetime_data(dtype, /)
6856 --
6857
6858 datetime_data(dtype, /)
6859
6860 Get information about the step size of a date or time type.
6861
6862 The returned tuple can be passed as the second argument of `numpy.datetime64` and
6863 `numpy.timedelta64`.
6864
6865 Parameters
6866 ----------
6867 dtype : dtype
6868 The dtype object, which must be a `datetime64` or `timedelta64` type.
6869
6870 Returns
6871 -------
6872 unit : str
6873 The :ref:`datetime unit <arrays.dtypes.dateunits>` on which this dtype
6874 is based.
6875 count : int
6876 The number of base units in a step.
6877
6878 Examples
6879 --------
6880 >>> import numpy as np
6881 >>> dt_25s = np.dtype('timedelta64[25s]')
6882 >>> np.datetime_data(dt_25s)
6883 ('s', 25)
6884 >>> np.array(10, dt_25s).astype('timedelta64[s]')
6885 array(250, dtype='timedelta64[s]')
6886
6887 The result can be used to construct a datetime that uses the same units
6888 as a timedelta
6889
6890 >>> np.datetime64('2010', np.datetime_data(dt_25s))
6891 np.datetime64('2010-01-01T00:00:00','25s')
6892 """)
6893
6894
6895##############################################################################
6896#
6897# Documentation for `generic` attributes and methods
6898#
6899##############################################################################
6900
6901add_newdoc('numpy._core.numerictypes', 'generic',
6902 """
6903 Base class for numpy scalar types.
6904
6905 Class from which most (all?) numpy scalar types are derived. For
6906 consistency, exposes the same API as `ndarray`, despite many
6907 consequent attributes being either "get-only," or completely irrelevant.
6908 This is the class from which it is strongly suggested users should derive
6909 custom scalar types.
6910
6911 """)
6912
6913# Attributes
6914
6915add_newdoc('numpy._core.numerictypes', 'generic', ('T',
6916 """Scalar attribute identical to `ndarray.T`."""))
6917
6918add_newdoc('numpy._core.numerictypes', 'generic', ('base',
6919 """Scalar attribute identical to `ndarray.base`."""))
6920
6921add_newdoc('numpy._core.numerictypes', 'generic', ('data',
6922 """Pointer to start of data."""))
6923
6924add_newdoc('numpy._core.numerictypes', 'generic', ('dtype',
6925 """Get array data-descriptor."""))
6926
6927add_newdoc('numpy._core.numerictypes', 'generic', ('flags',
6928 """The integer value of flags."""))
6929
6930add_newdoc('numpy._core.numerictypes', 'generic', ('flat',
6931 """A 1-D view of the scalar."""))
6932
6933add_newdoc('numpy._core.numerictypes', 'generic', ('imag',
6934 """The imaginary part of the scalar."""))
6935
6936add_newdoc('numpy._core.numerictypes', 'generic', ('itemsize',
6937 """The length of one element in bytes."""))
6938
6939add_newdoc('numpy._core.numerictypes', 'generic', ('ndim',
6940 """The number of array dimensions."""))
6941
6942add_newdoc('numpy._core.numerictypes', 'generic', ('real',
6943 """The real part of the scalar."""))
6944
6945add_newdoc('numpy._core.numerictypes', 'generic', ('shape',
6946 """Tuple of array dimensions."""))
6947
6948add_newdoc('numpy._core.numerictypes', 'generic', ('size',
6949 """The number of elements in the gentype."""))
6950
6951add_newdoc('numpy._core.numerictypes', 'generic', ('strides',
6952 """Tuple of bytes steps in each dimension."""))
6953
6954# Methods
6955
6956add_newdoc('numpy._core.numerictypes', 'number', ('__class_getitem__',
6957 """
6958 __class_getitem__($cls, item, /)
6959 --
6960
6961 number.__class_getitem__(item, /)
6962
6963 Return a parametrized wrapper around the `~numpy.number` type.
6964
6965 .. versionadded:: 1.22
6966
6967 Returns
6968 -------
6969 alias : types.GenericAlias
6970 A parametrized `~numpy.number` type.
6971
6972 Examples
6973 --------
6974 >>> from typing import Any
6975 >>> import numpy as np
6976
6977 >>> np.signedinteger[Any]
6978 numpy.signedinteger[typing.Any]
6979
6980 See Also
6981 --------
6982 :pep:`585` : Type hinting generics in standard collections.
6983
6984 """))
6985
6986##############################################################################
6987#
6988# Documentation for scalar type abstract base classes in type hierarchy
6989#
6990##############################################################################
6991
6992
6993add_newdoc('numpy._core.numerictypes', 'number',
6994 """
6995 Abstract base class of all numeric scalar types.
6996
6997 """)
6998
6999add_newdoc('numpy._core.numerictypes', 'integer',
7000 """
7001 Abstract base class of all integer scalar types.
7002
7003 """)
7004
7005add_newdoc('numpy._core.numerictypes', 'signedinteger',
7006 """
7007 Abstract base class of all signed integer scalar types.
7008
7009 """)
7010
7011add_newdoc('numpy._core.numerictypes', 'unsignedinteger',
7012 """
7013 Abstract base class of all unsigned integer scalar types.
7014
7015 """)
7016
7017add_newdoc('numpy._core.numerictypes', 'inexact',
7018 """
7019 Abstract base class of all numeric scalar types with a (potentially)
7020 inexact representation of the values in its range, such as
7021 floating-point numbers.
7022
7023 """)
7024
7025add_newdoc('numpy._core.numerictypes', 'floating',
7026 """
7027 Abstract base class of all floating-point scalar types.
7028
7029 """)
7030
7031add_newdoc('numpy._core.numerictypes', 'complexfloating',
7032 """
7033 Abstract base class of all complex number scalar types that are made up of
7034 floating-point numbers.
7035
7036 """)
7037
7038add_newdoc('numpy._core.numerictypes', 'flexible',
7039 """
7040 Abstract base class of all scalar types without predefined length.
7041 The actual size of these types depends on the specific `numpy.dtype`
7042 instantiation.
7043
7044 """)
7045
7046add_newdoc('numpy._core.numerictypes', 'character',
7047 """
7048 Abstract base class of all character string scalar types.
7049
7050 """)
7051
7052##############################################################################
7053#
7054# Documentation for `dtypes.*` classes
7055#
7056##############################################################################
7057
7058for _dtype_name, _signature, _sctype_name in (
7059 ("BoolDType", "()", "bool"),
7060 ("Int8DType", "()", "int8"),
7061 ("UInt8DType", "()", "uint8"),
7062 ("Int16DType", "()", "int16"),
7063 ("UInt16DType", "()", "uint16"),
7064 ("Int32DType", "()", "int32"),
7065 ("IntDType", "()", "intc"),
7066 ("UInt32DType", "()", "uint32"),
7067 ("UIntDType", "()", "uintc"),
7068 ("Int64DType", "()", "int64"),
7069 ("UInt64DType", "()", "uint64"),
7070 ("LongLongDType", "()", "longlong"),
7071 ("ULongLongDType", "()", "ulonglong"),
7072 ("Float16DType", "()", "float16"),
7073 ("Float32DType", "()", "float32"),
7074 ("Float64DType", "()", "float64"),
7075 ("LongDoubleDType", "()", "longdouble"),
7076 ("Complex64DType", "()", "complex64"),
7077 ("Complex128DType", "()", "complex128"),
7078 ("CLongDoubleDType", "()", "clongdouble"),
7079 ("ObjectDType", "()", "object"),
7080 ("BytesDType", "(size, /)", "bytes_"),
7081 ("StrDType", "(size, /)", "str_"),
7082 ("VoidDType", "(length, /)", "void"),
7083 ("DateTime64DType", "(unit, /)", "datetime64"),
7084 ("TimeDelta64DType", "(unit, /)", "timedelta64"),
7085):
7086 _extra_docs = ""
7087 if _dtype_name in {"VoidDType", "DateTime64DType", "TimeDelta64DType"}:
7088 _extra_docs = f"""
7089 .. warning::
7090 ``np.dtypes.{_dtype_name}`` cannot be instantiated directly.
7091 Use ``np.dtype("{_sctype_name}[{{unit}}]")`` instead.
7092 """
7093
7094 add_newdoc('numpy.dtypes', _dtype_name,
7095 f"""
7096 {_dtype_name}{_signature}
7097 --
7098
7099 DType class corresponding to the `numpy.{_sctype_name}` scalar type.
7100 {_extra_docs}
7101 See `numpy.dtype` for the typical way to create dtype instances
7102 and :ref:`arrays.dtypes` for additional information.
7103 """)
7104
7105 del _dtype_name, _signature, _sctype_name, _extra_docs # avoid namespace pollution
7106
7107
7108add_newdoc('numpy._core.multiarray', 'StringDType',
7109 """
7110 StringDType(*, coerce=True, **kwargs)
7111 --
7112
7113 StringDType(*, na_object=np._NoValue, coerce=True)
7114
7115 Create a StringDType instance.
7116
7117 StringDType can be used to store UTF-8 encoded variable-width strings in
7118 a NumPy array.
7119
7120 Parameters
7121 ----------
7122 na_object : object, optional
7123 Object used to represent missing data. If unset, the array will not
7124 use a missing data sentinel.
7125 coerce : bool, optional
7126 Whether or not items in an array-like passed to an array creation
7127 function that are neither a str or str subtype should be coerced to
7128 str. Defaults to True. If set to False, creating a StringDType
7129 array from an array-like containing entries that are not already
7130 strings will raise an error.
7131
7132 Examples
7133 --------
7134
7135 >>> import numpy as np
7136
7137 >>> from numpy.dtypes import StringDType
7138 >>> np.array(["hello", "world"], dtype=StringDType())
7139 array(["hello", "world"], dtype=StringDType())
7140
7141 >>> arr = np.array(["hello", None, "world"],
7142 ... dtype=StringDType(na_object=None))
7143 >>> arr
7144 array(["hello", None, "world"], dtype=StringDType(na_object=None))
7145 >>> arr[1] is None
7146 True
7147
7148 >>> arr = np.array(["hello", np.nan, "world"],
7149 ... dtype=StringDType(na_object=np.nan))
7150 >>> np.isnan(arr)
7151 array([False, True, False])
7152
7153 >>> np.array([1.2, object(), "hello world"],
7154 ... dtype=StringDType(coerce=False))
7155 Traceback (most recent call last):
7156 ...
7157 ValueError: StringDType only allows string data when string coercion is disabled.
7158
7159 >>> np.array(["hello", "world"], dtype=StringDType(coerce=True))
7160 array(["hello", "world"], dtype=StringDType(coerce=True))
7161 """)