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