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