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