Coverage for /home/martinb/.local/share/virtualenvs/camcops/lib/python3.6/site-packages/numpy/core/_add_newdocs.py : 100%

Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
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, core/defmatrix.py up-to-date.
10"""
12from numpy.core import numerictypes as _numerictypes
13from numpy.core import dtype
14from numpy.core.function_base import add_newdoc
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 """))
84add_newdoc('numpy.core', 'flatiter', ('coords',
85 """
86 An N-dimensional tuple of current coordinates.
88 Examples
89 --------
90 >>> x = np.arange(6).reshape(2, 3)
91 >>> fl = x.flat
92 >>> fl.coords
93 (0, 0)
94 >>> next(fl)
95 0
96 >>> fl.coords
97 (0, 1)
99 """))
103add_newdoc('numpy.core', 'flatiter', ('index',
104 """
105 Current flat index into the array.
107 Examples
108 --------
109 >>> x = np.arange(6).reshape(2, 3)
110 >>> fl = x.flat
111 >>> fl.index
112 0
113 >>> next(fl)
114 0
115 >>> fl.index
116 1
118 """))
120# flatiter functions
122add_newdoc('numpy.core', 'flatiter', ('__array__',
123 """__array__(type=None) Get array from iterator
125 """))
128add_newdoc('numpy.core', 'flatiter', ('copy',
129 """
130 copy()
132 Get a copy of the iterator as a 1-D array.
134 Examples
135 --------
136 >>> x = np.arange(6).reshape(2, 3)
137 >>> x
138 array([[0, 1, 2],
139 [3, 4, 5]])
140 >>> fl = x.flat
141 >>> fl.copy()
142 array([0, 1, 2, 3, 4, 5])
144 """))
147###############################################################################
148#
149# nditer
150#
151###############################################################################
153add_newdoc('numpy.core', 'nditer',
154 """
155 nditer(op, flags=None, op_flags=None, op_dtypes=None, order='K', casting='safe', op_axes=None, itershape=None, buffersize=0)
157 Efficient multi-dimensional iterator object to iterate over arrays.
158 To get started using this object, see the
159 :ref:`introductory guide to array iteration <arrays.nditer>`.
161 Parameters
162 ----------
163 op : ndarray or sequence of array_like
164 The array(s) to iterate over.
166 flags : sequence of str, optional
167 Flags to control the behavior of the iterator.
169 * ``buffered`` enables buffering when required.
170 * ``c_index`` causes a C-order index to be tracked.
171 * ``f_index`` causes a Fortran-order index to be tracked.
172 * ``multi_index`` causes a multi-index, or a tuple of indices
173 with one per iteration dimension, to be tracked.
174 * ``common_dtype`` causes all the operands to be converted to
175 a common data type, with copying or buffering as necessary.
176 * ``copy_if_overlap`` causes the iterator to determine if read
177 operands have overlap with write operands, and make temporary
178 copies as necessary to avoid overlap. False positives (needless
179 copying) are possible in some cases.
180 * ``delay_bufalloc`` delays allocation of the buffers until
181 a reset() call is made. Allows ``allocate`` operands to
182 be initialized before their values are copied into the buffers.
183 * ``external_loop`` causes the ``values`` given to be
184 one-dimensional arrays with multiple values instead of
185 zero-dimensional arrays.
186 * ``grow_inner`` allows the ``value`` array sizes to be made
187 larger than the buffer size when both ``buffered`` and
188 ``external_loop`` is used.
189 * ``ranged`` allows the iterator to be restricted to a sub-range
190 of the iterindex values.
191 * ``refs_ok`` enables iteration of reference types, such as
192 object arrays.
193 * ``reduce_ok`` enables iteration of ``readwrite`` operands
194 which are broadcasted, also known as reduction operands.
195 * ``zerosize_ok`` allows `itersize` to be zero.
196 op_flags : list of list of str, optional
197 This is a list of flags for each operand. At minimum, one of
198 ``readonly``, ``readwrite``, or ``writeonly`` must be specified.
200 * ``readonly`` indicates the operand will only be read from.
201 * ``readwrite`` indicates the operand will be read from and written to.
202 * ``writeonly`` indicates the operand will only be written to.
203 * ``no_broadcast`` prevents the operand from being broadcasted.
204 * ``contig`` forces the operand data to be contiguous.
205 * ``aligned`` forces the operand data to be aligned.
206 * ``nbo`` forces the operand data to be in native byte order.
207 * ``copy`` allows a temporary read-only copy if required.
208 * ``updateifcopy`` allows a temporary read-write copy if required.
209 * ``allocate`` causes the array to be allocated if it is None
210 in the ``op`` parameter.
211 * ``no_subtype`` prevents an ``allocate`` operand from using a subtype.
212 * ``arraymask`` indicates that this operand is the mask to use
213 for selecting elements when writing to operands with the
214 'writemasked' flag set. The iterator does not enforce this,
215 but when writing from a buffer back to the array, it only
216 copies those elements indicated by this mask.
217 * ``writemasked`` indicates that only elements where the chosen
218 ``arraymask`` operand is True will be written to.
219 * ``overlap_assume_elementwise`` can be used to mark operands that are
220 accessed only in the iterator order, to allow less conservative
221 copying when ``copy_if_overlap`` is present.
222 op_dtypes : dtype or tuple of dtype(s), optional
223 The required data type(s) of the operands. If copying or buffering
224 is enabled, the data will be converted to/from their original types.
225 order : {'C', 'F', 'A', 'K'}, optional
226 Controls the iteration order. 'C' means C order, 'F' means
227 Fortran order, 'A' means 'F' order if all the arrays are Fortran
228 contiguous, 'C' order otherwise, and 'K' means as close to the
229 order the array elements appear in memory as possible. This also
230 affects the element memory order of ``allocate`` operands, as they
231 are allocated to be compatible with iteration order.
232 Default is 'K'.
233 casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional
234 Controls what kind of data casting may occur when making a copy
235 or buffering. Setting this to 'unsafe' is not recommended,
236 as it can adversely affect accumulations.
238 * 'no' means the data types should not be cast at all.
239 * 'equiv' means only byte-order changes are allowed.
240 * 'safe' means only casts which can preserve values are allowed.
241 * 'same_kind' means only safe casts or casts within a kind,
242 like float64 to float32, are allowed.
243 * 'unsafe' means any data conversions may be done.
244 op_axes : list of list of ints, optional
245 If provided, is a list of ints or None for each operands.
246 The list of axes for an operand is a mapping from the dimensions
247 of the iterator to the dimensions of the operand. A value of
248 -1 can be placed for entries, causing that dimension to be
249 treated as `newaxis`.
250 itershape : tuple of ints, optional
251 The desired shape of the iterator. This allows ``allocate`` operands
252 with a dimension mapped by op_axes not corresponding to a dimension
253 of a different operand to get a value not equal to 1 for that
254 dimension.
255 buffersize : int, optional
256 When buffering is enabled, controls the size of the temporary
257 buffers. Set to 0 for the default value.
259 Attributes
260 ----------
261 dtypes : tuple of dtype(s)
262 The data types of the values provided in `value`. This may be
263 different from the operand data types if buffering is enabled.
264 Valid only before the iterator is closed.
265 finished : bool
266 Whether the iteration over the operands is finished or not.
267 has_delayed_bufalloc : bool
268 If True, the iterator was created with the ``delay_bufalloc`` flag,
269 and no reset() function was called on it yet.
270 has_index : bool
271 If True, the iterator was created with either the ``c_index`` or
272 the ``f_index`` flag, and the property `index` can be used to
273 retrieve it.
274 has_multi_index : bool
275 If True, the iterator was created with the ``multi_index`` flag,
276 and the property `multi_index` can be used to retrieve it.
277 index
278 When the ``c_index`` or ``f_index`` flag was used, this property
279 provides access to the index. Raises a ValueError if accessed
280 and ``has_index`` is False.
281 iterationneedsapi : bool
282 Whether iteration requires access to the Python API, for example
283 if one of the operands is an object array.
284 iterindex : int
285 An index which matches the order of iteration.
286 itersize : int
287 Size of the iterator.
288 itviews
289 Structured view(s) of `operands` in memory, matching the reordered
290 and optimized iterator access pattern. Valid only before the iterator
291 is closed.
292 multi_index
293 When the ``multi_index`` flag was used, this property
294 provides access to the index. Raises a ValueError if accessed
295 accessed and ``has_multi_index`` is False.
296 ndim : int
297 The dimensions of the iterator.
298 nop : int
299 The number of iterator operands.
300 operands : tuple of operand(s)
301 The array(s) to be iterated over. Valid only before the iterator is
302 closed.
303 shape : tuple of ints
304 Shape tuple, the shape of the iterator.
305 value
306 Value of ``operands`` at current iteration. Normally, this is a
307 tuple of array scalars, but if the flag ``external_loop`` is used,
308 it is a tuple of one dimensional arrays.
310 Notes
311 -----
312 `nditer` supersedes `flatiter`. The iterator implementation behind
313 `nditer` is also exposed by the NumPy C API.
315 The Python exposure supplies two iteration interfaces, one which follows
316 the Python iterator protocol, and another which mirrors the C-style
317 do-while pattern. The native Python approach is better in most cases, but
318 if you need the coordinates or index of an iterator, use the C-style pattern.
320 Examples
321 --------
322 Here is how we might write an ``iter_add`` function, using the
323 Python iterator protocol:
325 >>> def iter_add_py(x, y, out=None):
326 ... addop = np.add
327 ... it = np.nditer([x, y, out], [],
328 ... [['readonly'], ['readonly'], ['writeonly','allocate']])
329 ... with it:
330 ... for (a, b, c) in it:
331 ... addop(a, b, out=c)
332 ... return it.operands[2]
334 Here is the same function, but following the C-style pattern:
336 >>> def iter_add(x, y, out=None):
337 ... addop = np.add
338 ... it = np.nditer([x, y, out], [],
339 ... [['readonly'], ['readonly'], ['writeonly','allocate']])
340 ... with it:
341 ... while not it.finished:
342 ... addop(it[0], it[1], out=it[2])
343 ... it.iternext()
344 ... return it.operands[2]
346 Here is an example outer product function:
348 >>> def outer_it(x, y, out=None):
349 ... mulop = np.multiply
350 ... it = np.nditer([x, y, out], ['external_loop'],
351 ... [['readonly'], ['readonly'], ['writeonly', 'allocate']],
352 ... op_axes=[list(range(x.ndim)) + [-1] * y.ndim,
353 ... [-1] * x.ndim + list(range(y.ndim)),
354 ... None])
355 ... with it:
356 ... for (a, b, c) in it:
357 ... mulop(a, b, out=c)
358 ... return it.operands[2]
360 >>> a = np.arange(2)+1
361 >>> b = np.arange(3)+1
362 >>> outer_it(a,b)
363 array([[1, 2, 3],
364 [2, 4, 6]])
366 Here is an example function which operates like a "lambda" ufunc:
368 >>> def luf(lamdaexpr, *args, **kwargs):
369 ... '''luf(lambdaexpr, op1, ..., opn, out=None, order='K', casting='safe', buffersize=0)'''
370 ... nargs = len(args)
371 ... op = (kwargs.get('out',None),) + args
372 ... it = np.nditer(op, ['buffered','external_loop'],
373 ... [['writeonly','allocate','no_broadcast']] +
374 ... [['readonly','nbo','aligned']]*nargs,
375 ... order=kwargs.get('order','K'),
376 ... casting=kwargs.get('casting','safe'),
377 ... buffersize=kwargs.get('buffersize',0))
378 ... while not it.finished:
379 ... it[0] = lamdaexpr(*it[1:])
380 ... it.iternext()
381 ... return it.operands[0]
383 >>> a = np.arange(5)
384 >>> b = np.ones(5)
385 >>> luf(lambda i,j:i*i + j/2, a, b)
386 array([ 0.5, 1.5, 4.5, 9.5, 16.5])
388 If operand flags `"writeonly"` or `"readwrite"` are used the
389 operands may be views into the original data with the
390 `WRITEBACKIFCOPY` flag. In this case `nditer` must be used as a
391 context manager or the `nditer.close` method must be called before
392 using the result. The temporary data will be written back to the
393 original data when the `__exit__` function is called but not before:
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 Create nditers for use in nested loops
510 Create a tuple of `nditer` objects which iterate in nested loops over
511 different axes of the op argument. The first iterator is used in the
512 outermost loop, the last in the innermost loop. Advancing one will change
513 the subsequent iterators to point at its new element.
515 Parameters
516 ----------
517 op : ndarray or sequence of array_like
518 The array(s) to iterate over.
520 axes : list of list of int
521 Each item is used as an "op_axes" argument to an nditer
523 flags, op_flags, op_dtypes, order, casting, buffersize (optional)
524 See `nditer` parameters of the same name
526 Returns
527 -------
528 iters : tuple of nditer
529 An nditer for each item in `axes`, outermost first
531 See Also
532 --------
533 nditer
535 Examples
536 --------
538 Basic usage. Note how y is the "flattened" version of
539 [a[:, 0, :], a[:, 1, 0], a[:, 2, :]] since we specified
540 the first iter's axes as [1]
542 >>> a = np.arange(12).reshape(2, 3, 2)
543 >>> i, j = np.nested_iters(a, [[1], [0, 2]], flags=["multi_index"])
544 >>> for x in i:
545 ... print(i.multi_index)
546 ... for y in j:
547 ... print('', j.multi_index, y)
548 (0,)
549 (0, 0) 0
550 (0, 1) 1
551 (1, 0) 6
552 (1, 1) 7
553 (1,)
554 (0, 0) 2
555 (0, 1) 3
556 (1, 0) 8
557 (1, 1) 9
558 (2,)
559 (0, 0) 4
560 (0, 1) 5
561 (1, 0) 10
562 (1, 1) 11
564 """)
566add_newdoc('numpy.core', 'nditer', ('close',
567 """
568 close()
570 Resolve all writeback semantics in writeable operands.
572 .. versionadded:: 1.15.0
574 See Also
575 --------
577 :ref:`nditer-context-manager`
579 """))
582###############################################################################
583#
584# broadcast
585#
586###############################################################################
588add_newdoc('numpy.core', 'broadcast',
589 """
590 Produce an object that mimics broadcasting.
592 Parameters
593 ----------
594 in1, in2, ... : array_like
595 Input parameters.
597 Returns
598 -------
599 b : broadcast object
600 Broadcast the input parameters against one another, and
601 return an object that encapsulates the result.
602 Amongst others, it has ``shape`` and ``nd`` properties, and
603 may be used as an iterator.
605 See Also
606 --------
607 broadcast_arrays
608 broadcast_to
610 Examples
611 --------
613 Manually adding two vectors, using broadcasting:
615 >>> x = np.array([[1], [2], [3]])
616 >>> y = np.array([4, 5, 6])
617 >>> b = np.broadcast(x, y)
619 >>> out = np.empty(b.shape)
620 >>> out.flat = [u+v for (u,v) in b]
621 >>> out
622 array([[5., 6., 7.],
623 [6., 7., 8.],
624 [7., 8., 9.]])
626 Compare against built-in broadcasting:
628 >>> x + y
629 array([[5, 6, 7],
630 [6, 7, 8],
631 [7, 8, 9]])
633 """)
635# attributes
637add_newdoc('numpy.core', 'broadcast', ('index',
638 """
639 current index in broadcasted result
641 Examples
642 --------
643 >>> x = np.array([[1], [2], [3]])
644 >>> y = np.array([4, 5, 6])
645 >>> b = np.broadcast(x, y)
646 >>> b.index
647 0
648 >>> next(b), next(b), next(b)
649 ((1, 4), (1, 5), (1, 6))
650 >>> b.index
651 3
653 """))
655add_newdoc('numpy.core', 'broadcast', ('iters',
656 """
657 tuple of iterators along ``self``'s "components."
659 Returns a tuple of `numpy.flatiter` objects, one for each "component"
660 of ``self``.
662 See Also
663 --------
664 numpy.flatiter
666 Examples
667 --------
668 >>> x = np.array([1, 2, 3])
669 >>> y = np.array([[4], [5], [6]])
670 >>> b = np.broadcast(x, y)
671 >>> row, col = b.iters
672 >>> next(row), next(col)
673 (1, 4)
675 """))
677add_newdoc('numpy.core', 'broadcast', ('ndim',
678 """
679 Number of dimensions of broadcasted result. Alias for `nd`.
681 .. versionadded:: 1.12.0
683 Examples
684 --------
685 >>> x = np.array([1, 2, 3])
686 >>> y = np.array([[4], [5], [6]])
687 >>> b = np.broadcast(x, y)
688 >>> b.ndim
689 2
691 """))
693add_newdoc('numpy.core', 'broadcast', ('nd',
694 """
695 Number of dimensions of broadcasted result. For code intended for NumPy
696 1.12.0 and later the more consistent `ndim` is preferred.
698 Examples
699 --------
700 >>> x = np.array([1, 2, 3])
701 >>> y = np.array([[4], [5], [6]])
702 >>> b = np.broadcast(x, y)
703 >>> b.nd
704 2
706 """))
708add_newdoc('numpy.core', 'broadcast', ('numiter',
709 """
710 Number of iterators possessed by the broadcasted result.
712 Examples
713 --------
714 >>> x = np.array([1, 2, 3])
715 >>> y = np.array([[4], [5], [6]])
716 >>> b = np.broadcast(x, y)
717 >>> b.numiter
718 2
720 """))
722add_newdoc('numpy.core', 'broadcast', ('shape',
723 """
724 Shape of broadcasted result.
726 Examples
727 --------
728 >>> x = np.array([1, 2, 3])
729 >>> y = np.array([[4], [5], [6]])
730 >>> b = np.broadcast(x, y)
731 >>> b.shape
732 (3, 3)
734 """))
736add_newdoc('numpy.core', 'broadcast', ('size',
737 """
738 Total size of broadcasted result.
740 Examples
741 --------
742 >>> x = np.array([1, 2, 3])
743 >>> y = np.array([[4], [5], [6]])
744 >>> b = np.broadcast(x, y)
745 >>> b.size
746 9
748 """))
750add_newdoc('numpy.core', 'broadcast', ('reset',
751 """
752 reset()
754 Reset the broadcasted result's iterator(s).
756 Parameters
757 ----------
758 None
760 Returns
761 -------
762 None
764 Examples
765 --------
766 >>> x = np.array([1, 2, 3])
767 >>> y = np.array([[4], [5], [6]])
768 >>> b = np.broadcast(x, y)
769 >>> b.index
770 0
771 >>> next(b), next(b), next(b)
772 ((1, 4), (2, 4), (3, 4))
773 >>> b.index
774 3
775 >>> b.reset()
776 >>> b.index
777 0
779 """))
781###############################################################################
782#
783# numpy functions
784#
785###############################################################################
787add_newdoc('numpy.core.multiarray', 'array',
788 """
789 array(object, dtype=None, *, copy=True, order='K', subok=False, ndmin=0)
791 Create an array.
793 Parameters
794 ----------
795 object : array_like
796 An array, any object exposing the array interface, an object whose
797 __array__ method returns an array, or any (nested) sequence.
798 dtype : data-type, optional
799 The desired data-type for the array. If not given, then the type will
800 be determined as the minimum type required to hold the objects in the
801 sequence.
802 copy : bool, optional
803 If true (default), then the object is copied. Otherwise, a copy will
804 only be made if __array__ returns a copy, if obj is a nested sequence,
805 or if a copy is needed to satisfy any of the other requirements
806 (`dtype`, `order`, etc.).
807 order : {'K', 'A', 'C', 'F'}, optional
808 Specify the memory layout of the array. If object is not an array, the
809 newly created array will be in C order (row major) unless 'F' is
810 specified, in which case it will be in Fortran order (column major).
811 If object is an array the following holds.
813 ===== ========= ===================================================
814 order no copy copy=True
815 ===== ========= ===================================================
816 'K' unchanged F & C order preserved, otherwise most similar order
817 'A' unchanged F order if input is F and not C, otherwise C order
818 'C' C order C order
819 'F' F order F order
820 ===== ========= ===================================================
822 When ``copy=False`` and a copy is made for other reasons, the result is
823 the same as if ``copy=True``, with some exceptions for `A`, see the
824 Notes section. The default order is 'K'.
825 subok : bool, optional
826 If True, then sub-classes will be passed-through, otherwise
827 the returned array will be forced to be a base-class array (default).
828 ndmin : int, optional
829 Specifies the minimum number of dimensions that the resulting
830 array should have. Ones will be pre-pended to the shape as
831 needed to meet this requirement.
833 Returns
834 -------
835 out : ndarray
836 An array object satisfying the specified requirements.
838 See Also
839 --------
840 empty_like : Return an empty array with shape and type of input.
841 ones_like : Return an array of ones with shape and type of input.
842 zeros_like : Return an array of zeros with shape and type of input.
843 full_like : Return a new array with shape of input filled with value.
844 empty : Return a new uninitialized array.
845 ones : Return a new array setting values to one.
846 zeros : Return a new array setting values to zero.
847 full : Return a new array of given shape filled with value.
850 Notes
851 -----
852 When order is 'A' and `object` is an array in neither 'C' nor 'F' order,
853 and a copy is forced by a change in dtype, then the order of the result is
854 not necessarily 'C' as expected. This is likely a bug.
856 Examples
857 --------
858 >>> np.array([1, 2, 3])
859 array([1, 2, 3])
861 Upcasting:
863 >>> np.array([1, 2, 3.0])
864 array([ 1., 2., 3.])
866 More than one dimension:
868 >>> np.array([[1, 2], [3, 4]])
869 array([[1, 2],
870 [3, 4]])
872 Minimum dimensions 2:
874 >>> np.array([1, 2, 3], ndmin=2)
875 array([[1, 2, 3]])
877 Type provided:
879 >>> np.array([1, 2, 3], dtype=complex)
880 array([ 1.+0.j, 2.+0.j, 3.+0.j])
882 Data-type consisting of more than one element:
884 >>> x = np.array([(1,2),(3,4)],dtype=[('a','<i4'),('b','<i4')])
885 >>> x['a']
886 array([1, 3])
888 Creating an array from sub-classes:
890 >>> np.array(np.mat('1 2; 3 4'))
891 array([[1, 2],
892 [3, 4]])
894 >>> np.array(np.mat('1 2; 3 4'), subok=True)
895 matrix([[1, 2],
896 [3, 4]])
898 """)
900add_newdoc('numpy.core.multiarray', 'empty',
901 """
902 empty(shape, dtype=float, order='C')
904 Return a new array of given shape and type, without initializing entries.
906 Parameters
907 ----------
908 shape : int or tuple of int
909 Shape of the empty array, e.g., ``(2, 3)`` or ``2``.
910 dtype : data-type, optional
911 Desired output data-type for the array, e.g, `numpy.int8`. Default is
912 `numpy.float64`.
913 order : {'C', 'F'}, optional, default: 'C'
914 Whether to store multi-dimensional data in row-major
915 (C-style) or column-major (Fortran-style) order in
916 memory.
918 Returns
919 -------
920 out : ndarray
921 Array of uninitialized (arbitrary) data of the given shape, dtype, and
922 order. Object arrays will be initialized to None.
924 See Also
925 --------
926 empty_like : Return an empty array with shape and type of input.
927 ones : Return a new array setting values to one.
928 zeros : Return a new array setting values to zero.
929 full : Return a new array of given shape filled with value.
932 Notes
933 -----
934 `empty`, unlike `zeros`, does not set the array values to zero,
935 and may therefore be marginally faster. On the other hand, it requires
936 the user to manually set all the values in the array, and should be
937 used with caution.
939 Examples
940 --------
941 >>> np.empty([2, 2])
942 array([[ -9.74499359e+001, 6.69583040e-309],
943 [ 2.13182611e-314, 3.06959433e-309]]) #uninitialized
945 >>> np.empty([2, 2], dtype=int)
946 array([[-1073741821, -1067949133],
947 [ 496041986, 19249760]]) #uninitialized
949 """)
951add_newdoc('numpy.core.multiarray', 'scalar',
952 """
953 scalar(dtype, obj)
955 Return a new scalar array of the given type initialized with obj.
957 This function is meant mainly for pickle support. `dtype` must be a
958 valid data-type descriptor. If `dtype` corresponds to an object
959 descriptor, then `obj` can be any object, otherwise `obj` must be a
960 string. If `obj` is not given, it will be interpreted as None for object
961 type and as zeros for all other types.
963 """)
965add_newdoc('numpy.core.multiarray', 'zeros',
966 """
967 zeros(shape, dtype=float, order='C')
969 Return a new array of given shape and type, filled with zeros.
971 Parameters
972 ----------
973 shape : int or tuple of ints
974 Shape of the new array, e.g., ``(2, 3)`` or ``2``.
975 dtype : data-type, optional
976 The desired data-type for the array, e.g., `numpy.int8`. Default is
977 `numpy.float64`.
978 order : {'C', 'F'}, optional, default: 'C'
979 Whether to store multi-dimensional data in row-major
980 (C-style) or column-major (Fortran-style) order in
981 memory.
983 Returns
984 -------
985 out : ndarray
986 Array of zeros with the given shape, dtype, and order.
988 See Also
989 --------
990 zeros_like : Return an array of zeros with shape and type of input.
991 empty : Return a new uninitialized array.
992 ones : Return a new array setting values to one.
993 full : Return a new array of given shape filled with value.
995 Examples
996 --------
997 >>> np.zeros(5)
998 array([ 0., 0., 0., 0., 0.])
1000 >>> np.zeros((5,), dtype=int)
1001 array([0, 0, 0, 0, 0])
1003 >>> np.zeros((2, 1))
1004 array([[ 0.],
1005 [ 0.]])
1007 >>> s = (2,2)
1008 >>> np.zeros(s)
1009 array([[ 0., 0.],
1010 [ 0., 0.]])
1012 >>> np.zeros((2,), dtype=[('x', 'i4'), ('y', 'i4')]) # custom dtype
1013 array([(0, 0), (0, 0)],
1014 dtype=[('x', '<i4'), ('y', '<i4')])
1016 """)
1018add_newdoc('numpy.core.multiarray', 'set_typeDict',
1019 """set_typeDict(dict)
1021 Set the internal dictionary that can look up an array type using a
1022 registered code.
1024 """)
1026add_newdoc('numpy.core.multiarray', 'fromstring',
1027 """
1028 fromstring(string, dtype=float, count=-1, sep='')
1030 A new 1-D array initialized from text data in a string.
1032 Parameters
1033 ----------
1034 string : str
1035 A string containing the data.
1036 dtype : data-type, optional
1037 The data type of the array; default: float. For binary input data,
1038 the data must be in exactly this format. Most builtin numeric types are
1039 supported and extension types may be supported.
1041 .. versionadded:: 1.18.0
1042 Complex dtypes.
1044 count : int, optional
1045 Read this number of `dtype` elements from the data. If this is
1046 negative (the default), the count will be determined from the
1047 length of the data.
1048 sep : str, optional
1049 The string separating numbers in the data; extra whitespace between
1050 elements is also ignored.
1052 .. deprecated:: 1.14
1053 Passing ``sep=''``, the default, is deprecated since it will
1054 trigger the deprecated binary mode of this function. This mode
1055 interprets `string` as binary bytes, rather than ASCII text with
1056 decimal numbers, an operation which is better spelt
1057 ``frombuffer(string, dtype, count)``. If `string` contains unicode
1058 text, the binary mode of `fromstring` will first encode it into
1059 bytes using either utf-8 (python 3) or the default encoding
1060 (python 2), neither of which produce sane results.
1062 Returns
1063 -------
1064 arr : ndarray
1065 The constructed array.
1067 Raises
1068 ------
1069 ValueError
1070 If the string is not the correct size to satisfy the requested
1071 `dtype` and `count`.
1073 See Also
1074 --------
1075 frombuffer, fromfile, fromiter
1077 Examples
1078 --------
1079 >>> np.fromstring('1 2', dtype=int, sep=' ')
1080 array([1, 2])
1081 >>> np.fromstring('1, 2', dtype=int, sep=',')
1082 array([1, 2])
1084 """)
1086add_newdoc('numpy.core.multiarray', 'compare_chararrays',
1087 """
1088 compare_chararrays(a, b, cmp_op, rstrip)
1090 Performs element-wise comparison of two string arrays using the
1091 comparison operator specified by `cmp_op`.
1093 Parameters
1094 ----------
1095 a, b : array_like
1096 Arrays to be compared.
1097 cmp_op : {"<", "<=", "==", ">=", ">", "!="}
1098 Type of comparison.
1099 rstrip : Boolean
1100 If True, the spaces at the end of Strings are removed before the comparison.
1102 Returns
1103 -------
1104 out : ndarray
1105 The output array of type Boolean with the same shape as a and b.
1107 Raises
1108 ------
1109 ValueError
1110 If `cmp_op` is not valid.
1111 TypeError
1112 If at least one of `a` or `b` is a non-string array
1114 Examples
1115 --------
1116 >>> a = np.array(["a", "b", "cde"])
1117 >>> b = np.array(["a", "a", "dec"])
1118 >>> np.compare_chararrays(a, b, ">", True)
1119 array([False, True, False])
1121 """)
1123add_newdoc('numpy.core.multiarray', 'fromiter',
1124 """
1125 fromiter(iterable, dtype, count=-1)
1127 Create a new 1-dimensional array from an iterable object.
1129 Parameters
1130 ----------
1131 iterable : iterable object
1132 An iterable object providing data for the array.
1133 dtype : data-type
1134 The data-type of the returned array.
1135 count : int, optional
1136 The number of items to read from *iterable*. The default is -1,
1137 which means all data is read.
1139 Returns
1140 -------
1141 out : ndarray
1142 The output array.
1144 Notes
1145 -----
1146 Specify `count` to improve performance. It allows ``fromiter`` to
1147 pre-allocate the output array, instead of resizing it on demand.
1149 Examples
1150 --------
1151 >>> iterable = (x*x for x in range(5))
1152 >>> np.fromiter(iterable, float)
1153 array([ 0., 1., 4., 9., 16.])
1155 """)
1157add_newdoc('numpy.core.multiarray', 'fromfile',
1158 """
1159 fromfile(file, dtype=float, count=-1, sep='', offset=0)
1161 Construct an array from data in a text or binary file.
1163 A highly efficient way of reading binary data with a known data-type,
1164 as well as parsing simply formatted text files. Data written using the
1165 `tofile` method can be read using this function.
1167 Parameters
1168 ----------
1169 file : file or str or Path
1170 Open file object or filename.
1172 .. versionchanged:: 1.17.0
1173 `pathlib.Path` objects are now accepted.
1175 dtype : data-type
1176 Data type of the returned array.
1177 For binary files, it is used to determine the size and byte-order
1178 of the items in the file.
1179 Most builtin numeric types are supported and extension types may be supported.
1181 .. versionadded:: 1.18.0
1182 Complex dtypes.
1184 count : int
1185 Number of items to read. ``-1`` means all items (i.e., the complete
1186 file).
1187 sep : str
1188 Separator between items if file is a text file.
1189 Empty ("") separator means the file should be treated as binary.
1190 Spaces (" ") in the separator match zero or more whitespace characters.
1191 A separator consisting only of spaces must match at least one
1192 whitespace.
1193 offset : int
1194 The offset (in bytes) from the file's current position. Defaults to 0.
1195 Only permitted for binary files.
1197 .. versionadded:: 1.17.0
1199 See also
1200 --------
1201 load, save
1202 ndarray.tofile
1203 loadtxt : More flexible way of loading data from a text file.
1205 Notes
1206 -----
1207 Do not rely on the combination of `tofile` and `fromfile` for
1208 data storage, as the binary files generated are not platform
1209 independent. In particular, no byte-order or data-type information is
1210 saved. Data can be stored in the platform independent ``.npy`` format
1211 using `save` and `load` instead.
1213 Examples
1214 --------
1215 Construct an ndarray:
1217 >>> dt = np.dtype([('time', [('min', np.int64), ('sec', np.int64)]),
1218 ... ('temp', float)])
1219 >>> x = np.zeros((1,), dtype=dt)
1220 >>> x['time']['min'] = 10; x['temp'] = 98.25
1221 >>> x
1222 array([((10, 0), 98.25)],
1223 dtype=[('time', [('min', '<i8'), ('sec', '<i8')]), ('temp', '<f8')])
1225 Save the raw data to disk:
1227 >>> import tempfile
1228 >>> fname = tempfile.mkstemp()[1]
1229 >>> x.tofile(fname)
1231 Read the raw data from disk:
1233 >>> np.fromfile(fname, dtype=dt)
1234 array([((10, 0), 98.25)],
1235 dtype=[('time', [('min', '<i8'), ('sec', '<i8')]), ('temp', '<f8')])
1237 The recommended way to store and load data:
1239 >>> np.save(fname, x)
1240 >>> np.load(fname + '.npy')
1241 array([((10, 0), 98.25)],
1242 dtype=[('time', [('min', '<i8'), ('sec', '<i8')]), ('temp', '<f8')])
1244 """)
1246add_newdoc('numpy.core.multiarray', 'frombuffer',
1247 """
1248 frombuffer(buffer, dtype=float, count=-1, offset=0)
1250 Interpret a buffer as a 1-dimensional array.
1252 Parameters
1253 ----------
1254 buffer : buffer_like
1255 An object that exposes the buffer interface.
1256 dtype : data-type, optional
1257 Data-type of the returned array; default: float.
1258 count : int, optional
1259 Number of items to read. ``-1`` means all data in the buffer.
1260 offset : int, optional
1261 Start reading the buffer from this offset (in bytes); default: 0.
1263 Notes
1264 -----
1265 If the buffer has data that is not in machine byte-order, this should
1266 be specified as part of the data-type, e.g.::
1268 >>> dt = np.dtype(int)
1269 >>> dt = dt.newbyteorder('>')
1270 >>> np.frombuffer(buf, dtype=dt) # doctest: +SKIP
1272 The data of the resulting array will not be byteswapped, but will be
1273 interpreted correctly.
1275 Examples
1276 --------
1277 >>> s = b'hello world'
1278 >>> np.frombuffer(s, dtype='S1', count=5, offset=6)
1279 array([b'w', b'o', b'r', b'l', b'd'], dtype='|S1')
1281 >>> np.frombuffer(b'\\x01\\x02', dtype=np.uint8)
1282 array([1, 2], dtype=uint8)
1283 >>> np.frombuffer(b'\\x01\\x02\\x03\\x04\\x05', dtype=np.uint8, count=3)
1284 array([1, 2, 3], dtype=uint8)
1286 """)
1288add_newdoc('numpy.core', 'fastCopyAndTranspose',
1289 """_fastCopyAndTranspose(a)""")
1291add_newdoc('numpy.core.multiarray', 'correlate',
1292 """cross_correlate(a,v, mode=0)""")
1294add_newdoc('numpy.core.multiarray', 'arange',
1295 """
1296 arange([start,] stop[, step,], dtype=None)
1298 Return evenly spaced values within a given interval.
1300 Values are generated within the half-open interval ``[start, stop)``
1301 (in other words, the interval including `start` but excluding `stop`).
1302 For integer arguments the function is equivalent to the Python built-in
1303 `range` function, but returns an ndarray rather than a list.
1305 When using a non-integer step, such as 0.1, the results will often not
1306 be consistent. It is better to use `numpy.linspace` for these cases.
1308 Parameters
1309 ----------
1310 start : number, optional
1311 Start of interval. The interval includes this value. The default
1312 start value is 0.
1313 stop : number
1314 End of interval. The interval does not include this value, except
1315 in some cases where `step` is not an integer and floating point
1316 round-off affects the length of `out`.
1317 step : number, optional
1318 Spacing between values. For any output `out`, this is the distance
1319 between two adjacent values, ``out[i+1] - out[i]``. The default
1320 step size is 1. If `step` is specified as a position argument,
1321 `start` must also be given.
1322 dtype : dtype
1323 The type of the output array. If `dtype` is not given, infer the data
1324 type from the other input arguments.
1326 Returns
1327 -------
1328 arange : ndarray
1329 Array of evenly spaced values.
1331 For floating point arguments, the length of the result is
1332 ``ceil((stop - start)/step)``. Because of floating point overflow,
1333 this rule may result in the last element of `out` being greater
1334 than `stop`.
1336 See Also
1337 --------
1338 numpy.linspace : Evenly spaced numbers with careful handling of endpoints.
1339 numpy.ogrid: Arrays of evenly spaced numbers in N-dimensions.
1340 numpy.mgrid: Grid-shaped arrays of evenly spaced numbers in N-dimensions.
1342 Examples
1343 --------
1344 >>> np.arange(3)
1345 array([0, 1, 2])
1346 >>> np.arange(3.0)
1347 array([ 0., 1., 2.])
1348 >>> np.arange(3,7)
1349 array([3, 4, 5, 6])
1350 >>> np.arange(3,7,2)
1351 array([3, 5])
1353 """)
1355add_newdoc('numpy.core.multiarray', '_get_ndarray_c_version',
1356 """_get_ndarray_c_version()
1358 Return the compile time NPY_VERSION (formerly called NDARRAY_VERSION) number.
1360 """)
1362add_newdoc('numpy.core.multiarray', '_reconstruct',
1363 """_reconstruct(subtype, shape, dtype)
1365 Construct an empty array. Used by Pickles.
1367 """)
1370add_newdoc('numpy.core.multiarray', 'set_string_function',
1371 """
1372 set_string_function(f, repr=1)
1374 Internal method to set a function to be used when pretty printing arrays.
1376 """)
1378add_newdoc('numpy.core.multiarray', 'set_numeric_ops',
1379 """
1380 set_numeric_ops(op1=func1, op2=func2, ...)
1382 Set numerical operators for array objects.
1384 .. deprecated:: 1.16
1386 For the general case, use :c:func:`PyUFunc_ReplaceLoopBySignature`.
1387 For ndarray subclasses, define the ``__array_ufunc__`` method and
1388 override the relevant ufunc.
1390 Parameters
1391 ----------
1392 op1, op2, ... : callable
1393 Each ``op = func`` pair describes an operator to be replaced.
1394 For example, ``add = lambda x, y: np.add(x, y) % 5`` would replace
1395 addition by modulus 5 addition.
1397 Returns
1398 -------
1399 saved_ops : list of callables
1400 A list of all operators, stored before making replacements.
1402 Notes
1403 -----
1404 .. WARNING::
1405 Use with care! Incorrect usage may lead to memory errors.
1407 A function replacing an operator cannot make use of that operator.
1408 For example, when replacing add, you may not use ``+``. Instead,
1409 directly call ufuncs.
1411 Examples
1412 --------
1413 >>> def add_mod5(x, y):
1414 ... return np.add(x, y) % 5
1415 ...
1416 >>> old_funcs = np.set_numeric_ops(add=add_mod5)
1418 >>> x = np.arange(12).reshape((3, 4))
1419 >>> x + x
1420 array([[0, 2, 4, 1],
1421 [3, 0, 2, 4],
1422 [1, 3, 0, 2]])
1424 >>> ignore = np.set_numeric_ops(**old_funcs) # restore operators
1426 """)
1428add_newdoc('numpy.core.multiarray', 'promote_types',
1429 """
1430 promote_types(type1, type2)
1432 Returns the data type with the smallest size and smallest scalar
1433 kind to which both ``type1`` and ``type2`` may be safely cast.
1434 The returned data type is always in native byte order.
1436 This function is symmetric, but rarely associative.
1438 Parameters
1439 ----------
1440 type1 : dtype or dtype specifier
1441 First data type.
1442 type2 : dtype or dtype specifier
1443 Second data type.
1445 Returns
1446 -------
1447 out : dtype
1448 The promoted data type.
1450 Notes
1451 -----
1452 .. versionadded:: 1.6.0
1454 Starting in NumPy 1.9, promote_types function now returns a valid string
1455 length when given an integer or float dtype as one argument and a string
1456 dtype as another argument. Previously it always returned the input string
1457 dtype, even if it wasn't long enough to store the max integer/float value
1458 converted to a string.
1460 See Also
1461 --------
1462 result_type, dtype, can_cast
1464 Examples
1465 --------
1466 >>> np.promote_types('f4', 'f8')
1467 dtype('float64')
1469 >>> np.promote_types('i8', 'f4')
1470 dtype('float64')
1472 >>> np.promote_types('>i8', '<c8')
1473 dtype('complex128')
1475 >>> np.promote_types('i4', 'S8')
1476 dtype('S11')
1478 An example of a non-associative case:
1480 >>> p = np.promote_types
1481 >>> p('S', p('i1', 'u1'))
1482 dtype('S6')
1483 >>> p(p('S', 'i1'), 'u1')
1484 dtype('S4')
1486 """)
1488add_newdoc('numpy.core.multiarray', 'c_einsum',
1489 """
1490 c_einsum(subscripts, *operands, out=None, dtype=None, order='K',
1491 casting='safe')
1493 *This documentation shadows that of the native python implementation of the `einsum` function,
1494 except all references and examples related to the `optimize` argument (v 0.12.0) have been removed.*
1496 Evaluates the Einstein summation convention on the operands.
1498 Using the Einstein summation convention, many common multi-dimensional,
1499 linear algebraic array operations can be represented in a simple fashion.
1500 In *implicit* mode `einsum` computes these values.
1502 In *explicit* mode, `einsum` provides further flexibility to compute
1503 other array operations that might not be considered classical Einstein
1504 summation operations, by disabling, or forcing summation over specified
1505 subscript labels.
1507 See the notes and examples for clarification.
1509 Parameters
1510 ----------
1511 subscripts : str
1512 Specifies the subscripts for summation as comma separated list of
1513 subscript labels. An implicit (classical Einstein summation)
1514 calculation is performed unless the explicit indicator '->' is
1515 included as well as subscript labels of the precise output form.
1516 operands : list of array_like
1517 These are the arrays for the operation.
1518 out : ndarray, optional
1519 If provided, the calculation is done into this array.
1520 dtype : {data-type, None}, optional
1521 If provided, forces the calculation to use the data type specified.
1522 Note that you may have to also give a more liberal `casting`
1523 parameter to allow the conversions. Default is None.
1524 order : {'C', 'F', 'A', 'K'}, optional
1525 Controls the memory layout of the output. 'C' means it should
1526 be C contiguous. 'F' means it should be Fortran contiguous,
1527 'A' means it should be 'F' if the inputs are all 'F', 'C' otherwise.
1528 'K' means it should be as close to the layout as the inputs as
1529 is possible, including arbitrarily permuted axes.
1530 Default is 'K'.
1531 casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional
1532 Controls what kind of data casting may occur. Setting this to
1533 'unsafe' is not recommended, as it can adversely affect accumulations.
1535 * 'no' means the data types should not be cast at all.
1536 * 'equiv' means only byte-order changes are allowed.
1537 * 'safe' means only casts which can preserve values are allowed.
1538 * 'same_kind' means only safe casts or casts within a kind,
1539 like float64 to float32, are allowed.
1540 * 'unsafe' means any data conversions may be done.
1542 Default is 'safe'.
1543 optimize : {False, True, 'greedy', 'optimal'}, optional
1544 Controls if intermediate optimization should occur. No optimization
1545 will occur if False and True will default to the 'greedy' algorithm.
1546 Also accepts an explicit contraction list from the ``np.einsum_path``
1547 function. See ``np.einsum_path`` for more details. Defaults to False.
1549 Returns
1550 -------
1551 output : ndarray
1552 The calculation based on the Einstein summation convention.
1554 See Also
1555 --------
1556 einsum_path, dot, inner, outer, tensordot, linalg.multi_dot
1558 Notes
1559 -----
1560 .. versionadded:: 1.6.0
1562 The Einstein summation convention can be used to compute
1563 many multi-dimensional, linear algebraic array operations. `einsum`
1564 provides a succinct way of representing these.
1566 A non-exhaustive list of these operations,
1567 which can be computed by `einsum`, is shown below along with examples:
1569 * Trace of an array, :py:func:`numpy.trace`.
1570 * Return a diagonal, :py:func:`numpy.diag`.
1571 * Array axis summations, :py:func:`numpy.sum`.
1572 * Transpositions and permutations, :py:func:`numpy.transpose`.
1573 * Matrix multiplication and dot product, :py:func:`numpy.matmul` :py:func:`numpy.dot`.
1574 * Vector inner and outer products, :py:func:`numpy.inner` :py:func:`numpy.outer`.
1575 * Broadcasting, element-wise and scalar multiplication, :py:func:`numpy.multiply`.
1576 * Tensor contractions, :py:func:`numpy.tensordot`.
1577 * Chained array operations, in efficient calculation order, :py:func:`numpy.einsum_path`.
1579 The subscripts string is a comma-separated list of subscript labels,
1580 where each label refers to a dimension of the corresponding operand.
1581 Whenever a label is repeated it is summed, so ``np.einsum('i,i', a, b)``
1582 is equivalent to :py:func:`np.inner(a,b) <numpy.inner>`. If a label
1583 appears only once, it is not summed, so ``np.einsum('i', a)`` produces a
1584 view of ``a`` with no changes. A further example ``np.einsum('ij,jk', a, b)``
1585 describes traditional matrix multiplication and is equivalent to
1586 :py:func:`np.matmul(a,b) <numpy.matmul>`. Repeated subscript labels in one
1587 operand take the diagonal. For example, ``np.einsum('ii', a)`` is equivalent
1588 to :py:func:`np.trace(a) <numpy.trace>`.
1590 In *implicit mode*, the chosen subscripts are important
1591 since the axes of the output are reordered alphabetically. This
1592 means that ``np.einsum('ij', a)`` doesn't affect a 2D array, while
1593 ``np.einsum('ji', a)`` takes its transpose. Additionally,
1594 ``np.einsum('ij,jk', a, b)`` returns a matrix multiplication, while,
1595 ``np.einsum('ij,jh', a, b)`` returns the transpose of the
1596 multiplication since subscript 'h' precedes subscript 'i'.
1598 In *explicit mode* the output can be directly controlled by
1599 specifying output subscript labels. This requires the
1600 identifier '->' as well as the list of output subscript labels.
1601 This feature increases the flexibility of the function since
1602 summing can be disabled or forced when required. The call
1603 ``np.einsum('i->', a)`` is like :py:func:`np.sum(a, axis=-1) <numpy.sum>`,
1604 and ``np.einsum('ii->i', a)`` is like :py:func:`np.diag(a) <numpy.diag>`.
1605 The difference is that `einsum` does not allow broadcasting by default.
1606 Additionally ``np.einsum('ij,jh->ih', a, b)`` directly specifies the
1607 order of the output subscript labels and therefore returns matrix
1608 multiplication, unlike the example above in implicit mode.
1610 To enable and control broadcasting, use an ellipsis. Default
1611 NumPy-style broadcasting is done by adding an ellipsis
1612 to the left of each term, like ``np.einsum('...ii->...i', a)``.
1613 To take the trace along the first and last axes,
1614 you can do ``np.einsum('i...i', a)``, or to do a matrix-matrix
1615 product with the left-most indices instead of rightmost, one can do
1616 ``np.einsum('ij...,jk...->ik...', a, b)``.
1618 When there is only one operand, no axes are summed, and no output
1619 parameter is provided, a view into the operand is returned instead
1620 of a new array. Thus, taking the diagonal as ``np.einsum('ii->i', a)``
1621 produces a view (changed in version 1.10.0).
1623 `einsum` also provides an alternative way to provide the subscripts
1624 and operands as ``einsum(op0, sublist0, op1, sublist1, ..., [sublistout])``.
1625 If the output shape is not provided in this format `einsum` will be
1626 calculated in implicit mode, otherwise it will be performed explicitly.
1627 The examples below have corresponding `einsum` calls with the two
1628 parameter methods.
1630 .. versionadded:: 1.10.0
1632 Views returned from einsum are now writeable whenever the input array
1633 is writeable. For example, ``np.einsum('ijk...->kji...', a)`` will now
1634 have the same effect as :py:func:`np.swapaxes(a, 0, 2) <numpy.swapaxes>`
1635 and ``np.einsum('ii->i', a)`` will return a writeable view of the diagonal
1636 of a 2D array.
1638 Examples
1639 --------
1640 >>> a = np.arange(25).reshape(5,5)
1641 >>> b = np.arange(5)
1642 >>> c = np.arange(6).reshape(2,3)
1644 Trace of a matrix:
1646 >>> np.einsum('ii', a)
1647 60
1648 >>> np.einsum(a, [0,0])
1649 60
1650 >>> np.trace(a)
1651 60
1653 Extract the diagonal (requires explicit form):
1655 >>> np.einsum('ii->i', a)
1656 array([ 0, 6, 12, 18, 24])
1657 >>> np.einsum(a, [0,0], [0])
1658 array([ 0, 6, 12, 18, 24])
1659 >>> np.diag(a)
1660 array([ 0, 6, 12, 18, 24])
1662 Sum over an axis (requires explicit form):
1664 >>> np.einsum('ij->i', a)
1665 array([ 10, 35, 60, 85, 110])
1666 >>> np.einsum(a, [0,1], [0])
1667 array([ 10, 35, 60, 85, 110])
1668 >>> np.sum(a, axis=1)
1669 array([ 10, 35, 60, 85, 110])
1671 For higher dimensional arrays summing a single axis can be done with ellipsis:
1673 >>> np.einsum('...j->...', a)
1674 array([ 10, 35, 60, 85, 110])
1675 >>> np.einsum(a, [Ellipsis,1], [Ellipsis])
1676 array([ 10, 35, 60, 85, 110])
1678 Compute a matrix transpose, or reorder any number of axes:
1680 >>> np.einsum('ji', c)
1681 array([[0, 3],
1682 [1, 4],
1683 [2, 5]])
1684 >>> np.einsum('ij->ji', c)
1685 array([[0, 3],
1686 [1, 4],
1687 [2, 5]])
1688 >>> np.einsum(c, [1,0])
1689 array([[0, 3],
1690 [1, 4],
1691 [2, 5]])
1692 >>> np.transpose(c)
1693 array([[0, 3],
1694 [1, 4],
1695 [2, 5]])
1697 Vector inner products:
1699 >>> np.einsum('i,i', b, b)
1700 30
1701 >>> np.einsum(b, [0], b, [0])
1702 30
1703 >>> np.inner(b,b)
1704 30
1706 Matrix vector multiplication:
1708 >>> np.einsum('ij,j', a, b)
1709 array([ 30, 80, 130, 180, 230])
1710 >>> np.einsum(a, [0,1], b, [1])
1711 array([ 30, 80, 130, 180, 230])
1712 >>> np.dot(a, b)
1713 array([ 30, 80, 130, 180, 230])
1714 >>> np.einsum('...j,j', a, b)
1715 array([ 30, 80, 130, 180, 230])
1717 Broadcasting and scalar multiplication:
1719 >>> np.einsum('..., ...', 3, c)
1720 array([[ 0, 3, 6],
1721 [ 9, 12, 15]])
1722 >>> np.einsum(',ij', 3, c)
1723 array([[ 0, 3, 6],
1724 [ 9, 12, 15]])
1725 >>> np.einsum(3, [Ellipsis], c, [Ellipsis])
1726 array([[ 0, 3, 6],
1727 [ 9, 12, 15]])
1728 >>> np.multiply(3, c)
1729 array([[ 0, 3, 6],
1730 [ 9, 12, 15]])
1732 Vector outer product:
1734 >>> np.einsum('i,j', np.arange(2)+1, b)
1735 array([[0, 1, 2, 3, 4],
1736 [0, 2, 4, 6, 8]])
1737 >>> np.einsum(np.arange(2)+1, [0], b, [1])
1738 array([[0, 1, 2, 3, 4],
1739 [0, 2, 4, 6, 8]])
1740 >>> np.outer(np.arange(2)+1, b)
1741 array([[0, 1, 2, 3, 4],
1742 [0, 2, 4, 6, 8]])
1744 Tensor contraction:
1746 >>> a = np.arange(60.).reshape(3,4,5)
1747 >>> b = np.arange(24.).reshape(4,3,2)
1748 >>> np.einsum('ijk,jil->kl', a, b)
1749 array([[ 4400., 4730.],
1750 [ 4532., 4874.],
1751 [ 4664., 5018.],
1752 [ 4796., 5162.],
1753 [ 4928., 5306.]])
1754 >>> np.einsum(a, [0,1,2], b, [1,0,3], [2,3])
1755 array([[ 4400., 4730.],
1756 [ 4532., 4874.],
1757 [ 4664., 5018.],
1758 [ 4796., 5162.],
1759 [ 4928., 5306.]])
1760 >>> np.tensordot(a,b, axes=([1,0],[0,1]))
1761 array([[ 4400., 4730.],
1762 [ 4532., 4874.],
1763 [ 4664., 5018.],
1764 [ 4796., 5162.],
1765 [ 4928., 5306.]])
1767 Writeable returned arrays (since version 1.10.0):
1769 >>> a = np.zeros((3, 3))
1770 >>> np.einsum('ii->i', a)[:] = 1
1771 >>> a
1772 array([[ 1., 0., 0.],
1773 [ 0., 1., 0.],
1774 [ 0., 0., 1.]])
1776 Example of ellipsis use:
1778 >>> a = np.arange(6).reshape((3,2))
1779 >>> b = np.arange(12).reshape((4,3))
1780 >>> np.einsum('ki,jk->ij', a, b)
1781 array([[10, 28, 46, 64],
1782 [13, 40, 67, 94]])
1783 >>> np.einsum('ki,...k->i...', a, b)
1784 array([[10, 28, 46, 64],
1785 [13, 40, 67, 94]])
1786 >>> np.einsum('k...,jk', a, b)
1787 array([[10, 28, 46, 64],
1788 [13, 40, 67, 94]])
1790 """)
1793##############################################################################
1794#
1795# Documentation for ndarray attributes and methods
1796#
1797##############################################################################
1800##############################################################################
1801#
1802# ndarray object
1803#
1804##############################################################################
1807add_newdoc('numpy.core.multiarray', 'ndarray',
1808 """
1809 ndarray(shape, dtype=float, buffer=None, offset=0,
1810 strides=None, order=None)
1812 An array object represents a multidimensional, homogeneous array
1813 of fixed-size items. An associated data-type object describes the
1814 format of each element in the array (its byte-order, how many bytes it
1815 occupies in memory, whether it is an integer, a floating point number,
1816 or something else, etc.)
1818 Arrays should be constructed using `array`, `zeros` or `empty` (refer
1819 to the See Also section below). The parameters given here refer to
1820 a low-level method (`ndarray(...)`) for instantiating an array.
1822 For more information, refer to the `numpy` module and examine the
1823 methods and attributes of an array.
1825 Parameters
1826 ----------
1827 (for the __new__ method; see Notes below)
1829 shape : tuple of ints
1830 Shape of created array.
1831 dtype : data-type, optional
1832 Any object that can be interpreted as a numpy data type.
1833 buffer : object exposing buffer interface, optional
1834 Used to fill the array with data.
1835 offset : int, optional
1836 Offset of array data in buffer.
1837 strides : tuple of ints, optional
1838 Strides of data in memory.
1839 order : {'C', 'F'}, optional
1840 Row-major (C-style) or column-major (Fortran-style) order.
1842 Attributes
1843 ----------
1844 T : ndarray
1845 Transpose of the array.
1846 data : buffer
1847 The array's elements, in memory.
1848 dtype : dtype object
1849 Describes the format of the elements in the array.
1850 flags : dict
1851 Dictionary containing information related to memory use, e.g.,
1852 'C_CONTIGUOUS', 'OWNDATA', 'WRITEABLE', etc.
1853 flat : numpy.flatiter object
1854 Flattened version of the array as an iterator. The iterator
1855 allows assignments, e.g., ``x.flat = 3`` (See `ndarray.flat` for
1856 assignment examples; TODO).
1857 imag : ndarray
1858 Imaginary part of the array.
1859 real : ndarray
1860 Real part of the array.
1861 size : int
1862 Number of elements in the array.
1863 itemsize : int
1864 The memory use of each array element in bytes.
1865 nbytes : int
1866 The total number of bytes required to store the array data,
1867 i.e., ``itemsize * size``.
1868 ndim : int
1869 The array's number of dimensions.
1870 shape : tuple of ints
1871 Shape of the array.
1872 strides : tuple of ints
1873 The step-size required to move from one element to the next in
1874 memory. For example, a contiguous ``(3, 4)`` array of type
1875 ``int16`` in C-order has strides ``(8, 2)``. This implies that
1876 to move from element to element in memory requires jumps of 2 bytes.
1877 To move from row-to-row, one needs to jump 8 bytes at a time
1878 (``2 * 4``).
1879 ctypes : ctypes object
1880 Class containing properties of the array needed for interaction
1881 with ctypes.
1882 base : ndarray
1883 If the array is a view into another array, that array is its `base`
1884 (unless that array is also a view). The `base` array is where the
1885 array data is actually stored.
1887 See Also
1888 --------
1889 array : Construct an array.
1890 zeros : Create an array, each element of which is zero.
1891 empty : Create an array, but leave its allocated memory unchanged (i.e.,
1892 it contains "garbage").
1893 dtype : Create a data-type.
1895 Notes
1896 -----
1897 There are two modes of creating an array using ``__new__``:
1899 1. If `buffer` is None, then only `shape`, `dtype`, and `order`
1900 are used.
1901 2. If `buffer` is an object exposing the buffer interface, then
1902 all keywords are interpreted.
1904 No ``__init__`` method is needed because the array is fully initialized
1905 after the ``__new__`` method.
1907 Examples
1908 --------
1909 These examples illustrate the low-level `ndarray` constructor. Refer
1910 to the `See Also` section above for easier ways of constructing an
1911 ndarray.
1913 First mode, `buffer` is None:
1915 >>> np.ndarray(shape=(2,2), dtype=float, order='F')
1916 array([[0.0e+000, 0.0e+000], # random
1917 [ nan, 2.5e-323]])
1919 Second mode:
1921 >>> np.ndarray((2,), buffer=np.array([1,2,3]),
1922 ... offset=np.int_().itemsize,
1923 ... dtype=int) # offset = 1*itemsize, i.e. skip first element
1924 array([2, 3])
1926 """)
1929##############################################################################
1930#
1931# ndarray attributes
1932#
1933##############################################################################
1936add_newdoc('numpy.core.multiarray', 'ndarray', ('__array_interface__',
1937 """Array protocol: Python side."""))
1940add_newdoc('numpy.core.multiarray', 'ndarray', ('__array_finalize__',
1941 """None."""))
1944add_newdoc('numpy.core.multiarray', 'ndarray', ('__array_priority__',
1945 """Array priority."""))
1948add_newdoc('numpy.core.multiarray', 'ndarray', ('__array_struct__',
1949 """Array protocol: C-struct side."""))
1952add_newdoc('numpy.core.multiarray', 'ndarray', ('base',
1953 """
1954 Base object if memory is from some other object.
1956 Examples
1957 --------
1958 The base of an array that owns its memory is None:
1960 >>> x = np.array([1,2,3,4])
1961 >>> x.base is None
1962 True
1964 Slicing creates a view, whose memory is shared with x:
1966 >>> y = x[2:]
1967 >>> y.base is x
1968 True
1970 """))
1973add_newdoc('numpy.core.multiarray', 'ndarray', ('ctypes',
1974 """
1975 An object to simplify the interaction of the array with the ctypes
1976 module.
1978 This attribute creates an object that makes it easier to use arrays
1979 when calling shared libraries with the ctypes module. The returned
1980 object has, among others, data, shape, and strides attributes (see
1981 Notes below) which themselves return ctypes objects that can be used
1982 as arguments to a shared library.
1984 Parameters
1985 ----------
1986 None
1988 Returns
1989 -------
1990 c : Python object
1991 Possessing attributes data, shape, strides, etc.
1993 See Also
1994 --------
1995 numpy.ctypeslib
1997 Notes
1998 -----
1999 Below are the public attributes of this object which were documented
2000 in "Guide to NumPy" (we have omitted undocumented public attributes,
2001 as well as documented private attributes):
2003 .. autoattribute:: numpy.core._internal._ctypes.data
2004 :noindex:
2006 .. autoattribute:: numpy.core._internal._ctypes.shape
2007 :noindex:
2009 .. autoattribute:: numpy.core._internal._ctypes.strides
2010 :noindex:
2012 .. automethod:: numpy.core._internal._ctypes.data_as
2013 :noindex:
2015 .. automethod:: numpy.core._internal._ctypes.shape_as
2016 :noindex:
2018 .. automethod:: numpy.core._internal._ctypes.strides_as
2019 :noindex:
2021 If the ctypes module is not available, then the ctypes attribute
2022 of array objects still returns something useful, but ctypes objects
2023 are not returned and errors may be raised instead. In particular,
2024 the object will still have the ``as_parameter`` attribute which will
2025 return an integer equal to the data attribute.
2027 Examples
2028 --------
2029 >>> import ctypes
2030 >>> x = np.array([[0, 1], [2, 3]], dtype=np.int32)
2031 >>> x
2032 array([[0, 1],
2033 [2, 3]], dtype=int32)
2034 >>> x.ctypes.data
2035 31962608 # may vary
2036 >>> x.ctypes.data_as(ctypes.POINTER(ctypes.c_uint32))
2037 <__main__.LP_c_uint object at 0x7ff2fc1fc200> # may vary
2038 >>> x.ctypes.data_as(ctypes.POINTER(ctypes.c_uint32)).contents
2039 c_uint(0)
2040 >>> x.ctypes.data_as(ctypes.POINTER(ctypes.c_uint64)).contents
2041 c_ulong(4294967296)
2042 >>> x.ctypes.shape
2043 <numpy.core._internal.c_long_Array_2 object at 0x7ff2fc1fce60> # may vary
2044 >>> x.ctypes.strides
2045 <numpy.core._internal.c_long_Array_2 object at 0x7ff2fc1ff320> # may vary
2047 """))
2050add_newdoc('numpy.core.multiarray', 'ndarray', ('data',
2051 """Python buffer object pointing to the start of the array's data."""))
2054add_newdoc('numpy.core.multiarray', 'ndarray', ('dtype',
2055 """
2056 Data-type of the array's elements.
2058 Parameters
2059 ----------
2060 None
2062 Returns
2063 -------
2064 d : numpy dtype object
2066 See Also
2067 --------
2068 numpy.dtype
2070 Examples
2071 --------
2072 >>> x
2073 array([[0, 1],
2074 [2, 3]])
2075 >>> x.dtype
2076 dtype('int32')
2077 >>> type(x.dtype)
2078 <type 'numpy.dtype'>
2080 """))
2083add_newdoc('numpy.core.multiarray', 'ndarray', ('imag',
2084 """
2085 The imaginary part of the array.
2087 Examples
2088 --------
2089 >>> x = np.sqrt([1+0j, 0+1j])
2090 >>> x.imag
2091 array([ 0. , 0.70710678])
2092 >>> x.imag.dtype
2093 dtype('float64')
2095 """))
2098add_newdoc('numpy.core.multiarray', 'ndarray', ('itemsize',
2099 """
2100 Length of one array element in bytes.
2102 Examples
2103 --------
2104 >>> x = np.array([1,2,3], dtype=np.float64)
2105 >>> x.itemsize
2106 8
2107 >>> x = np.array([1,2,3], dtype=np.complex128)
2108 >>> x.itemsize
2109 16
2111 """))
2114add_newdoc('numpy.core.multiarray', 'ndarray', ('flags',
2115 """
2116 Information about the memory layout of the array.
2118 Attributes
2119 ----------
2120 C_CONTIGUOUS (C)
2121 The data is in a single, C-style contiguous segment.
2122 F_CONTIGUOUS (F)
2123 The data is in a single, Fortran-style contiguous segment.
2124 OWNDATA (O)
2125 The array owns the memory it uses or borrows it from another object.
2126 WRITEABLE (W)
2127 The data area can be written to. Setting this to False locks
2128 the data, making it read-only. A view (slice, etc.) inherits WRITEABLE
2129 from its base array at creation time, but a view of a writeable
2130 array may be subsequently locked while the base array remains writeable.
2131 (The opposite is not true, in that a view of a locked array may not
2132 be made writeable. However, currently, locking a base object does not
2133 lock any views that already reference it, so under that circumstance it
2134 is possible to alter the contents of a locked array via a previously
2135 created writeable view onto it.) Attempting to change a non-writeable
2136 array raises a RuntimeError exception.
2137 ALIGNED (A)
2138 The data and all elements are aligned appropriately for the hardware.
2139 WRITEBACKIFCOPY (X)
2140 This array is a copy of some other array. The C-API function
2141 PyArray_ResolveWritebackIfCopy must be called before deallocating
2142 to the base array will be updated with the contents of this array.
2143 UPDATEIFCOPY (U)
2144 (Deprecated, use WRITEBACKIFCOPY) This array is a copy of some other array.
2145 When this array is
2146 deallocated, the base array will be updated with the contents of
2147 this array.
2148 FNC
2149 F_CONTIGUOUS and not C_CONTIGUOUS.
2150 FORC
2151 F_CONTIGUOUS or C_CONTIGUOUS (one-segment test).
2152 BEHAVED (B)
2153 ALIGNED and WRITEABLE.
2154 CARRAY (CA)
2155 BEHAVED and C_CONTIGUOUS.
2156 FARRAY (FA)
2157 BEHAVED and F_CONTIGUOUS and not C_CONTIGUOUS.
2159 Notes
2160 -----
2161 The `flags` object can be accessed dictionary-like (as in ``a.flags['WRITEABLE']``),
2162 or by using lowercased attribute names (as in ``a.flags.writeable``). Short flag
2163 names are only supported in dictionary access.
2165 Only the WRITEBACKIFCOPY, UPDATEIFCOPY, WRITEABLE, and ALIGNED flags can be
2166 changed by the user, via direct assignment to the attribute or dictionary
2167 entry, or by calling `ndarray.setflags`.
2169 The array flags cannot be set arbitrarily:
2171 - UPDATEIFCOPY can only be set ``False``.
2172 - WRITEBACKIFCOPY can only be set ``False``.
2173 - ALIGNED can only be set ``True`` if the data is truly aligned.
2174 - WRITEABLE can only be set ``True`` if the array owns its own memory
2175 or the ultimate owner of the memory exposes a writeable buffer
2176 interface or is a string.
2178 Arrays can be both C-style and Fortran-style contiguous simultaneously.
2179 This is clear for 1-dimensional arrays, but can also be true for higher
2180 dimensional arrays.
2182 Even for contiguous arrays a stride for a given dimension
2183 ``arr.strides[dim]`` may be *arbitrary* if ``arr.shape[dim] == 1``
2184 or the array has no elements.
2185 It does *not* generally hold that ``self.strides[-1] == self.itemsize``
2186 for C-style contiguous arrays or ``self.strides[0] == self.itemsize`` for
2187 Fortran-style contiguous arrays is true.
2188 """))
2191add_newdoc('numpy.core.multiarray', 'ndarray', ('flat',
2192 """
2193 A 1-D iterator over the array.
2195 This is a `numpy.flatiter` instance, which acts similarly to, but is not
2196 a subclass of, Python's built-in iterator object.
2198 See Also
2199 --------
2200 flatten : Return a copy of the array collapsed into one dimension.
2202 flatiter
2204 Examples
2205 --------
2206 >>> x = np.arange(1, 7).reshape(2, 3)
2207 >>> x
2208 array([[1, 2, 3],
2209 [4, 5, 6]])
2210 >>> x.flat[3]
2211 4
2212 >>> x.T
2213 array([[1, 4],
2214 [2, 5],
2215 [3, 6]])
2216 >>> x.T.flat[3]
2217 5
2218 >>> type(x.flat)
2219 <class 'numpy.flatiter'>
2221 An assignment example:
2223 >>> x.flat = 3; x
2224 array([[3, 3, 3],
2225 [3, 3, 3]])
2226 >>> x.flat[[1,4]] = 1; x
2227 array([[3, 1, 3],
2228 [3, 1, 3]])
2230 """))
2233add_newdoc('numpy.core.multiarray', 'ndarray', ('nbytes',
2234 """
2235 Total bytes consumed by the elements of the array.
2237 Notes
2238 -----
2239 Does not include memory consumed by non-element attributes of the
2240 array object.
2242 Examples
2243 --------
2244 >>> x = np.zeros((3,5,2), dtype=np.complex128)
2245 >>> x.nbytes
2246 480
2247 >>> np.prod(x.shape) * x.itemsize
2248 480
2250 """))
2253add_newdoc('numpy.core.multiarray', 'ndarray', ('ndim',
2254 """
2255 Number of array dimensions.
2257 Examples
2258 --------
2259 >>> x = np.array([1, 2, 3])
2260 >>> x.ndim
2261 1
2262 >>> y = np.zeros((2, 3, 4))
2263 >>> y.ndim
2264 3
2266 """))
2269add_newdoc('numpy.core.multiarray', 'ndarray', ('real',
2270 """
2271 The real part of the array.
2273 Examples
2274 --------
2275 >>> x = np.sqrt([1+0j, 0+1j])
2276 >>> x.real
2277 array([ 1. , 0.70710678])
2278 >>> x.real.dtype
2279 dtype('float64')
2281 See Also
2282 --------
2283 numpy.real : equivalent function
2285 """))
2288add_newdoc('numpy.core.multiarray', 'ndarray', ('shape',
2289 """
2290 Tuple of array dimensions.
2292 The shape property is usually used to get the current shape of an array,
2293 but may also be used to reshape the array in-place by assigning a tuple of
2294 array dimensions to it. As with `numpy.reshape`, one of the new shape
2295 dimensions can be -1, in which case its value is inferred from the size of
2296 the array and the remaining dimensions. Reshaping an array in-place will
2297 fail if a copy is required.
2299 Examples
2300 --------
2301 >>> x = np.array([1, 2, 3, 4])
2302 >>> x.shape
2303 (4,)
2304 >>> y = np.zeros((2, 3, 4))
2305 >>> y.shape
2306 (2, 3, 4)
2307 >>> y.shape = (3, 8)
2308 >>> y
2309 array([[ 0., 0., 0., 0., 0., 0., 0., 0.],
2310 [ 0., 0., 0., 0., 0., 0., 0., 0.],
2311 [ 0., 0., 0., 0., 0., 0., 0., 0.]])
2312 >>> y.shape = (3, 6)
2313 Traceback (most recent call last):
2314 File "<stdin>", line 1, in <module>
2315 ValueError: total size of new array must be unchanged
2316 >>> np.zeros((4,2))[::2].shape = (-1,)
2317 Traceback (most recent call last):
2318 File "<stdin>", line 1, in <module>
2319 AttributeError: Incompatible shape for in-place modification. Use
2320 `.reshape()` to make a copy with the desired shape.
2322 See Also
2323 --------
2324 numpy.reshape : similar function
2325 ndarray.reshape : similar method
2327 """))
2330add_newdoc('numpy.core.multiarray', 'ndarray', ('size',
2331 """
2332 Number of elements in the array.
2334 Equal to ``np.prod(a.shape)``, i.e., the product of the array's
2335 dimensions.
2337 Notes
2338 -----
2339 `a.size` returns a standard arbitrary precision Python integer. This
2340 may not be the case with other methods of obtaining the same value
2341 (like the suggested ``np.prod(a.shape)``, which returns an instance
2342 of ``np.int_``), and may be relevant if the value is used further in
2343 calculations that may overflow a fixed size integer type.
2345 Examples
2346 --------
2347 >>> x = np.zeros((3, 5, 2), dtype=np.complex128)
2348 >>> x.size
2349 30
2350 >>> np.prod(x.shape)
2351 30
2353 """))
2356add_newdoc('numpy.core.multiarray', 'ndarray', ('strides',
2357 """
2358 Tuple of bytes to step in each dimension when traversing an array.
2360 The byte offset of element ``(i[0], i[1], ..., i[n])`` in an array `a`
2361 is::
2363 offset = sum(np.array(i) * a.strides)
2365 A more detailed explanation of strides can be found in the
2366 "ndarray.rst" file in the NumPy reference guide.
2368 Notes
2369 -----
2370 Imagine an array of 32-bit integers (each 4 bytes)::
2372 x = np.array([[0, 1, 2, 3, 4],
2373 [5, 6, 7, 8, 9]], dtype=np.int32)
2375 This array is stored in memory as 40 bytes, one after the other
2376 (known as a contiguous block of memory). The strides of an array tell
2377 us how many bytes we have to skip in memory to move to the next position
2378 along a certain axis. For example, we have to skip 4 bytes (1 value) to
2379 move to the next column, but 20 bytes (5 values) to get to the same
2380 position in the next row. As such, the strides for the array `x` will be
2381 ``(20, 4)``.
2383 See Also
2384 --------
2385 numpy.lib.stride_tricks.as_strided
2387 Examples
2388 --------
2389 >>> y = np.reshape(np.arange(2*3*4), (2,3,4))
2390 >>> y
2391 array([[[ 0, 1, 2, 3],
2392 [ 4, 5, 6, 7],
2393 [ 8, 9, 10, 11]],
2394 [[12, 13, 14, 15],
2395 [16, 17, 18, 19],
2396 [20, 21, 22, 23]]])
2397 >>> y.strides
2398 (48, 16, 4)
2399 >>> y[1,1,1]
2400 17
2401 >>> offset=sum(y.strides * np.array((1,1,1)))
2402 >>> offset/y.itemsize
2403 17
2405 >>> x = np.reshape(np.arange(5*6*7*8), (5,6,7,8)).transpose(2,3,1,0)
2406 >>> x.strides
2407 (32, 4, 224, 1344)
2408 >>> i = np.array([3,5,2,2])
2409 >>> offset = sum(i * x.strides)
2410 >>> x[3,5,2,2]
2411 813
2412 >>> offset / x.itemsize
2413 813
2415 """))
2418add_newdoc('numpy.core.multiarray', 'ndarray', ('T',
2419 """
2420 The transposed array.
2422 Same as ``self.transpose()``.
2424 Examples
2425 --------
2426 >>> x = np.array([[1.,2.],[3.,4.]])
2427 >>> x
2428 array([[ 1., 2.],
2429 [ 3., 4.]])
2430 >>> x.T
2431 array([[ 1., 3.],
2432 [ 2., 4.]])
2433 >>> x = np.array([1.,2.,3.,4.])
2434 >>> x
2435 array([ 1., 2., 3., 4.])
2436 >>> x.T
2437 array([ 1., 2., 3., 4.])
2439 See Also
2440 --------
2441 transpose
2443 """))
2446##############################################################################
2447#
2448# ndarray methods
2449#
2450##############################################################################
2453add_newdoc('numpy.core.multiarray', 'ndarray', ('__array__',
2454 """ a.__array__([dtype], /) -> reference if type unchanged, copy otherwise.
2456 Returns either a new reference to self if dtype is not given or a new array
2457 of provided data type if dtype is different from the current dtype of the
2458 array.
2460 """))
2463add_newdoc('numpy.core.multiarray', 'ndarray', ('__array_prepare__',
2464 """a.__array_prepare__(obj) -> Object of same type as ndarray object obj.
2466 """))
2469add_newdoc('numpy.core.multiarray', 'ndarray', ('__array_wrap__',
2470 """a.__array_wrap__(obj) -> Object of same type as ndarray object a.
2472 """))
2475add_newdoc('numpy.core.multiarray', 'ndarray', ('__copy__',
2476 """a.__copy__()
2478 Used if :func:`copy.copy` is called on an array. Returns a copy of the array.
2480 Equivalent to ``a.copy(order='K')``.
2482 """))
2485add_newdoc('numpy.core.multiarray', 'ndarray', ('__deepcopy__',
2486 """a.__deepcopy__(memo, /) -> Deep copy of array.
2488 Used if :func:`copy.deepcopy` is called on an array.
2490 """))
2493add_newdoc('numpy.core.multiarray', 'ndarray', ('__reduce__',
2494 """a.__reduce__()
2496 For pickling.
2498 """))
2501add_newdoc('numpy.core.multiarray', 'ndarray', ('__setstate__',
2502 """a.__setstate__(state, /)
2504 For unpickling.
2506 The `state` argument must be a sequence that contains the following
2507 elements:
2509 Parameters
2510 ----------
2511 version : int
2512 optional pickle version. If omitted defaults to 0.
2513 shape : tuple
2514 dtype : data-type
2515 isFortran : bool
2516 rawdata : string or list
2517 a binary string with the data (or a list if 'a' is an object array)
2519 """))
2522add_newdoc('numpy.core.multiarray', 'ndarray', ('all',
2523 """
2524 a.all(axis=None, out=None, keepdims=False)
2526 Returns True if all elements evaluate to True.
2528 Refer to `numpy.all` for full documentation.
2530 See Also
2531 --------
2532 numpy.all : equivalent function
2534 """))
2537add_newdoc('numpy.core.multiarray', 'ndarray', ('any',
2538 """
2539 a.any(axis=None, out=None, keepdims=False)
2541 Returns True if any of the elements of `a` evaluate to True.
2543 Refer to `numpy.any` for full documentation.
2545 See Also
2546 --------
2547 numpy.any : equivalent function
2549 """))
2552add_newdoc('numpy.core.multiarray', 'ndarray', ('argmax',
2553 """
2554 a.argmax(axis=None, out=None)
2556 Return indices of the maximum values along the given axis.
2558 Refer to `numpy.argmax` for full documentation.
2560 See Also
2561 --------
2562 numpy.argmax : equivalent function
2564 """))
2567add_newdoc('numpy.core.multiarray', 'ndarray', ('argmin',
2568 """
2569 a.argmin(axis=None, out=None)
2571 Return indices of the minimum values along the given axis of `a`.
2573 Refer to `numpy.argmin` for detailed documentation.
2575 See Also
2576 --------
2577 numpy.argmin : equivalent function
2579 """))
2582add_newdoc('numpy.core.multiarray', 'ndarray', ('argsort',
2583 """
2584 a.argsort(axis=-1, kind=None, order=None)
2586 Returns the indices that would sort this array.
2588 Refer to `numpy.argsort` for full documentation.
2590 See Also
2591 --------
2592 numpy.argsort : equivalent function
2594 """))
2597add_newdoc('numpy.core.multiarray', 'ndarray', ('argpartition',
2598 """
2599 a.argpartition(kth, axis=-1, kind='introselect', order=None)
2601 Returns the indices that would partition this array.
2603 Refer to `numpy.argpartition` for full documentation.
2605 .. versionadded:: 1.8.0
2607 See Also
2608 --------
2609 numpy.argpartition : equivalent function
2611 """))
2614add_newdoc('numpy.core.multiarray', 'ndarray', ('astype',
2615 """
2616 a.astype(dtype, order='K', casting='unsafe', subok=True, copy=True)
2618 Copy of the array, cast to a specified type.
2620 Parameters
2621 ----------
2622 dtype : str or dtype
2623 Typecode or data-type to which the array is cast.
2624 order : {'C', 'F', 'A', 'K'}, optional
2625 Controls the memory layout order of the result.
2626 'C' means C order, 'F' means Fortran order, 'A'
2627 means 'F' order if all the arrays are Fortran contiguous,
2628 'C' order otherwise, and 'K' means as close to the
2629 order the array elements appear in memory as possible.
2630 Default is 'K'.
2631 casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional
2632 Controls what kind of data casting may occur. Defaults to 'unsafe'
2633 for backwards compatibility.
2635 * 'no' means the data types should not be cast at all.
2636 * 'equiv' means only byte-order changes are allowed.
2637 * 'safe' means only casts which can preserve values are allowed.
2638 * 'same_kind' means only safe casts or casts within a kind,
2639 like float64 to float32, are allowed.
2640 * 'unsafe' means any data conversions may be done.
2641 subok : bool, optional
2642 If True, then sub-classes will be passed-through (default), otherwise
2643 the returned array will be forced to be a base-class array.
2644 copy : bool, optional
2645 By default, astype always returns a newly allocated array. If this
2646 is set to false, and the `dtype`, `order`, and `subok`
2647 requirements are satisfied, the input array is returned instead
2648 of a copy.
2650 Returns
2651 -------
2652 arr_t : ndarray
2653 Unless `copy` is False and the other conditions for returning the input
2654 array are satisfied (see description for `copy` input parameter), `arr_t`
2655 is a new array of the same shape as the input array, with dtype, order
2656 given by `dtype`, `order`.
2658 Notes
2659 -----
2660 .. versionchanged:: 1.17.0
2661 Casting between a simple data type and a structured one is possible only
2662 for "unsafe" casting. Casting to multiple fields is allowed, but
2663 casting from multiple fields is not.
2665 .. versionchanged:: 1.9.0
2666 Casting from numeric to string types in 'safe' casting mode requires
2667 that the string dtype length is long enough to store the max
2668 integer/float value converted.
2670 Raises
2671 ------
2672 ComplexWarning
2673 When casting from complex to float or int. To avoid this,
2674 one should use ``a.real.astype(t)``.
2676 Examples
2677 --------
2678 >>> x = np.array([1, 2, 2.5])
2679 >>> x
2680 array([1. , 2. , 2.5])
2682 >>> x.astype(int)
2683 array([1, 2, 2])
2685 """))
2688add_newdoc('numpy.core.multiarray', 'ndarray', ('byteswap',
2689 """
2690 a.byteswap(inplace=False)
2692 Swap the bytes of the array elements
2694 Toggle between low-endian and big-endian data representation by
2695 returning a byteswapped array, optionally swapped in-place.
2696 Arrays of byte-strings are not swapped. The real and imaginary
2697 parts of a complex number are swapped individually.
2699 Parameters
2700 ----------
2701 inplace : bool, optional
2702 If ``True``, swap bytes in-place, default is ``False``.
2704 Returns
2705 -------
2706 out : ndarray
2707 The byteswapped array. If `inplace` is ``True``, this is
2708 a view to self.
2710 Examples
2711 --------
2712 >>> A = np.array([1, 256, 8755], dtype=np.int16)
2713 >>> list(map(hex, A))
2714 ['0x1', '0x100', '0x2233']
2715 >>> A.byteswap(inplace=True)
2716 array([ 256, 1, 13090], dtype=int16)
2717 >>> list(map(hex, A))
2718 ['0x100', '0x1', '0x3322']
2720 Arrays of byte-strings are not swapped
2722 >>> A = np.array([b'ceg', b'fac'])
2723 >>> A.byteswap()
2724 array([b'ceg', b'fac'], dtype='|S3')
2726 ``A.newbyteorder().byteswap()`` produces an array with the same values
2727 but different representation in memory
2729 >>> A = np.array([1, 2, 3])
2730 >>> A.view(np.uint8)
2731 array([1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0,
2732 0, 0], dtype=uint8)
2733 >>> A.newbyteorder().byteswap(inplace=True)
2734 array([1, 2, 3])
2735 >>> A.view(np.uint8)
2736 array([0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0,
2737 0, 3], dtype=uint8)
2739 """))
2742add_newdoc('numpy.core.multiarray', 'ndarray', ('choose',
2743 """
2744 a.choose(choices, out=None, mode='raise')
2746 Use an index array to construct a new array from a set of choices.
2748 Refer to `numpy.choose` for full documentation.
2750 See Also
2751 --------
2752 numpy.choose : equivalent function
2754 """))
2757add_newdoc('numpy.core.multiarray', 'ndarray', ('clip',
2758 """
2759 a.clip(min=None, max=None, out=None, **kwargs)
2761 Return an array whose values are limited to ``[min, max]``.
2762 One of max or min must be given.
2764 Refer to `numpy.clip` for full documentation.
2766 See Also
2767 --------
2768 numpy.clip : equivalent function
2770 """))
2773add_newdoc('numpy.core.multiarray', 'ndarray', ('compress',
2774 """
2775 a.compress(condition, axis=None, out=None)
2777 Return selected slices of this array along given axis.
2779 Refer to `numpy.compress` for full documentation.
2781 See Also
2782 --------
2783 numpy.compress : equivalent function
2785 """))
2788add_newdoc('numpy.core.multiarray', 'ndarray', ('conj',
2789 """
2790 a.conj()
2792 Complex-conjugate all elements.
2794 Refer to `numpy.conjugate` for full documentation.
2796 See Also
2797 --------
2798 numpy.conjugate : equivalent function
2800 """))
2803add_newdoc('numpy.core.multiarray', 'ndarray', ('conjugate',
2804 """
2805 a.conjugate()
2807 Return the complex conjugate, element-wise.
2809 Refer to `numpy.conjugate` for full documentation.
2811 See Also
2812 --------
2813 numpy.conjugate : equivalent function
2815 """))
2818add_newdoc('numpy.core.multiarray', 'ndarray', ('copy',
2819 """
2820 a.copy(order='C')
2822 Return a copy of the array.
2824 Parameters
2825 ----------
2826 order : {'C', 'F', 'A', 'K'}, optional
2827 Controls the memory layout of the copy. 'C' means C-order,
2828 'F' means F-order, 'A' means 'F' if `a` is Fortran contiguous,
2829 'C' otherwise. 'K' means match the layout of `a` as closely
2830 as possible. (Note that this function and :func:`numpy.copy` are very
2831 similar, but have different default values for their order=
2832 arguments.)
2834 See also
2835 --------
2836 numpy.copy
2837 numpy.copyto
2839 Examples
2840 --------
2841 >>> x = np.array([[1,2,3],[4,5,6]], order='F')
2843 >>> y = x.copy()
2845 >>> x.fill(0)
2847 >>> x
2848 array([[0, 0, 0],
2849 [0, 0, 0]])
2851 >>> y
2852 array([[1, 2, 3],
2853 [4, 5, 6]])
2855 >>> y.flags['C_CONTIGUOUS']
2856 True
2858 """))
2861add_newdoc('numpy.core.multiarray', 'ndarray', ('cumprod',
2862 """
2863 a.cumprod(axis=None, dtype=None, out=None)
2865 Return the cumulative product of the elements along the given axis.
2867 Refer to `numpy.cumprod` for full documentation.
2869 See Also
2870 --------
2871 numpy.cumprod : equivalent function
2873 """))
2876add_newdoc('numpy.core.multiarray', 'ndarray', ('cumsum',
2877 """
2878 a.cumsum(axis=None, dtype=None, out=None)
2880 Return the cumulative sum of the elements along the given axis.
2882 Refer to `numpy.cumsum` for full documentation.
2884 See Also
2885 --------
2886 numpy.cumsum : equivalent function
2888 """))
2891add_newdoc('numpy.core.multiarray', 'ndarray', ('diagonal',
2892 """
2893 a.diagonal(offset=0, axis1=0, axis2=1)
2895 Return specified diagonals. In NumPy 1.9 the returned array is a
2896 read-only view instead of a copy as in previous NumPy versions. In
2897 a future version the read-only restriction will be removed.
2899 Refer to :func:`numpy.diagonal` for full documentation.
2901 See Also
2902 --------
2903 numpy.diagonal : equivalent function
2905 """))
2908add_newdoc('numpy.core.multiarray', 'ndarray', ('dot',
2909 """
2910 a.dot(b, out=None)
2912 Dot product of two arrays.
2914 Refer to `numpy.dot` for full documentation.
2916 See Also
2917 --------
2918 numpy.dot : equivalent function
2920 Examples
2921 --------
2922 >>> a = np.eye(2)
2923 >>> b = np.ones((2, 2)) * 2
2924 >>> a.dot(b)
2925 array([[2., 2.],
2926 [2., 2.]])
2928 This array method can be conveniently chained:
2930 >>> a.dot(b).dot(b)
2931 array([[8., 8.],
2932 [8., 8.]])
2934 """))
2937add_newdoc('numpy.core.multiarray', 'ndarray', ('dump',
2938 """a.dump(file)
2940 Dump a pickle of the array to the specified file.
2941 The array can be read back with pickle.load or numpy.load.
2943 Parameters
2944 ----------
2945 file : str or Path
2946 A string naming the dump file.
2948 .. versionchanged:: 1.17.0
2949 `pathlib.Path` objects are now accepted.
2951 """))
2954add_newdoc('numpy.core.multiarray', 'ndarray', ('dumps',
2955 """
2956 a.dumps()
2958 Returns the pickle of the array as a string.
2959 pickle.loads or numpy.loads will convert the string back to an array.
2961 Parameters
2962 ----------
2963 None
2965 """))
2968add_newdoc('numpy.core.multiarray', 'ndarray', ('fill',
2969 """
2970 a.fill(value)
2972 Fill the array with a scalar value.
2974 Parameters
2975 ----------
2976 value : scalar
2977 All elements of `a` will be assigned this value.
2979 Examples
2980 --------
2981 >>> a = np.array([1, 2])
2982 >>> a.fill(0)
2983 >>> a
2984 array([0, 0])
2985 >>> a = np.empty(2)
2986 >>> a.fill(1)
2987 >>> a
2988 array([1., 1.])
2990 """))
2993add_newdoc('numpy.core.multiarray', 'ndarray', ('flatten',
2994 """
2995 a.flatten(order='C')
2997 Return a copy of the array collapsed into one dimension.
2999 Parameters
3000 ----------
3001 order : {'C', 'F', 'A', 'K'}, optional
3002 'C' means to flatten in row-major (C-style) order.
3003 'F' means to flatten in column-major (Fortran-
3004 style) order. 'A' means to flatten in column-major
3005 order if `a` is Fortran *contiguous* in memory,
3006 row-major order otherwise. 'K' means to flatten
3007 `a` in the order the elements occur in memory.
3008 The default is 'C'.
3010 Returns
3011 -------
3012 y : ndarray
3013 A copy of the input array, flattened to one dimension.
3015 See Also
3016 --------
3017 ravel : Return a flattened array.
3018 flat : A 1-D flat iterator over the array.
3020 Examples
3021 --------
3022 >>> a = np.array([[1,2], [3,4]])
3023 >>> a.flatten()
3024 array([1, 2, 3, 4])
3025 >>> a.flatten('F')
3026 array([1, 3, 2, 4])
3028 """))
3031add_newdoc('numpy.core.multiarray', 'ndarray', ('getfield',
3032 """
3033 a.getfield(dtype, offset=0)
3035 Returns a field of the given array as a certain type.
3037 A field is a view of the array data with a given data-type. The values in
3038 the view are determined by the given type and the offset into the current
3039 array in bytes. The offset needs to be such that the view dtype fits in the
3040 array dtype; for example an array of dtype complex128 has 16-byte elements.
3041 If taking a view with a 32-bit integer (4 bytes), the offset needs to be
3042 between 0 and 12 bytes.
3044 Parameters
3045 ----------
3046 dtype : str or dtype
3047 The data type of the view. The dtype size of the view can not be larger
3048 than that of the array itself.
3049 offset : int
3050 Number of bytes to skip before beginning the element view.
3052 Examples
3053 --------
3054 >>> x = np.diag([1.+1.j]*2)
3055 >>> x[1, 1] = 2 + 4.j
3056 >>> x
3057 array([[1.+1.j, 0.+0.j],
3058 [0.+0.j, 2.+4.j]])
3059 >>> x.getfield(np.float64)
3060 array([[1., 0.],
3061 [0., 2.]])
3063 By choosing an offset of 8 bytes we can select the complex part of the
3064 array for our view:
3066 >>> x.getfield(np.float64, offset=8)
3067 array([[1., 0.],
3068 [0., 4.]])
3070 """))
3073add_newdoc('numpy.core.multiarray', 'ndarray', ('item',
3074 """
3075 a.item(*args)
3077 Copy an element of an array to a standard Python scalar and return it.
3079 Parameters
3080 ----------
3081 \\*args : Arguments (variable number and type)
3083 * none: in this case, the method only works for arrays
3084 with one element (`a.size == 1`), which element is
3085 copied into a standard Python scalar object and returned.
3087 * int_type: this argument is interpreted as a flat index into
3088 the array, specifying which element to copy and return.
3090 * tuple of int_types: functions as does a single int_type argument,
3091 except that the argument is interpreted as an nd-index into the
3092 array.
3094 Returns
3095 -------
3096 z : Standard Python scalar object
3097 A copy of the specified element of the array as a suitable
3098 Python scalar
3100 Notes
3101 -----
3102 When the data type of `a` is longdouble or clongdouble, item() returns
3103 a scalar array object because there is no available Python scalar that
3104 would not lose information. Void arrays return a buffer object for item(),
3105 unless fields are defined, in which case a tuple is returned.
3107 `item` is very similar to a[args], except, instead of an array scalar,
3108 a standard Python scalar is returned. This can be useful for speeding up
3109 access to elements of the array and doing arithmetic on elements of the
3110 array using Python's optimized math.
3112 Examples
3113 --------
3114 >>> np.random.seed(123)
3115 >>> x = np.random.randint(9, size=(3, 3))
3116 >>> x
3117 array([[2, 2, 6],
3118 [1, 3, 6],
3119 [1, 0, 1]])
3120 >>> x.item(3)
3121 1
3122 >>> x.item(7)
3123 0
3124 >>> x.item((0, 1))
3125 2
3126 >>> x.item((2, 2))
3127 1
3129 """))
3132add_newdoc('numpy.core.multiarray', 'ndarray', ('itemset',
3133 """
3134 a.itemset(*args)
3136 Insert scalar into an array (scalar is cast to array's dtype, if possible)
3138 There must be at least 1 argument, and define the last argument
3139 as *item*. Then, ``a.itemset(*args)`` is equivalent to but faster
3140 than ``a[args] = item``. The item should be a scalar value and `args`
3141 must select a single item in the array `a`.
3143 Parameters
3144 ----------
3145 \\*args : Arguments
3146 If one argument: a scalar, only used in case `a` is of size 1.
3147 If two arguments: the last argument is the value to be set
3148 and must be a scalar, the first argument specifies a single array
3149 element location. It is either an int or a tuple.
3151 Notes
3152 -----
3153 Compared to indexing syntax, `itemset` provides some speed increase
3154 for placing a scalar into a particular location in an `ndarray`,
3155 if you must do this. However, generally this is discouraged:
3156 among other problems, it complicates the appearance of the code.
3157 Also, when using `itemset` (and `item`) inside a loop, be sure
3158 to assign the methods to a local variable to avoid the attribute
3159 look-up at each loop iteration.
3161 Examples
3162 --------
3163 >>> np.random.seed(123)
3164 >>> x = np.random.randint(9, size=(3, 3))
3165 >>> x
3166 array([[2, 2, 6],
3167 [1, 3, 6],
3168 [1, 0, 1]])
3169 >>> x.itemset(4, 0)
3170 >>> x.itemset((2, 2), 9)
3171 >>> x
3172 array([[2, 2, 6],
3173 [1, 0, 6],
3174 [1, 0, 9]])
3176 """))
3179add_newdoc('numpy.core.multiarray', 'ndarray', ('max',
3180 """
3181 a.max(axis=None, out=None, keepdims=False, initial=<no value>, where=True)
3183 Return the maximum along a given axis.
3185 Refer to `numpy.amax` for full documentation.
3187 See Also
3188 --------
3189 numpy.amax : equivalent function
3191 """))
3194add_newdoc('numpy.core.multiarray', 'ndarray', ('mean',
3195 """
3196 a.mean(axis=None, dtype=None, out=None, keepdims=False)
3198 Returns the average of the array elements along given axis.
3200 Refer to `numpy.mean` for full documentation.
3202 See Also
3203 --------
3204 numpy.mean : equivalent function
3206 """))
3209add_newdoc('numpy.core.multiarray', 'ndarray', ('min',
3210 """
3211 a.min(axis=None, out=None, keepdims=False, initial=<no value>, where=True)
3213 Return the minimum along a given axis.
3215 Refer to `numpy.amin` for full documentation.
3217 See Also
3218 --------
3219 numpy.amin : equivalent function
3221 """))
3224add_newdoc('numpy.core.multiarray', 'ndarray', ('newbyteorder',
3225 """
3226 arr.newbyteorder(new_order='S')
3228 Return the array with the same data viewed with a different byte order.
3230 Equivalent to::
3232 arr.view(arr.dtype.newbytorder(new_order))
3234 Changes are also made in all fields and sub-arrays of the array data
3235 type.
3239 Parameters
3240 ----------
3241 new_order : string, optional
3242 Byte order to force; a value from the byte order specifications
3243 below. `new_order` codes can be any of:
3245 * 'S' - swap dtype from current to opposite endian
3246 * {'<', 'L'} - little endian
3247 * {'>', 'B'} - big endian
3248 * {'=', 'N'} - native order
3249 * {'|', 'I'} - ignore (no change to byte order)
3251 The default value ('S') results in swapping the current
3252 byte order. The code does a case-insensitive check on the first
3253 letter of `new_order` for the alternatives above. For example,
3254 any of 'B' or 'b' or 'biggish' are valid to specify big-endian.
3257 Returns
3258 -------
3259 new_arr : array
3260 New array object with the dtype reflecting given change to the
3261 byte order.
3263 """))
3266add_newdoc('numpy.core.multiarray', 'ndarray', ('nonzero',
3267 """
3268 a.nonzero()
3270 Return the indices of the elements that are non-zero.
3272 Refer to `numpy.nonzero` for full documentation.
3274 See Also
3275 --------
3276 numpy.nonzero : equivalent function
3278 """))
3281add_newdoc('numpy.core.multiarray', 'ndarray', ('prod',
3282 """
3283 a.prod(axis=None, dtype=None, out=None, keepdims=False, initial=1, where=True)
3285 Return the product of the array elements over the given axis
3287 Refer to `numpy.prod` for full documentation.
3289 See Also
3290 --------
3291 numpy.prod : equivalent function
3293 """))
3296add_newdoc('numpy.core.multiarray', 'ndarray', ('ptp',
3297 """
3298 a.ptp(axis=None, out=None, keepdims=False)
3300 Peak to peak (maximum - minimum) value along a given axis.
3302 Refer to `numpy.ptp` for full documentation.
3304 See Also
3305 --------
3306 numpy.ptp : equivalent function
3308 """))
3311add_newdoc('numpy.core.multiarray', 'ndarray', ('put',
3312 """
3313 a.put(indices, values, mode='raise')
3315 Set ``a.flat[n] = values[n]`` for all `n` in indices.
3317 Refer to `numpy.put` for full documentation.
3319 See Also
3320 --------
3321 numpy.put : equivalent function
3323 """))
3326add_newdoc('numpy.core.multiarray', 'ndarray', ('ravel',
3327 """
3328 a.ravel([order])
3330 Return a flattened array.
3332 Refer to `numpy.ravel` for full documentation.
3334 See Also
3335 --------
3336 numpy.ravel : equivalent function
3338 ndarray.flat : a flat iterator on the array.
3340 """))
3343add_newdoc('numpy.core.multiarray', 'ndarray', ('repeat',
3344 """
3345 a.repeat(repeats, axis=None)
3347 Repeat elements of an array.
3349 Refer to `numpy.repeat` for full documentation.
3351 See Also
3352 --------
3353 numpy.repeat : equivalent function
3355 """))
3358add_newdoc('numpy.core.multiarray', 'ndarray', ('reshape',
3359 """
3360 a.reshape(shape, order='C')
3362 Returns an array containing the same data with a new shape.
3364 Refer to `numpy.reshape` for full documentation.
3366 See Also
3367 --------
3368 numpy.reshape : equivalent function
3370 Notes
3371 -----
3372 Unlike the free function `numpy.reshape`, this method on `ndarray` allows
3373 the elements of the shape parameter to be passed in as separate arguments.
3374 For example, ``a.reshape(10, 11)`` is equivalent to
3375 ``a.reshape((10, 11))``.
3377 """))
3380add_newdoc('numpy.core.multiarray', 'ndarray', ('resize',
3381 """
3382 a.resize(new_shape, refcheck=True)
3384 Change shape and size of array in-place.
3386 Parameters
3387 ----------
3388 new_shape : tuple of ints, or `n` ints
3389 Shape of resized array.
3390 refcheck : bool, optional
3391 If False, reference count will not be checked. Default is True.
3393 Returns
3394 -------
3395 None
3397 Raises
3398 ------
3399 ValueError
3400 If `a` does not own its own data or references or views to it exist,
3401 and the data memory must be changed.
3402 PyPy only: will always raise if the data memory must be changed, since
3403 there is no reliable way to determine if references or views to it
3404 exist.
3406 SystemError
3407 If the `order` keyword argument is specified. This behaviour is a
3408 bug in NumPy.
3410 See Also
3411 --------
3412 resize : Return a new array with the specified shape.
3414 Notes
3415 -----
3416 This reallocates space for the data area if necessary.
3418 Only contiguous arrays (data elements consecutive in memory) can be
3419 resized.
3421 The purpose of the reference count check is to make sure you
3422 do not use this array as a buffer for another Python object and then
3423 reallocate the memory. However, reference counts can increase in
3424 other ways so if you are sure that you have not shared the memory
3425 for this array with another Python object, then you may safely set
3426 `refcheck` to False.
3428 Examples
3429 --------
3430 Shrinking an array: array is flattened (in the order that the data are
3431 stored in memory), resized, and reshaped:
3433 >>> a = np.array([[0, 1], [2, 3]], order='C')
3434 >>> a.resize((2, 1))
3435 >>> a
3436 array([[0],
3437 [1]])
3439 >>> a = np.array([[0, 1], [2, 3]], order='F')
3440 >>> a.resize((2, 1))
3441 >>> a
3442 array([[0],
3443 [2]])
3445 Enlarging an array: as above, but missing entries are filled with zeros:
3447 >>> b = np.array([[0, 1], [2, 3]])
3448 >>> b.resize(2, 3) # new_shape parameter doesn't have to be a tuple
3449 >>> b
3450 array([[0, 1, 2],
3451 [3, 0, 0]])
3453 Referencing an array prevents resizing...
3455 >>> c = a
3456 >>> a.resize((1, 1))
3457 Traceback (most recent call last):
3458 ...
3459 ValueError: cannot resize an array that references or is referenced ...
3461 Unless `refcheck` is False:
3463 >>> a.resize((1, 1), refcheck=False)
3464 >>> a
3465 array([[0]])
3466 >>> c
3467 array([[0]])
3469 """))
3472add_newdoc('numpy.core.multiarray', 'ndarray', ('round',
3473 """
3474 a.round(decimals=0, out=None)
3476 Return `a` with each element rounded to the given number of decimals.
3478 Refer to `numpy.around` for full documentation.
3480 See Also
3481 --------
3482 numpy.around : equivalent function
3484 """))
3487add_newdoc('numpy.core.multiarray', 'ndarray', ('searchsorted',
3488 """
3489 a.searchsorted(v, side='left', sorter=None)
3491 Find indices where elements of v should be inserted in a to maintain order.
3493 For full documentation, see `numpy.searchsorted`
3495 See Also
3496 --------
3497 numpy.searchsorted : equivalent function
3499 """))
3502add_newdoc('numpy.core.multiarray', 'ndarray', ('setfield',
3503 """
3504 a.setfield(val, dtype, offset=0)
3506 Put a value into a specified place in a field defined by a data-type.
3508 Place `val` into `a`'s field defined by `dtype` and beginning `offset`
3509 bytes into the field.
3511 Parameters
3512 ----------
3513 val : object
3514 Value to be placed in field.
3515 dtype : dtype object
3516 Data-type of the field in which to place `val`.
3517 offset : int, optional
3518 The number of bytes into the field at which to place `val`.
3520 Returns
3521 -------
3522 None
3524 See Also
3525 --------
3526 getfield
3528 Examples
3529 --------
3530 >>> x = np.eye(3)
3531 >>> x.getfield(np.float64)
3532 array([[1., 0., 0.],
3533 [0., 1., 0.],
3534 [0., 0., 1.]])
3535 >>> x.setfield(3, np.int32)
3536 >>> x.getfield(np.int32)
3537 array([[3, 3, 3],
3538 [3, 3, 3],
3539 [3, 3, 3]], dtype=int32)
3540 >>> x
3541 array([[1.0e+000, 1.5e-323, 1.5e-323],
3542 [1.5e-323, 1.0e+000, 1.5e-323],
3543 [1.5e-323, 1.5e-323, 1.0e+000]])
3544 >>> x.setfield(np.eye(3), np.int32)
3545 >>> x
3546 array([[1., 0., 0.],
3547 [0., 1., 0.],
3548 [0., 0., 1.]])
3550 """))
3553add_newdoc('numpy.core.multiarray', 'ndarray', ('setflags',
3554 """
3555 a.setflags(write=None, align=None, uic=None)
3557 Set array flags WRITEABLE, ALIGNED, (WRITEBACKIFCOPY and UPDATEIFCOPY),
3558 respectively.
3560 These Boolean-valued flags affect how numpy interprets the memory
3561 area used by `a` (see Notes below). The ALIGNED flag can only
3562 be set to True if the data is actually aligned according to the type.
3563 The WRITEBACKIFCOPY and (deprecated) UPDATEIFCOPY flags can never be set
3564 to True. The flag WRITEABLE can only be set to True if the array owns its
3565 own memory, or the ultimate owner of the memory exposes a writeable buffer
3566 interface, or is a string. (The exception for string is made so that
3567 unpickling can be done without copying memory.)
3569 Parameters
3570 ----------
3571 write : bool, optional
3572 Describes whether or not `a` can be written to.
3573 align : bool, optional
3574 Describes whether or not `a` is aligned properly for its type.
3575 uic : bool, optional
3576 Describes whether or not `a` is a copy of another "base" array.
3578 Notes
3579 -----
3580 Array flags provide information about how the memory area used
3581 for the array is to be interpreted. There are 7 Boolean flags
3582 in use, only four of which can be changed by the user:
3583 WRITEBACKIFCOPY, UPDATEIFCOPY, WRITEABLE, and ALIGNED.
3585 WRITEABLE (W) the data area can be written to;
3587 ALIGNED (A) the data and strides are aligned appropriately for the hardware
3588 (as determined by the compiler);
3590 UPDATEIFCOPY (U) (deprecated), replaced by WRITEBACKIFCOPY;
3592 WRITEBACKIFCOPY (X) this array is a copy of some other array (referenced
3593 by .base). When the C-API function PyArray_ResolveWritebackIfCopy is
3594 called, the base array will be updated with the contents of this array.
3596 All flags can be accessed using the single (upper case) letter as well
3597 as the full name.
3599 Examples
3600 --------
3601 >>> y = np.array([[3, 1, 7],
3602 ... [2, 0, 0],
3603 ... [8, 5, 9]])
3604 >>> y
3605 array([[3, 1, 7],
3606 [2, 0, 0],
3607 [8, 5, 9]])
3608 >>> y.flags
3609 C_CONTIGUOUS : True
3610 F_CONTIGUOUS : False
3611 OWNDATA : True
3612 WRITEABLE : True
3613 ALIGNED : True
3614 WRITEBACKIFCOPY : False
3615 UPDATEIFCOPY : False
3616 >>> y.setflags(write=0, align=0)
3617 >>> y.flags
3618 C_CONTIGUOUS : True
3619 F_CONTIGUOUS : False
3620 OWNDATA : True
3621 WRITEABLE : False
3622 ALIGNED : False
3623 WRITEBACKIFCOPY : False
3624 UPDATEIFCOPY : False
3625 >>> y.setflags(uic=1)
3626 Traceback (most recent call last):
3627 File "<stdin>", line 1, in <module>
3628 ValueError: cannot set WRITEBACKIFCOPY flag to True
3630 """))
3633add_newdoc('numpy.core.multiarray', 'ndarray', ('sort',
3634 """
3635 a.sort(axis=-1, kind=None, order=None)
3637 Sort an array in-place. Refer to `numpy.sort` for full documentation.
3639 Parameters
3640 ----------
3641 axis : int, optional
3642 Axis along which to sort. Default is -1, which means sort along the
3643 last axis.
3644 kind : {'quicksort', 'mergesort', 'heapsort', 'stable'}, optional
3645 Sorting algorithm. The default is 'quicksort'. Note that both 'stable'
3646 and 'mergesort' use timsort under the covers and, in general, the
3647 actual implementation will vary with datatype. The 'mergesort' option
3648 is retained for backwards compatibility.
3650 .. versionchanged:: 1.15.0.
3651 The 'stable' option was added.
3653 order : str or list of str, optional
3654 When `a` is an array with fields defined, this argument specifies
3655 which fields to compare first, second, etc. A single field can
3656 be specified as a string, and not all fields need be specified,
3657 but unspecified fields will still be used, in the order in which
3658 they come up in the dtype, to break ties.
3660 See Also
3661 --------
3662 numpy.sort : Return a sorted copy of an array.
3663 numpy.argsort : Indirect sort.
3664 numpy.lexsort : Indirect stable sort on multiple keys.
3665 numpy.searchsorted : Find elements in sorted array.
3666 numpy.partition: Partial sort.
3668 Notes
3669 -----
3670 See `numpy.sort` for notes on the different sorting algorithms.
3672 Examples
3673 --------
3674 >>> a = np.array([[1,4], [3,1]])
3675 >>> a.sort(axis=1)
3676 >>> a
3677 array([[1, 4],
3678 [1, 3]])
3679 >>> a.sort(axis=0)
3680 >>> a
3681 array([[1, 3],
3682 [1, 4]])
3684 Use the `order` keyword to specify a field to use when sorting a
3685 structured array:
3687 >>> a = np.array([('a', 2), ('c', 1)], dtype=[('x', 'S1'), ('y', int)])
3688 >>> a.sort(order='y')
3689 >>> a
3690 array([(b'c', 1), (b'a', 2)],
3691 dtype=[('x', 'S1'), ('y', '<i8')])
3693 """))
3696add_newdoc('numpy.core.multiarray', 'ndarray', ('partition',
3697 """
3698 a.partition(kth, axis=-1, kind='introselect', order=None)
3700 Rearranges the elements in the array in such a way that the value of the
3701 element in kth position is in the position it would be in a sorted array.
3702 All elements smaller than the kth element are moved before this element and
3703 all equal or greater are moved behind it. The ordering of the elements in
3704 the two partitions is undefined.
3706 .. versionadded:: 1.8.0
3708 Parameters
3709 ----------
3710 kth : int or sequence of ints
3711 Element index to partition by. The kth element value will be in its
3712 final sorted position and all smaller elements will be moved before it
3713 and all equal or greater elements behind it.
3714 The order of all elements in the partitions is undefined.
3715 If provided with a sequence of kth it will partition all elements
3716 indexed by kth of them into their sorted position at once.
3717 axis : int, optional
3718 Axis along which to sort. Default is -1, which means sort along the
3719 last axis.
3720 kind : {'introselect'}, optional
3721 Selection algorithm. Default is 'introselect'.
3722 order : str or list of str, optional
3723 When `a` is an array with fields defined, this argument specifies
3724 which fields to compare first, second, etc. A single field can
3725 be specified as a string, and not all fields need to be specified,
3726 but unspecified fields will still be used, in the order in which
3727 they come up in the dtype, to break ties.
3729 See Also
3730 --------
3731 numpy.partition : Return a parititioned copy of an array.
3732 argpartition : Indirect partition.
3733 sort : Full sort.
3735 Notes
3736 -----
3737 See ``np.partition`` for notes on the different algorithms.
3739 Examples
3740 --------
3741 >>> a = np.array([3, 4, 2, 1])
3742 >>> a.partition(3)
3743 >>> a
3744 array([2, 1, 3, 4])
3746 >>> a.partition((1, 3))
3747 >>> a
3748 array([1, 2, 3, 4])
3749 """))
3752add_newdoc('numpy.core.multiarray', 'ndarray', ('squeeze',
3753 """
3754 a.squeeze(axis=None)
3756 Remove single-dimensional entries from the shape of `a`.
3758 Refer to `numpy.squeeze` for full documentation.
3760 See Also
3761 --------
3762 numpy.squeeze : equivalent function
3764 """))
3767add_newdoc('numpy.core.multiarray', 'ndarray', ('std',
3768 """
3769 a.std(axis=None, dtype=None, out=None, ddof=0, keepdims=False)
3771 Returns the standard deviation of the array elements along given axis.
3773 Refer to `numpy.std` for full documentation.
3775 See Also
3776 --------
3777 numpy.std : equivalent function
3779 """))
3782add_newdoc('numpy.core.multiarray', 'ndarray', ('sum',
3783 """
3784 a.sum(axis=None, dtype=None, out=None, keepdims=False, initial=0, where=True)
3786 Return the sum of the array elements over the given axis.
3788 Refer to `numpy.sum` for full documentation.
3790 See Also
3791 --------
3792 numpy.sum : equivalent function
3794 """))
3797add_newdoc('numpy.core.multiarray', 'ndarray', ('swapaxes',
3798 """
3799 a.swapaxes(axis1, axis2)
3801 Return a view of the array with `axis1` and `axis2` interchanged.
3803 Refer to `numpy.swapaxes` for full documentation.
3805 See Also
3806 --------
3807 numpy.swapaxes : equivalent function
3809 """))
3812add_newdoc('numpy.core.multiarray', 'ndarray', ('take',
3813 """
3814 a.take(indices, axis=None, out=None, mode='raise')
3816 Return an array formed from the elements of `a` at the given indices.
3818 Refer to `numpy.take` for full documentation.
3820 See Also
3821 --------
3822 numpy.take : equivalent function
3824 """))
3827add_newdoc('numpy.core.multiarray', 'ndarray', ('tofile',
3828 """
3829 a.tofile(fid, sep="", format="%s")
3831 Write array to a file as text or binary (default).
3833 Data is always written in 'C' order, independent of the order of `a`.
3834 The data produced by this method can be recovered using the function
3835 fromfile().
3837 Parameters
3838 ----------
3839 fid : file or str or Path
3840 An open file object, or a string containing a filename.
3842 .. versionchanged:: 1.17.0
3843 `pathlib.Path` objects are now accepted.
3845 sep : str
3846 Separator between array items for text output.
3847 If "" (empty), a binary file is written, equivalent to
3848 ``file.write(a.tobytes())``.
3849 format : str
3850 Format string for text file output.
3851 Each entry in the array is formatted to text by first converting
3852 it to the closest Python type, and then using "format" % item.
3854 Notes
3855 -----
3856 This is a convenience function for quick storage of array data.
3857 Information on endianness and precision is lost, so this method is not a
3858 good choice for files intended to archive data or transport data between
3859 machines with different endianness. Some of these problems can be overcome
3860 by outputting the data as text files, at the expense of speed and file
3861 size.
3863 When fid is a file object, array contents are directly written to the
3864 file, bypassing the file object's ``write`` method. As a result, tofile
3865 cannot be used with files objects supporting compression (e.g., GzipFile)
3866 or file-like objects that do not support ``fileno()`` (e.g., BytesIO).
3868 """))
3871add_newdoc('numpy.core.multiarray', 'ndarray', ('tolist',
3872 """
3873 a.tolist()
3875 Return the array as an ``a.ndim``-levels deep nested list of Python scalars.
3877 Return a copy of the array data as a (nested) Python list.
3878 Data items are converted to the nearest compatible builtin Python type, via
3879 the `~numpy.ndarray.item` function.
3881 If ``a.ndim`` is 0, then since the depth of the nested list is 0, it will
3882 not be a list at all, but a simple Python scalar.
3884 Parameters
3885 ----------
3886 none
3888 Returns
3889 -------
3890 y : object, or list of object, or list of list of object, or ...
3891 The possibly nested list of array elements.
3893 Notes
3894 -----
3895 The array may be recreated via ``a = np.array(a.tolist())``, although this
3896 may sometimes lose precision.
3898 Examples
3899 --------
3900 For a 1D array, ``a.tolist()`` is almost the same as ``list(a)``,
3901 except that ``tolist`` changes numpy scalars to Python scalars:
3903 >>> a = np.uint32([1, 2])
3904 >>> a_list = list(a)
3905 >>> a_list
3906 [1, 2]
3907 >>> type(a_list[0])
3908 <class 'numpy.uint32'>
3909 >>> a_tolist = a.tolist()
3910 >>> a_tolist
3911 [1, 2]
3912 >>> type(a_tolist[0])
3913 <class 'int'>
3915 Additionally, for a 2D array, ``tolist`` applies recursively:
3917 >>> a = np.array([[1, 2], [3, 4]])
3918 >>> list(a)
3919 [array([1, 2]), array([3, 4])]
3920 >>> a.tolist()
3921 [[1, 2], [3, 4]]
3923 The base case for this recursion is a 0D array:
3925 >>> a = np.array(1)
3926 >>> list(a)
3927 Traceback (most recent call last):
3928 ...
3929 TypeError: iteration over a 0-d array
3930 >>> a.tolist()
3931 1
3932 """))
3935add_newdoc('numpy.core.multiarray', 'ndarray', ('tobytes', """
3936 a.tobytes(order='C')
3938 Construct Python bytes containing the raw data bytes in the array.
3940 Constructs Python bytes showing a copy of the raw contents of
3941 data memory. The bytes object can be produced in either 'C' or 'Fortran',
3942 or 'Any' order (the default is 'C'-order). 'Any' order means C-order
3943 unless the F_CONTIGUOUS flag in the array is set, in which case it
3944 means 'Fortran' order.
3946 .. versionadded:: 1.9.0
3948 Parameters
3949 ----------
3950 order : {'C', 'F', None}, optional
3951 Order of the data for multidimensional arrays:
3952 C, Fortran, or the same as for the original array.
3954 Returns
3955 -------
3956 s : bytes
3957 Python bytes exhibiting a copy of `a`'s raw data.
3959 Examples
3960 --------
3961 >>> x = np.array([[0, 1], [2, 3]], dtype='<u2')
3962 >>> x.tobytes()
3963 b'\\x00\\x00\\x01\\x00\\x02\\x00\\x03\\x00'
3964 >>> x.tobytes('C') == x.tobytes()
3965 True
3966 >>> x.tobytes('F')
3967 b'\\x00\\x00\\x02\\x00\\x01\\x00\\x03\\x00'
3969 """))
3972add_newdoc('numpy.core.multiarray', 'ndarray', ('tostring', r"""
3973 a.tostring(order='C')
3975 A compatibility alias for `tobytes`, with exactly the same behavior.
3977 Despite its name, it returns `bytes` not `str`\ s.
3979 .. deprecated:: 1.19.0
3980 """))
3983add_newdoc('numpy.core.multiarray', 'ndarray', ('trace',
3984 """
3985 a.trace(offset=0, axis1=0, axis2=1, dtype=None, out=None)
3987 Return the sum along diagonals of the array.
3989 Refer to `numpy.trace` for full documentation.
3991 See Also
3992 --------
3993 numpy.trace : equivalent function
3995 """))
3998add_newdoc('numpy.core.multiarray', 'ndarray', ('transpose',
3999 """
4000 a.transpose(*axes)
4002 Returns a view of the array with axes transposed.
4004 For a 1-D array this has no effect, as a transposed vector is simply the
4005 same vector. To convert a 1-D array into a 2D column vector, an additional
4006 dimension must be added. `np.atleast2d(a).T` achieves this, as does
4007 `a[:, np.newaxis]`.
4008 For a 2-D array, this is a standard matrix transpose.
4009 For an n-D array, if axes are given, their order indicates how the
4010 axes are permuted (see Examples). If axes are not provided and
4011 ``a.shape = (i[0], i[1], ... i[n-2], i[n-1])``, then
4012 ``a.transpose().shape = (i[n-1], i[n-2], ... i[1], i[0])``.
4014 Parameters
4015 ----------
4016 axes : None, tuple of ints, or `n` ints
4018 * None or no argument: reverses the order of the axes.
4020 * tuple of ints: `i` in the `j`-th place in the tuple means `a`'s
4021 `i`-th axis becomes `a.transpose()`'s `j`-th axis.
4023 * `n` ints: same as an n-tuple of the same ints (this form is
4024 intended simply as a "convenience" alternative to the tuple form)
4026 Returns
4027 -------
4028 out : ndarray
4029 View of `a`, with axes suitably permuted.
4031 See Also
4032 --------
4033 ndarray.T : Array property returning the array transposed.
4034 ndarray.reshape : Give a new shape to an array without changing its data.
4036 Examples
4037 --------
4038 >>> a = np.array([[1, 2], [3, 4]])
4039 >>> a
4040 array([[1, 2],
4041 [3, 4]])
4042 >>> a.transpose()
4043 array([[1, 3],
4044 [2, 4]])
4045 >>> a.transpose((1, 0))
4046 array([[1, 3],
4047 [2, 4]])
4048 >>> a.transpose(1, 0)
4049 array([[1, 3],
4050 [2, 4]])
4052 """))
4055add_newdoc('numpy.core.multiarray', 'ndarray', ('var',
4056 """
4057 a.var(axis=None, dtype=None, out=None, ddof=0, keepdims=False)
4059 Returns the variance of the array elements, along given axis.
4061 Refer to `numpy.var` for full documentation.
4063 See Also
4064 --------
4065 numpy.var : equivalent function
4067 """))
4070add_newdoc('numpy.core.multiarray', 'ndarray', ('view',
4071 """
4072 a.view([dtype][, type])
4074 New view of array with the same data.
4076 .. note::
4077 Passing None for ``dtype`` is different from omitting the parameter,
4078 since the former invokes ``dtype(None)`` which is an alias for
4079 ``dtype('float_')``.
4081 Parameters
4082 ----------
4083 dtype : data-type or ndarray sub-class, optional
4084 Data-type descriptor of the returned view, e.g., float32 or int16.
4085 Omitting it results in the view having the same data-type as `a`.
4086 This argument can also be specified as an ndarray sub-class, which
4087 then specifies the type of the returned object (this is equivalent to
4088 setting the ``type`` parameter).
4089 type : Python type, optional
4090 Type of the returned view, e.g., ndarray or matrix. Again, omission
4091 of the parameter results in type preservation.
4093 Notes
4094 -----
4095 ``a.view()`` is used two different ways:
4097 ``a.view(some_dtype)`` or ``a.view(dtype=some_dtype)`` constructs a view
4098 of the array's memory with a different data-type. This can cause a
4099 reinterpretation of the bytes of memory.
4101 ``a.view(ndarray_subclass)`` or ``a.view(type=ndarray_subclass)`` just
4102 returns an instance of `ndarray_subclass` that looks at the same array
4103 (same shape, dtype, etc.) This does not cause a reinterpretation of the
4104 memory.
4106 For ``a.view(some_dtype)``, if ``some_dtype`` has a different number of
4107 bytes per entry than the previous dtype (for example, converting a
4108 regular array to a structured array), then the behavior of the view
4109 cannot be predicted just from the superficial appearance of ``a`` (shown
4110 by ``print(a)``). It also depends on exactly how ``a`` is stored in
4111 memory. Therefore if ``a`` is C-ordered versus fortran-ordered, versus
4112 defined as a slice or transpose, etc., the view may give different
4113 results.
4116 Examples
4117 --------
4118 >>> x = np.array([(1, 2)], dtype=[('a', np.int8), ('b', np.int8)])
4120 Viewing array data using a different type and dtype:
4122 >>> y = x.view(dtype=np.int16, type=np.matrix)
4123 >>> y
4124 matrix([[513]], dtype=int16)
4125 >>> print(type(y))
4126 <class 'numpy.matrix'>
4128 Creating a view on a structured array so it can be used in calculations
4130 >>> x = np.array([(1, 2),(3,4)], dtype=[('a', np.int8), ('b', np.int8)])
4131 >>> xv = x.view(dtype=np.int8).reshape(-1,2)
4132 >>> xv
4133 array([[1, 2],
4134 [3, 4]], dtype=int8)
4135 >>> xv.mean(0)
4136 array([2., 3.])
4138 Making changes to the view changes the underlying array
4140 >>> xv[0,1] = 20
4141 >>> x
4142 array([(1, 20), (3, 4)], dtype=[('a', 'i1'), ('b', 'i1')])
4144 Using a view to convert an array to a recarray:
4146 >>> z = x.view(np.recarray)
4147 >>> z.a
4148 array([1, 3], dtype=int8)
4150 Views share data:
4152 >>> x[0] = (9, 10)
4153 >>> z[0]
4154 (9, 10)
4156 Views that change the dtype size (bytes per entry) should normally be
4157 avoided on arrays defined by slices, transposes, fortran-ordering, etc.:
4159 >>> x = np.array([[1,2,3],[4,5,6]], dtype=np.int16)
4160 >>> y = x[:, 0:2]
4161 >>> y
4162 array([[1, 2],
4163 [4, 5]], dtype=int16)
4164 >>> y.view(dtype=[('width', np.int16), ('length', np.int16)])
4165 Traceback (most recent call last):
4166 ...
4167 ValueError: To change to a dtype of a different size, the array must be C-contiguous
4168 >>> z = y.copy()
4169 >>> z.view(dtype=[('width', np.int16), ('length', np.int16)])
4170 array([[(1, 2)],
4171 [(4, 5)]], dtype=[('width', '<i2'), ('length', '<i2')])
4172 """))
4175##############################################################################
4176#
4177# umath functions
4178#
4179##############################################################################
4181add_newdoc('numpy.core.umath', 'frompyfunc',
4182 """
4183 frompyfunc(func, nin, nout, *[, identity])
4185 Takes an arbitrary Python function and returns a NumPy ufunc.
4187 Can be used, for example, to add broadcasting to a built-in Python
4188 function (see Examples section).
4190 Parameters
4191 ----------
4192 func : Python function object
4193 An arbitrary Python function.
4194 nin : int
4195 The number of input arguments.
4196 nout : int
4197 The number of objects returned by `func`.
4198 identity : object, optional
4199 The value to use for the `~numpy.ufunc.identity` attribute of the resulting
4200 object. If specified, this is equivalent to setting the underlying
4201 C ``identity`` field to ``PyUFunc_IdentityValue``.
4202 If omitted, the identity is set to ``PyUFunc_None``. Note that this is
4203 _not_ equivalent to setting the identity to ``None``, which implies the
4204 operation is reorderable.
4206 Returns
4207 -------
4208 out : ufunc
4209 Returns a NumPy universal function (``ufunc``) object.
4211 See Also
4212 --------
4213 vectorize : Evaluates pyfunc over input arrays using broadcasting rules of numpy.
4215 Notes
4216 -----
4217 The returned ufunc always returns PyObject arrays.
4219 Examples
4220 --------
4221 Use frompyfunc to add broadcasting to the Python function ``oct``:
4223 >>> oct_array = np.frompyfunc(oct, 1, 1)
4224 >>> oct_array(np.array((10, 30, 100)))
4225 array(['0o12', '0o36', '0o144'], dtype=object)
4226 >>> np.array((oct(10), oct(30), oct(100))) # for comparison
4227 array(['0o12', '0o36', '0o144'], dtype='<U5')
4229 """)
4231add_newdoc('numpy.core.umath', 'geterrobj',
4232 """
4233 geterrobj()
4235 Return the current object that defines floating-point error handling.
4237 The error object contains all information that defines the error handling
4238 behavior in NumPy. `geterrobj` is used internally by the other
4239 functions that get and set error handling behavior (`geterr`, `seterr`,
4240 `geterrcall`, `seterrcall`).
4242 Returns
4243 -------
4244 errobj : list
4245 The error object, a list containing three elements:
4246 [internal numpy buffer size, error mask, error callback function].
4248 The error mask is a single integer that holds the treatment information
4249 on all four floating point errors. The information for each error type
4250 is contained in three bits of the integer. If we print it in base 8, we
4251 can see what treatment is set for "invalid", "under", "over", and
4252 "divide" (in that order). The printed string can be interpreted with
4254 * 0 : 'ignore'
4255 * 1 : 'warn'
4256 * 2 : 'raise'
4257 * 3 : 'call'
4258 * 4 : 'print'
4259 * 5 : 'log'
4261 See Also
4262 --------
4263 seterrobj, seterr, geterr, seterrcall, geterrcall
4264 getbufsize, setbufsize
4266 Notes
4267 -----
4268 For complete documentation of the types of floating-point exceptions and
4269 treatment options, see `seterr`.
4271 Examples
4272 --------
4273 >>> np.geterrobj() # first get the defaults
4274 [8192, 521, None]
4276 >>> def err_handler(type, flag):
4277 ... print("Floating point error (%s), with flag %s" % (type, flag))
4278 ...
4279 >>> old_bufsize = np.setbufsize(20000)
4280 >>> old_err = np.seterr(divide='raise')
4281 >>> old_handler = np.seterrcall(err_handler)
4282 >>> np.geterrobj()
4283 [8192, 521, <function err_handler at 0x91dcaac>]
4285 >>> old_err = np.seterr(all='ignore')
4286 >>> np.base_repr(np.geterrobj()[1], 8)
4287 '0'
4288 >>> old_err = np.seterr(divide='warn', over='log', under='call',
4289 ... invalid='print')
4290 >>> np.base_repr(np.geterrobj()[1], 8)
4291 '4351'
4293 """)
4295add_newdoc('numpy.core.umath', 'seterrobj',
4296 """
4297 seterrobj(errobj)
4299 Set the object that defines floating-point error handling.
4301 The error object contains all information that defines the error handling
4302 behavior in NumPy. `seterrobj` is used internally by the other
4303 functions that set error handling behavior (`seterr`, `seterrcall`).
4305 Parameters
4306 ----------
4307 errobj : list
4308 The error object, a list containing three elements:
4309 [internal numpy buffer size, error mask, error callback function].
4311 The error mask is a single integer that holds the treatment information
4312 on all four floating point errors. The information for each error type
4313 is contained in three bits of the integer. If we print it in base 8, we
4314 can see what treatment is set for "invalid", "under", "over", and
4315 "divide" (in that order). The printed string can be interpreted with
4317 * 0 : 'ignore'
4318 * 1 : 'warn'
4319 * 2 : 'raise'
4320 * 3 : 'call'
4321 * 4 : 'print'
4322 * 5 : 'log'
4324 See Also
4325 --------
4326 geterrobj, seterr, geterr, seterrcall, geterrcall
4327 getbufsize, setbufsize
4329 Notes
4330 -----
4331 For complete documentation of the types of floating-point exceptions and
4332 treatment options, see `seterr`.
4334 Examples
4335 --------
4336 >>> old_errobj = np.geterrobj() # first get the defaults
4337 >>> old_errobj
4338 [8192, 521, None]
4340 >>> def err_handler(type, flag):
4341 ... print("Floating point error (%s), with flag %s" % (type, flag))
4342 ...
4343 >>> new_errobj = [20000, 12, err_handler]
4344 >>> np.seterrobj(new_errobj)
4345 >>> np.base_repr(12, 8) # int for divide=4 ('print') and over=1 ('warn')
4346 '14'
4347 >>> np.geterr()
4348 {'over': 'warn', 'divide': 'print', 'invalid': 'ignore', 'under': 'ignore'}
4349 >>> np.geterrcall() is err_handler
4350 True
4352 """)
4355##############################################################################
4356#
4357# compiled_base functions
4358#
4359##############################################################################
4361add_newdoc('numpy.core.multiarray', 'add_docstring',
4362 """
4363 add_docstring(obj, docstring)
4365 Add a docstring to a built-in obj if possible.
4366 If the obj already has a docstring raise a RuntimeError
4367 If this routine does not know how to add a docstring to the object
4368 raise a TypeError
4369 """)
4371add_newdoc('numpy.core.umath', '_add_newdoc_ufunc',
4372 """
4373 add_ufunc_docstring(ufunc, new_docstring)
4375 Replace the docstring for a ufunc with new_docstring.
4376 This method will only work if the current docstring for
4377 the ufunc is NULL. (At the C level, i.e. when ufunc->doc is NULL.)
4379 Parameters
4380 ----------
4381 ufunc : numpy.ufunc
4382 A ufunc whose current doc is NULL.
4383 new_docstring : string
4384 The new docstring for the ufunc.
4386 Notes
4387 -----
4388 This method allocates memory for new_docstring on
4389 the heap. Technically this creates a mempory leak, since this
4390 memory will not be reclaimed until the end of the program
4391 even if the ufunc itself is removed. However this will only
4392 be a problem if the user is repeatedly creating ufuncs with
4393 no documentation, adding documentation via add_newdoc_ufunc,
4394 and then throwing away the ufunc.
4395 """)
4397add_newdoc('numpy.core.multiarray', '_set_madvise_hugepage',
4398 """
4399 _set_madvise_hugepage(enabled: bool) -> bool
4401 Set or unset use of ``madvise (2)`` MADV_HUGEPAGE support when
4402 allocating the array data. Returns the previously set value.
4403 See `global_state` for more information.
4404 """)
4406add_newdoc('numpy.core._multiarray_tests', 'format_float_OSprintf_g',
4407 """
4408 format_float_OSprintf_g(val, precision)
4410 Print a floating point scalar using the system's printf function,
4411 equivalent to:
4413 printf("%.*g", precision, val);
4415 for half/float/double, or replacing 'g' by 'Lg' for longdouble. This
4416 method is designed to help cross-validate the format_float_* methods.
4418 Parameters
4419 ----------
4420 val : python float or numpy floating scalar
4421 Value to format.
4423 precision : non-negative integer, optional
4424 Precision given to printf.
4426 Returns
4427 -------
4428 rep : string
4429 The string representation of the floating point value
4431 See Also
4432 --------
4433 format_float_scientific
4434 format_float_positional
4435 """)
4438##############################################################################
4439#
4440# Documentation for ufunc attributes and methods
4441#
4442##############################################################################
4445##############################################################################
4446#
4447# ufunc object
4448#
4449##############################################################################
4451add_newdoc('numpy.core', 'ufunc',
4452 """
4453 Functions that operate element by element on whole arrays.
4455 To see the documentation for a specific ufunc, use `info`. For
4456 example, ``np.info(np.sin)``. Because ufuncs are written in C
4457 (for speed) and linked into Python with NumPy's ufunc facility,
4458 Python's help() function finds this page whenever help() is called
4459 on a ufunc.
4461 A detailed explanation of ufuncs can be found in the docs for :ref:`ufuncs`.
4463 Calling ufuncs:
4464 ===============
4466 op(*x[, out], where=True, **kwargs)
4467 Apply `op` to the arguments `*x` elementwise, broadcasting the arguments.
4469 The broadcasting rules are:
4471 * Dimensions of length 1 may be prepended to either array.
4472 * Arrays may be repeated along dimensions of length 1.
4474 Parameters
4475 ----------
4476 *x : array_like
4477 Input arrays.
4478 out : ndarray, None, or tuple of ndarray and None, optional
4479 Alternate array object(s) in which to put the result; if provided, it
4480 must have a shape that the inputs broadcast to. A tuple of arrays
4481 (possible only as a keyword argument) must have length equal to the
4482 number of outputs; use None for uninitialized outputs to be
4483 allocated by the ufunc.
4484 where : array_like, optional
4485 This condition is broadcast over the input. At locations where the
4486 condition is True, the `out` array will be set to the ufunc result.
4487 Elsewhere, the `out` array will retain its original value.
4488 Note that if an uninitialized `out` array is created via the default
4489 ``out=None``, locations within it where the condition is False will
4490 remain uninitialized.
4491 **kwargs
4492 For other keyword-only arguments, see the :ref:`ufunc docs <ufuncs.kwargs>`.
4494 Returns
4495 -------
4496 r : ndarray or tuple of ndarray
4497 `r` will have the shape that the arrays in `x` broadcast to; if `out` is
4498 provided, it will be returned. If not, `r` will be allocated and
4499 may contain uninitialized values. If the function has more than one
4500 output, then the result will be a tuple of arrays.
4502 """)
4505##############################################################################
4506#
4507# ufunc attributes
4508#
4509##############################################################################
4511add_newdoc('numpy.core', 'ufunc', ('identity',
4512 """
4513 The identity value.
4515 Data attribute containing the identity element for the ufunc, if it has one.
4516 If it does not, the attribute value is None.
4518 Examples
4519 --------
4520 >>> np.add.identity
4521 0
4522 >>> np.multiply.identity
4523 1
4524 >>> np.power.identity
4525 1
4526 >>> print(np.exp.identity)
4527 None
4528 """))
4530add_newdoc('numpy.core', 'ufunc', ('nargs',
4531 """
4532 The number of arguments.
4534 Data attribute containing the number of arguments the ufunc takes, including
4535 optional ones.
4537 Notes
4538 -----
4539 Typically this value will be one more than what you might expect because all
4540 ufuncs take the optional "out" argument.
4542 Examples
4543 --------
4544 >>> np.add.nargs
4545 3
4546 >>> np.multiply.nargs
4547 3
4548 >>> np.power.nargs
4549 3
4550 >>> np.exp.nargs
4551 2
4552 """))
4554add_newdoc('numpy.core', 'ufunc', ('nin',
4555 """
4556 The number of inputs.
4558 Data attribute containing the number of arguments the ufunc treats as input.
4560 Examples
4561 --------
4562 >>> np.add.nin
4563 2
4564 >>> np.multiply.nin
4565 2
4566 >>> np.power.nin
4567 2
4568 >>> np.exp.nin
4569 1
4570 """))
4572add_newdoc('numpy.core', 'ufunc', ('nout',
4573 """
4574 The number of outputs.
4576 Data attribute containing the number of arguments the ufunc treats as output.
4578 Notes
4579 -----
4580 Since all ufuncs can take output arguments, this will always be (at least) 1.
4582 Examples
4583 --------
4584 >>> np.add.nout
4585 1
4586 >>> np.multiply.nout
4587 1
4588 >>> np.power.nout
4589 1
4590 >>> np.exp.nout
4591 1
4593 """))
4595add_newdoc('numpy.core', 'ufunc', ('ntypes',
4596 """
4597 The number of types.
4599 The number of numerical NumPy types - of which there are 18 total - on which
4600 the ufunc can operate.
4602 See Also
4603 --------
4604 numpy.ufunc.types
4606 Examples
4607 --------
4608 >>> np.add.ntypes
4609 18
4610 >>> np.multiply.ntypes
4611 18
4612 >>> np.power.ntypes
4613 17
4614 >>> np.exp.ntypes
4615 7
4616 >>> np.remainder.ntypes
4617 14
4619 """))
4621add_newdoc('numpy.core', 'ufunc', ('types',
4622 """
4623 Returns a list with types grouped input->output.
4625 Data attribute listing the data-type "Domain-Range" groupings the ufunc can
4626 deliver. The data-types are given using the character codes.
4628 See Also
4629 --------
4630 numpy.ufunc.ntypes
4632 Examples
4633 --------
4634 >>> np.add.types
4635 ['??->?', 'bb->b', 'BB->B', 'hh->h', 'HH->H', 'ii->i', 'II->I', 'll->l',
4636 'LL->L', 'qq->q', 'QQ->Q', 'ff->f', 'dd->d', 'gg->g', 'FF->F', 'DD->D',
4637 'GG->G', 'OO->O']
4639 >>> np.multiply.types
4640 ['??->?', 'bb->b', 'BB->B', 'hh->h', 'HH->H', 'ii->i', 'II->I', 'll->l',
4641 'LL->L', 'qq->q', 'QQ->Q', 'ff->f', 'dd->d', 'gg->g', 'FF->F', 'DD->D',
4642 'GG->G', 'OO->O']
4644 >>> np.power.types
4645 ['bb->b', 'BB->B', 'hh->h', 'HH->H', 'ii->i', 'II->I', 'll->l', 'LL->L',
4646 'qq->q', 'QQ->Q', 'ff->f', 'dd->d', 'gg->g', 'FF->F', 'DD->D', 'GG->G',
4647 'OO->O']
4649 >>> np.exp.types
4650 ['f->f', 'd->d', 'g->g', 'F->F', 'D->D', 'G->G', 'O->O']
4652 >>> np.remainder.types
4653 ['bb->b', 'BB->B', 'hh->h', 'HH->H', 'ii->i', 'II->I', 'll->l', 'LL->L',
4654 'qq->q', 'QQ->Q', 'ff->f', 'dd->d', 'gg->g', 'OO->O']
4656 """))
4658add_newdoc('numpy.core', 'ufunc', ('signature',
4659 """
4660 Definition of the core elements a generalized ufunc operates on.
4662 The signature determines how the dimensions of each input/output array
4663 are split into core and loop dimensions:
4665 1. Each dimension in the signature is matched to a dimension of the
4666 corresponding passed-in array, starting from the end of the shape tuple.
4667 2. Core dimensions assigned to the same label in the signature must have
4668 exactly matching sizes, no broadcasting is performed.
4669 3. The core dimensions are removed from all inputs and the remaining
4670 dimensions are broadcast together, defining the loop dimensions.
4672 Notes
4673 -----
4674 Generalized ufuncs are used internally in many linalg functions, and in
4675 the testing suite; the examples below are taken from these.
4676 For ufuncs that operate on scalars, the signature is None, which is
4677 equivalent to '()' for every argument.
4679 Examples
4680 --------
4681 >>> np.core.umath_tests.matrix_multiply.signature
4682 '(m,n),(n,p)->(m,p)'
4683 >>> np.linalg._umath_linalg.det.signature
4684 '(m,m)->()'
4685 >>> np.add.signature is None
4686 True # equivalent to '(),()->()'
4687 """))
4689##############################################################################
4690#
4691# ufunc methods
4692#
4693##############################################################################
4695add_newdoc('numpy.core', 'ufunc', ('reduce',
4696 """
4697 reduce(a, axis=0, dtype=None, out=None, keepdims=False, initial=<no value>, where=True)
4699 Reduces `a`'s dimension by one, by applying ufunc along one axis.
4701 Let :math:`a.shape = (N_0, ..., N_i, ..., N_{M-1})`. Then
4702 :math:`ufunc.reduce(a, axis=i)[k_0, ..,k_{i-1}, k_{i+1}, .., k_{M-1}]` =
4703 the result of iterating `j` over :math:`range(N_i)`, cumulatively applying
4704 ufunc to each :math:`a[k_0, ..,k_{i-1}, j, k_{i+1}, .., k_{M-1}]`.
4705 For a one-dimensional array, reduce produces results equivalent to:
4706 ::
4708 r = op.identity # op = ufunc
4709 for i in range(len(A)):
4710 r = op(r, A[i])
4711 return r
4713 For example, add.reduce() is equivalent to sum().
4715 Parameters
4716 ----------
4717 a : array_like
4718 The array to act on.
4719 axis : None or int or tuple of ints, optional
4720 Axis or axes along which a reduction is performed.
4721 The default (`axis` = 0) is perform a reduction over the first
4722 dimension of the input array. `axis` may be negative, in
4723 which case it counts from the last to the first axis.
4725 .. versionadded:: 1.7.0
4727 If this is None, a reduction is performed over all the axes.
4728 If this is a tuple of ints, a reduction is performed on multiple
4729 axes, instead of a single axis or all the axes as before.
4731 For operations which are either not commutative or not associative,
4732 doing a reduction over multiple axes is not well-defined. The
4733 ufuncs do not currently raise an exception in this case, but will
4734 likely do so in the future.
4735 dtype : data-type code, optional
4736 The type used to represent the intermediate results. Defaults
4737 to the data-type of the output array if this is provided, or
4738 the data-type of the input array if no output array is provided.
4739 out : ndarray, None, or tuple of ndarray and None, optional
4740 A location into which the result is stored. If not provided or None,
4741 a freshly-allocated array is returned. For consistency with
4742 ``ufunc.__call__``, if given as a keyword, this may be wrapped in a
4743 1-element tuple.
4745 .. versionchanged:: 1.13.0
4746 Tuples are allowed for keyword argument.
4747 keepdims : bool, optional
4748 If this is set to True, the axes which are reduced are left
4749 in the result as dimensions with size one. With this option,
4750 the result will broadcast correctly against the original `arr`.
4752 .. versionadded:: 1.7.0
4753 initial : scalar, optional
4754 The value with which to start the reduction.
4755 If the ufunc has no identity or the dtype is object, this defaults
4756 to None - otherwise it defaults to ufunc.identity.
4757 If ``None`` is given, the first element of the reduction is used,
4758 and an error is thrown if the reduction is empty.
4760 .. versionadded:: 1.15.0
4762 where : array_like of bool, optional
4763 A boolean array which is broadcasted to match the dimensions
4764 of `a`, and selects elements to include in the reduction. Note
4765 that for ufuncs like ``minimum`` that do not have an identity
4766 defined, one has to pass in also ``initial``.
4768 .. versionadded:: 1.17.0
4770 Returns
4771 -------
4772 r : ndarray
4773 The reduced array. If `out` was supplied, `r` is a reference to it.
4775 Examples
4776 --------
4777 >>> np.multiply.reduce([2,3,5])
4778 30
4780 A multi-dimensional array example:
4782 >>> X = np.arange(8).reshape((2,2,2))
4783 >>> X
4784 array([[[0, 1],
4785 [2, 3]],
4786 [[4, 5],
4787 [6, 7]]])
4788 >>> np.add.reduce(X, 0)
4789 array([[ 4, 6],
4790 [ 8, 10]])
4791 >>> np.add.reduce(X) # confirm: default axis value is 0
4792 array([[ 4, 6],
4793 [ 8, 10]])
4794 >>> np.add.reduce(X, 1)
4795 array([[ 2, 4],
4796 [10, 12]])
4797 >>> np.add.reduce(X, 2)
4798 array([[ 1, 5],
4799 [ 9, 13]])
4801 You can use the ``initial`` keyword argument to initialize the reduction
4802 with a different value, and ``where`` to select specific elements to include:
4804 >>> np.add.reduce([10], initial=5)
4805 15
4806 >>> np.add.reduce(np.ones((2, 2, 2)), axis=(0, 2), initial=10)
4807 array([14., 14.])
4808 >>> a = np.array([10., np.nan, 10])
4809 >>> np.add.reduce(a, where=~np.isnan(a))
4810 20.0
4812 Allows reductions of empty arrays where they would normally fail, i.e.
4813 for ufuncs without an identity.
4815 >>> np.minimum.reduce([], initial=np.inf)
4816 inf
4817 >>> np.minimum.reduce([[1., 2.], [3., 4.]], initial=10., where=[True, False])
4818 array([ 1., 10.])
4819 >>> np.minimum.reduce([])
4820 Traceback (most recent call last):
4821 ...
4822 ValueError: zero-size array to reduction operation minimum which has no identity
4823 """))
4825add_newdoc('numpy.core', 'ufunc', ('accumulate',
4826 """
4827 accumulate(array, axis=0, dtype=None, out=None)
4829 Accumulate the result of applying the operator to all elements.
4831 For a one-dimensional array, accumulate produces results equivalent to::
4833 r = np.empty(len(A))
4834 t = op.identity # op = the ufunc being applied to A's elements
4835 for i in range(len(A)):
4836 t = op(t, A[i])
4837 r[i] = t
4838 return r
4840 For example, add.accumulate() is equivalent to np.cumsum().
4842 For a multi-dimensional array, accumulate is applied along only one
4843 axis (axis zero by default; see Examples below) so repeated use is
4844 necessary if one wants to accumulate over multiple axes.
4846 Parameters
4847 ----------
4848 array : array_like
4849 The array to act on.
4850 axis : int, optional
4851 The axis along which to apply the accumulation; default is zero.
4852 dtype : data-type code, optional
4853 The data-type used to represent the intermediate results. Defaults
4854 to the data-type of the output array if such is provided, or the
4855 the data-type of the input array if no output array is provided.
4856 out : ndarray, None, or tuple of ndarray and None, optional
4857 A location into which the result is stored. If not provided or None,
4858 a freshly-allocated array is returned. For consistency with
4859 ``ufunc.__call__``, if given as a keyword, this may be wrapped in a
4860 1-element tuple.
4862 .. versionchanged:: 1.13.0
4863 Tuples are allowed for keyword argument.
4865 Returns
4866 -------
4867 r : ndarray
4868 The accumulated values. If `out` was supplied, `r` is a reference to
4869 `out`.
4871 Examples
4872 --------
4873 1-D array examples:
4875 >>> np.add.accumulate([2, 3, 5])
4876 array([ 2, 5, 10])
4877 >>> np.multiply.accumulate([2, 3, 5])
4878 array([ 2, 6, 30])
4880 2-D array examples:
4882 >>> I = np.eye(2)
4883 >>> I
4884 array([[1., 0.],
4885 [0., 1.]])
4887 Accumulate along axis 0 (rows), down columns:
4889 >>> np.add.accumulate(I, 0)
4890 array([[1., 0.],
4891 [1., 1.]])
4892 >>> np.add.accumulate(I) # no axis specified = axis zero
4893 array([[1., 0.],
4894 [1., 1.]])
4896 Accumulate along axis 1 (columns), through rows:
4898 >>> np.add.accumulate(I, 1)
4899 array([[1., 1.],
4900 [0., 1.]])
4902 """))
4904add_newdoc('numpy.core', 'ufunc', ('reduceat',
4905 """
4906 reduceat(a, indices, axis=0, dtype=None, out=None)
4908 Performs a (local) reduce with specified slices over a single axis.
4910 For i in ``range(len(indices))``, `reduceat` computes
4911 ``ufunc.reduce(a[indices[i]:indices[i+1]])``, which becomes the i-th
4912 generalized "row" parallel to `axis` in the final result (i.e., in a
4913 2-D array, for example, if `axis = 0`, it becomes the i-th row, but if
4914 `axis = 1`, it becomes the i-th column). There are three exceptions to this:
4916 * when ``i = len(indices) - 1`` (so for the last index),
4917 ``indices[i+1] = a.shape[axis]``.
4918 * if ``indices[i] >= indices[i + 1]``, the i-th generalized "row" is
4919 simply ``a[indices[i]]``.
4920 * if ``indices[i] >= len(a)`` or ``indices[i] < 0``, an error is raised.
4922 The shape of the output depends on the size of `indices`, and may be
4923 larger than `a` (this happens if ``len(indices) > a.shape[axis]``).
4925 Parameters
4926 ----------
4927 a : array_like
4928 The array to act on.
4929 indices : array_like
4930 Paired indices, comma separated (not colon), specifying slices to
4931 reduce.
4932 axis : int, optional
4933 The axis along which to apply the reduceat.
4934 dtype : data-type code, optional
4935 The type used to represent the intermediate results. Defaults
4936 to the data type of the output array if this is provided, or
4937 the data type of the input array if no output array is provided.
4938 out : ndarray, None, or tuple of ndarray and None, optional
4939 A location into which the result is stored. If not provided or None,
4940 a freshly-allocated array is returned. For consistency with
4941 ``ufunc.__call__``, if given as a keyword, this may be wrapped in a
4942 1-element tuple.
4944 .. versionchanged:: 1.13.0
4945 Tuples are allowed for keyword argument.
4947 Returns
4948 -------
4949 r : ndarray
4950 The reduced values. If `out` was supplied, `r` is a reference to
4951 `out`.
4953 Notes
4954 -----
4955 A descriptive example:
4957 If `a` is 1-D, the function `ufunc.accumulate(a)` is the same as
4958 ``ufunc.reduceat(a, indices)[::2]`` where `indices` is
4959 ``range(len(array) - 1)`` with a zero placed
4960 in every other element:
4961 ``indices = zeros(2 * len(a) - 1)``, ``indices[1::2] = range(1, len(a))``.
4963 Don't be fooled by this attribute's name: `reduceat(a)` is not
4964 necessarily smaller than `a`.
4966 Examples
4967 --------
4968 To take the running sum of four successive values:
4970 >>> np.add.reduceat(np.arange(8),[0,4, 1,5, 2,6, 3,7])[::2]
4971 array([ 6, 10, 14, 18])
4973 A 2-D example:
4975 >>> x = np.linspace(0, 15, 16).reshape(4,4)
4976 >>> x
4977 array([[ 0., 1., 2., 3.],
4978 [ 4., 5., 6., 7.],
4979 [ 8., 9., 10., 11.],
4980 [12., 13., 14., 15.]])
4982 ::
4984 # reduce such that the result has the following five rows:
4985 # [row1 + row2 + row3]
4986 # [row4]
4987 # [row2]
4988 # [row3]
4989 # [row1 + row2 + row3 + row4]
4991 >>> np.add.reduceat(x, [0, 3, 1, 2, 0])
4992 array([[12., 15., 18., 21.],
4993 [12., 13., 14., 15.],
4994 [ 4., 5., 6., 7.],
4995 [ 8., 9., 10., 11.],
4996 [24., 28., 32., 36.]])
4998 ::
5000 # reduce such that result has the following two columns:
5001 # [col1 * col2 * col3, col4]
5003 >>> np.multiply.reduceat(x, [0, 3], 1)
5004 array([[ 0., 3.],
5005 [ 120., 7.],
5006 [ 720., 11.],
5007 [2184., 15.]])
5009 """))
5011add_newdoc('numpy.core', 'ufunc', ('outer',
5012 r"""
5013 outer(A, B, **kwargs)
5015 Apply the ufunc `op` to all pairs (a, b) with a in `A` and b in `B`.
5017 Let ``M = A.ndim``, ``N = B.ndim``. Then the result, `C`, of
5018 ``op.outer(A, B)`` is an array of dimension M + N such that:
5020 .. math:: C[i_0, ..., i_{M-1}, j_0, ..., j_{N-1}] =
5021 op(A[i_0, ..., i_{M-1}], B[j_0, ..., j_{N-1}])
5023 For `A` and `B` one-dimensional, this is equivalent to::
5025 r = empty(len(A),len(B))
5026 for i in range(len(A)):
5027 for j in range(len(B)):
5028 r[i,j] = op(A[i], B[j]) # op = ufunc in question
5030 Parameters
5031 ----------
5032 A : array_like
5033 First array
5034 B : array_like
5035 Second array
5036 kwargs : any
5037 Arguments to pass on to the ufunc. Typically `dtype` or `out`.
5039 Returns
5040 -------
5041 r : ndarray
5042 Output array
5044 See Also
5045 --------
5046 numpy.outer : A less powerful version of ``np.multiply.outer``
5047 that `ravel`\ s all inputs to 1D. This exists
5048 primarily for compatibility with old code.
5050 tensordot : ``np.tensordot(a, b, axes=((), ()))`` and
5051 ``np.multiply.outer(a, b)`` behave same for all
5052 dimensions of a and b.
5054 Examples
5055 --------
5056 >>> np.multiply.outer([1, 2, 3], [4, 5, 6])
5057 array([[ 4, 5, 6],
5058 [ 8, 10, 12],
5059 [12, 15, 18]])
5061 A multi-dimensional example:
5063 >>> A = np.array([[1, 2, 3], [4, 5, 6]])
5064 >>> A.shape
5065 (2, 3)
5066 >>> B = np.array([[1, 2, 3, 4]])
5067 >>> B.shape
5068 (1, 4)
5069 >>> C = np.multiply.outer(A, B)
5070 >>> C.shape; C
5071 (2, 3, 1, 4)
5072 array([[[[ 1, 2, 3, 4]],
5073 [[ 2, 4, 6, 8]],
5074 [[ 3, 6, 9, 12]]],
5075 [[[ 4, 8, 12, 16]],
5076 [[ 5, 10, 15, 20]],
5077 [[ 6, 12, 18, 24]]]])
5079 """))
5081add_newdoc('numpy.core', 'ufunc', ('at',
5082 """
5083 at(a, indices, b=None)
5085 Performs unbuffered in place operation on operand 'a' for elements
5086 specified by 'indices'. For addition ufunc, this method is equivalent to
5087 ``a[indices] += b``, except that results are accumulated for elements that
5088 are indexed more than once. For example, ``a[[0,0]] += 1`` will only
5089 increment the first element once because of buffering, whereas
5090 ``add.at(a, [0,0], 1)`` will increment the first element twice.
5092 .. versionadded:: 1.8.0
5094 Parameters
5095 ----------
5096 a : array_like
5097 The array to perform in place operation on.
5098 indices : array_like or tuple
5099 Array like index object or slice object for indexing into first
5100 operand. If first operand has multiple dimensions, indices can be a
5101 tuple of array like index objects or slice objects.
5102 b : array_like
5103 Second operand for ufuncs requiring two operands. Operand must be
5104 broadcastable over first operand after indexing or slicing.
5106 Examples
5107 --------
5108 Set items 0 and 1 to their negative values:
5110 >>> a = np.array([1, 2, 3, 4])
5111 >>> np.negative.at(a, [0, 1])
5112 >>> a
5113 array([-1, -2, 3, 4])
5115 Increment items 0 and 1, and increment item 2 twice:
5117 >>> a = np.array([1, 2, 3, 4])
5118 >>> np.add.at(a, [0, 1, 2, 2], 1)
5119 >>> a
5120 array([2, 3, 5, 4])
5122 Add items 0 and 1 in first array to second array,
5123 and store results in first array:
5125 >>> a = np.array([1, 2, 3, 4])
5126 >>> b = np.array([1, 2])
5127 >>> np.add.at(a, [0, 1], b)
5128 >>> a
5129 array([2, 4, 3, 4])
5131 """))
5133##############################################################################
5134#
5135# Documentation for dtype attributes and methods
5136#
5137##############################################################################
5139##############################################################################
5140#
5141# dtype object
5142#
5143##############################################################################
5145add_newdoc('numpy.core.multiarray', 'dtype',
5146 """
5147 dtype(obj, align=False, copy=False)
5149 Create a data type object.
5151 A numpy array is homogeneous, and contains elements described by a
5152 dtype object. A dtype object can be constructed from different
5153 combinations of fundamental numeric types.
5155 Parameters
5156 ----------
5157 obj
5158 Object to be converted to a data type object.
5159 align : bool, optional
5160 Add padding to the fields to match what a C compiler would output
5161 for a similar C-struct. Can be ``True`` only if `obj` is a dictionary
5162 or a comma-separated string. If a struct dtype is being created,
5163 this also sets a sticky alignment flag ``isalignedstruct``.
5164 copy : bool, optional
5165 Make a new copy of the data-type object. If ``False``, the result
5166 may just be a reference to a built-in data-type object.
5168 See also
5169 --------
5170 result_type
5172 Examples
5173 --------
5174 Using array-scalar type:
5176 >>> np.dtype(np.int16)
5177 dtype('int16')
5179 Structured type, one field name 'f1', containing int16:
5181 >>> np.dtype([('f1', np.int16)])
5182 dtype([('f1', '<i2')])
5184 Structured type, one field named 'f1', in itself containing a structured
5185 type with one field:
5187 >>> np.dtype([('f1', [('f1', np.int16)])])
5188 dtype([('f1', [('f1', '<i2')])])
5190 Structured type, two fields: the first field contains an unsigned int, the
5191 second an int32:
5193 >>> np.dtype([('f1', np.uint64), ('f2', np.int32)])
5194 dtype([('f1', '<u8'), ('f2', '<i4')])
5196 Using array-protocol type strings:
5198 >>> np.dtype([('a','f8'),('b','S10')])
5199 dtype([('a', '<f8'), ('b', 'S10')])
5201 Using comma-separated field formats. The shape is (2,3):
5203 >>> np.dtype("i4, (2,3)f8")
5204 dtype([('f0', '<i4'), ('f1', '<f8', (2, 3))])
5206 Using tuples. ``int`` is a fixed type, 3 the field's shape. ``void``
5207 is a flexible type, here of size 10:
5209 >>> np.dtype([('hello',(np.int64,3)),('world',np.void,10)])
5210 dtype([('hello', '<i8', (3,)), ('world', 'V10')])
5212 Subdivide ``int16`` into 2 ``int8``'s, called x and y. 0 and 1 are
5213 the offsets in bytes:
5215 >>> np.dtype((np.int16, {'x':(np.int8,0), 'y':(np.int8,1)}))
5216 dtype((numpy.int16, [('x', 'i1'), ('y', 'i1')]))
5218 Using dictionaries. Two fields named 'gender' and 'age':
5220 >>> np.dtype({'names':['gender','age'], 'formats':['S1',np.uint8]})
5221 dtype([('gender', 'S1'), ('age', 'u1')])
5223 Offsets in bytes, here 0 and 25:
5225 >>> np.dtype({'surname':('S25',0),'age':(np.uint8,25)})
5226 dtype([('surname', 'S25'), ('age', 'u1')])
5228 """)
5230##############################################################################
5231#
5232# dtype attributes
5233#
5234##############################################################################
5236add_newdoc('numpy.core.multiarray', 'dtype', ('alignment',
5237 """
5238 The required alignment (bytes) of this data-type according to the compiler.
5240 More information is available in the C-API section of the manual.
5242 Examples
5243 --------
5245 >>> x = np.dtype('i4')
5246 >>> x.alignment
5247 4
5249 >>> x = np.dtype(float)
5250 >>> x.alignment
5251 8
5253 """))
5255add_newdoc('numpy.core.multiarray', 'dtype', ('byteorder',
5256 """
5257 A character indicating the byte-order of this data-type object.
5259 One of:
5261 === ==============
5262 '=' native
5263 '<' little-endian
5264 '>' big-endian
5265 '|' not applicable
5266 === ==============
5268 All built-in data-type objects have byteorder either '=' or '|'.
5270 Examples
5271 --------
5273 >>> dt = np.dtype('i2')
5274 >>> dt.byteorder
5275 '='
5276 >>> # endian is not relevant for 8 bit numbers
5277 >>> np.dtype('i1').byteorder
5278 '|'
5279 >>> # or ASCII strings
5280 >>> np.dtype('S2').byteorder
5281 '|'
5282 >>> # Even if specific code is given, and it is native
5283 >>> # '=' is the byteorder
5284 >>> import sys
5285 >>> sys_is_le = sys.byteorder == 'little'
5286 >>> native_code = sys_is_le and '<' or '>'
5287 >>> swapped_code = sys_is_le and '>' or '<'
5288 >>> dt = np.dtype(native_code + 'i2')
5289 >>> dt.byteorder
5290 '='
5291 >>> # Swapped code shows up as itself
5292 >>> dt = np.dtype(swapped_code + 'i2')
5293 >>> dt.byteorder == swapped_code
5294 True
5296 """))
5298add_newdoc('numpy.core.multiarray', 'dtype', ('char',
5299 """A unique character code for each of the 21 different built-in types.
5301 Examples
5302 --------
5304 >>> x = np.dtype(float)
5305 >>> x.char
5306 'd'
5308 """))
5310add_newdoc('numpy.core.multiarray', 'dtype', ('descr',
5311 """
5312 `__array_interface__` description of the data-type.
5314 The format is that required by the 'descr' key in the
5315 `__array_interface__` attribute.
5317 Warning: This attribute exists specifically for `__array_interface__`,
5318 and passing it directly to `np.dtype` will not accurately reconstruct
5319 some dtypes (e.g., scalar and subarray dtypes).
5321 Examples
5322 --------
5324 >>> x = np.dtype(float)
5325 >>> x.descr
5326 [('', '<f8')]
5328 >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
5329 >>> dt.descr
5330 [('name', '<U16'), ('grades', '<f8', (2,))]
5332 """))
5334add_newdoc('numpy.core.multiarray', 'dtype', ('fields',
5335 """
5336 Dictionary of named fields defined for this data type, or ``None``.
5338 The dictionary is indexed by keys that are the names of the fields.
5339 Each entry in the dictionary is a tuple fully describing the field::
5341 (dtype, offset[, title])
5343 Offset is limited to C int, which is signed and usually 32 bits.
5344 If present, the optional title can be any object (if it is a string
5345 or unicode then it will also be a key in the fields dictionary,
5346 otherwise it's meta-data). Notice also that the first two elements
5347 of the tuple can be passed directly as arguments to the ``ndarray.getfield``
5348 and ``ndarray.setfield`` methods.
5350 See Also
5351 --------
5352 ndarray.getfield, ndarray.setfield
5354 Examples
5355 --------
5356 >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
5357 >>> print(dt.fields)
5358 {'grades': (dtype(('float64',(2,))), 16), 'name': (dtype('|S16'), 0)}
5360 """))
5362add_newdoc('numpy.core.multiarray', 'dtype', ('flags',
5363 """
5364 Bit-flags describing how this data type is to be interpreted.
5366 Bit-masks are in `numpy.core.multiarray` as the constants
5367 `ITEM_HASOBJECT`, `LIST_PICKLE`, `ITEM_IS_POINTER`, `NEEDS_INIT`,
5368 `NEEDS_PYAPI`, `USE_GETITEM`, `USE_SETITEM`. A full explanation
5369 of these flags is in C-API documentation; they are largely useful
5370 for user-defined data-types.
5372 The following example demonstrates that operations on this particular
5373 dtype requires Python C-API.
5375 Examples
5376 --------
5378 >>> x = np.dtype([('a', np.int32, 8), ('b', np.float64, 6)])
5379 >>> x.flags
5380 16
5381 >>> np.core.multiarray.NEEDS_PYAPI
5382 16
5384 """))
5386add_newdoc('numpy.core.multiarray', 'dtype', ('hasobject',
5387 """
5388 Boolean indicating whether this dtype contains any reference-counted
5389 objects in any fields or sub-dtypes.
5391 Recall that what is actually in the ndarray memory representing
5392 the Python object is the memory address of that object (a pointer).
5393 Special handling may be required, and this attribute is useful for
5394 distinguishing data types that may contain arbitrary Python objects
5395 and data-types that won't.
5397 """))
5399add_newdoc('numpy.core.multiarray', 'dtype', ('isbuiltin',
5400 """
5401 Integer indicating how this dtype relates to the built-in dtypes.
5403 Read-only.
5405 = ========================================================================
5406 0 if this is a structured array type, with fields
5407 1 if this is a dtype compiled into numpy (such as ints, floats etc)
5408 2 if the dtype is for a user-defined numpy type
5409 A user-defined type uses the numpy C-API machinery to extend
5410 numpy to handle a new array type. See
5411 :ref:`user.user-defined-data-types` in the NumPy manual.
5412 = ========================================================================
5414 Examples
5415 --------
5416 >>> dt = np.dtype('i2')
5417 >>> dt.isbuiltin
5418 1
5419 >>> dt = np.dtype('f8')
5420 >>> dt.isbuiltin
5421 1
5422 >>> dt = np.dtype([('field1', 'f8')])
5423 >>> dt.isbuiltin
5424 0
5426 """))
5428add_newdoc('numpy.core.multiarray', 'dtype', ('isnative',
5429 """
5430 Boolean indicating whether the byte order of this dtype is native
5431 to the platform.
5433 """))
5435add_newdoc('numpy.core.multiarray', 'dtype', ('isalignedstruct',
5436 """
5437 Boolean indicating whether the dtype is a struct which maintains
5438 field alignment. This flag is sticky, so when combining multiple
5439 structs together, it is preserved and produces new dtypes which
5440 are also aligned.
5442 """))
5444add_newdoc('numpy.core.multiarray', 'dtype', ('itemsize',
5445 """
5446 The element size of this data-type object.
5448 For 18 of the 21 types this number is fixed by the data-type.
5449 For the flexible data-types, this number can be anything.
5451 Examples
5452 --------
5454 >>> arr = np.array([[1, 2], [3, 4]])
5455 >>> arr.dtype
5456 dtype('int64')
5457 >>> arr.itemsize
5458 8
5460 >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
5461 >>> dt.itemsize
5462 80
5464 """))
5466add_newdoc('numpy.core.multiarray', 'dtype', ('kind',
5467 """
5468 A character code (one of 'biufcmMOSUV') identifying the general kind of data.
5470 = ======================
5471 b boolean
5472 i signed integer
5473 u unsigned integer
5474 f floating-point
5475 c complex floating-point
5476 m timedelta
5477 M datetime
5478 O object
5479 S (byte-)string
5480 U Unicode
5481 V void
5482 = ======================
5484 Examples
5485 --------
5487 >>> dt = np.dtype('i4')
5488 >>> dt.kind
5489 'i'
5490 >>> dt = np.dtype('f8')
5491 >>> dt.kind
5492 'f'
5493 >>> dt = np.dtype([('field1', 'f8')])
5494 >>> dt.kind
5495 'V'
5497 """))
5499add_newdoc('numpy.core.multiarray', 'dtype', ('name',
5500 """
5501 A bit-width name for this data-type.
5503 Un-sized flexible data-type objects do not have this attribute.
5505 Examples
5506 --------
5508 >>> x = np.dtype(float)
5509 >>> x.name
5510 'float64'
5511 >>> x = np.dtype([('a', np.int32, 8), ('b', np.float64, 6)])
5512 >>> x.name
5513 'void640'
5515 """))
5517add_newdoc('numpy.core.multiarray', 'dtype', ('names',
5518 """
5519 Ordered list of field names, or ``None`` if there are no fields.
5521 The names are ordered according to increasing byte offset. This can be
5522 used, for example, to walk through all of the named fields in offset order.
5524 Examples
5525 --------
5526 >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
5527 >>> dt.names
5528 ('name', 'grades')
5530 """))
5532add_newdoc('numpy.core.multiarray', 'dtype', ('num',
5533 """
5534 A unique number for each of the 21 different built-in types.
5536 These are roughly ordered from least-to-most precision.
5538 Examples
5539 --------
5541 >>> dt = np.dtype(str)
5542 >>> dt.num
5543 19
5545 >>> dt = np.dtype(float)
5546 >>> dt.num
5547 12
5549 """))
5551add_newdoc('numpy.core.multiarray', 'dtype', ('shape',
5552 """
5553 Shape tuple of the sub-array if this data type describes a sub-array,
5554 and ``()`` otherwise.
5556 Examples
5557 --------
5559 >>> dt = np.dtype(('i4', 4))
5560 >>> dt.shape
5561 (4,)
5563 >>> dt = np.dtype(('i4', (2, 3)))
5564 >>> dt.shape
5565 (2, 3)
5567 """))
5569add_newdoc('numpy.core.multiarray', 'dtype', ('ndim',
5570 """
5571 Number of dimensions of the sub-array if this data type describes a
5572 sub-array, and ``0`` otherwise.
5574 .. versionadded:: 1.13.0
5576 Examples
5577 --------
5578 >>> x = np.dtype(float)
5579 >>> x.ndim
5580 0
5582 >>> x = np.dtype((float, 8))
5583 >>> x.ndim
5584 1
5586 >>> x = np.dtype(('i4', (3, 4)))
5587 >>> x.ndim
5588 2
5590 """))
5592add_newdoc('numpy.core.multiarray', 'dtype', ('str',
5593 """The array-protocol typestring of this data-type object."""))
5595add_newdoc('numpy.core.multiarray', 'dtype', ('subdtype',
5596 """
5597 Tuple ``(item_dtype, shape)`` if this `dtype` describes a sub-array, and
5598 None otherwise.
5600 The *shape* is the fixed shape of the sub-array described by this
5601 data type, and *item_dtype* the data type of the array.
5603 If a field whose dtype object has this attribute is retrieved,
5604 then the extra dimensions implied by *shape* are tacked on to
5605 the end of the retrieved array.
5607 See Also
5608 --------
5609 dtype.base
5611 Examples
5612 --------
5613 >>> x = numpy.dtype('8f')
5614 >>> x.subdtype
5615 (dtype('float32'), (8,))
5617 >>> x = numpy.dtype('i2')
5618 >>> x.subdtype
5619 >>>
5621 """))
5623add_newdoc('numpy.core.multiarray', 'dtype', ('base',
5624 """
5625 Returns dtype for the base element of the subarrays,
5626 regardless of their dimension or shape.
5628 See Also
5629 --------
5630 dtype.subdtype
5632 Examples
5633 --------
5634 >>> x = numpy.dtype('8f')
5635 >>> x.base
5636 dtype('float32')
5638 >>> x = numpy.dtype('i2')
5639 >>> x.base
5640 dtype('int16')
5642 """))
5644add_newdoc('numpy.core.multiarray', 'dtype', ('type',
5645 """The type object used to instantiate a scalar of this data-type."""))
5647##############################################################################
5648#
5649# dtype methods
5650#
5651##############################################################################
5653add_newdoc('numpy.core.multiarray', 'dtype', ('newbyteorder',
5654 """
5655 newbyteorder(new_order='S')
5657 Return a new dtype with a different byte order.
5659 Changes are also made in all fields and sub-arrays of the data type.
5661 Parameters
5662 ----------
5663 new_order : string, optional
5664 Byte order to force; a value from the byte order specifications
5665 below. The default value ('S') results in swapping the current
5666 byte order. `new_order` codes can be any of:
5668 * 'S' - swap dtype from current to opposite endian
5669 * {'<', 'L'} - little endian
5670 * {'>', 'B'} - big endian
5671 * {'=', 'N'} - native order
5672 * {'|', 'I'} - ignore (no change to byte order)
5674 The code does a case-insensitive check on the first letter of
5675 `new_order` for these alternatives. For example, any of '>'
5676 or 'B' or 'b' or 'brian' are valid to specify big-endian.
5678 Returns
5679 -------
5680 new_dtype : dtype
5681 New dtype object with the given change to the byte order.
5683 Notes
5684 -----
5685 Changes are also made in all fields and sub-arrays of the data type.
5687 Examples
5688 --------
5689 >>> import sys
5690 >>> sys_is_le = sys.byteorder == 'little'
5691 >>> native_code = sys_is_le and '<' or '>'
5692 >>> swapped_code = sys_is_le and '>' or '<'
5693 >>> native_dt = np.dtype(native_code+'i2')
5694 >>> swapped_dt = np.dtype(swapped_code+'i2')
5695 >>> native_dt.newbyteorder('S') == swapped_dt
5696 True
5697 >>> native_dt.newbyteorder() == swapped_dt
5698 True
5699 >>> native_dt == swapped_dt.newbyteorder('S')
5700 True
5701 >>> native_dt == swapped_dt.newbyteorder('=')
5702 True
5703 >>> native_dt == swapped_dt.newbyteorder('N')
5704 True
5705 >>> native_dt == native_dt.newbyteorder('|')
5706 True
5707 >>> np.dtype('<i2') == native_dt.newbyteorder('<')
5708 True
5709 >>> np.dtype('<i2') == native_dt.newbyteorder('L')
5710 True
5711 >>> np.dtype('>i2') == native_dt.newbyteorder('>')
5712 True
5713 >>> np.dtype('>i2') == native_dt.newbyteorder('B')
5714 True
5716 """))
5719##############################################################################
5720#
5721# Datetime-related Methods
5722#
5723##############################################################################
5725add_newdoc('numpy.core.multiarray', 'busdaycalendar',
5726 """
5727 busdaycalendar(weekmask='1111100', holidays=None)
5729 A business day calendar object that efficiently stores information
5730 defining valid days for the busday family of functions.
5732 The default valid days are Monday through Friday ("business days").
5733 A busdaycalendar object can be specified with any set of weekly
5734 valid days, plus an optional "holiday" dates that always will be invalid.
5736 Once a busdaycalendar object is created, the weekmask and holidays
5737 cannot be modified.
5739 .. versionadded:: 1.7.0
5741 Parameters
5742 ----------
5743 weekmask : str or array_like of bool, optional
5744 A seven-element array indicating which of Monday through Sunday are
5745 valid days. May be specified as a length-seven list or array, like
5746 [1,1,1,1,1,0,0]; a length-seven string, like '1111100'; or a string
5747 like "Mon Tue Wed Thu Fri", made up of 3-character abbreviations for
5748 weekdays, optionally separated by white space. Valid abbreviations
5749 are: Mon Tue Wed Thu Fri Sat Sun
5750 holidays : array_like of datetime64[D], optional
5751 An array of dates to consider as invalid dates, no matter which
5752 weekday they fall upon. Holiday dates may be specified in any
5753 order, and NaT (not-a-time) dates are ignored. This list is
5754 saved in a normalized form that is suited for fast calculations
5755 of valid days.
5757 Returns
5758 -------
5759 out : busdaycalendar
5760 A business day calendar object containing the specified
5761 weekmask and holidays values.
5763 See Also
5764 --------
5765 is_busday : Returns a boolean array indicating valid days.
5766 busday_offset : Applies an offset counted in valid days.
5767 busday_count : Counts how many valid days are in a half-open date range.
5769 Attributes
5770 ----------
5771 Note: once a busdaycalendar object is created, you cannot modify the
5772 weekmask or holidays. The attributes return copies of internal data.
5773 weekmask : (copy) seven-element array of bool
5774 holidays : (copy) sorted array of datetime64[D]
5776 Examples
5777 --------
5778 >>> # Some important days in July
5779 ... bdd = np.busdaycalendar(
5780 ... holidays=['2011-07-01', '2011-07-04', '2011-07-17'])
5781 >>> # Default is Monday to Friday weekdays
5782 ... bdd.weekmask
5783 array([ True, True, True, True, True, False, False])
5784 >>> # Any holidays already on the weekend are removed
5785 ... bdd.holidays
5786 array(['2011-07-01', '2011-07-04'], dtype='datetime64[D]')
5787 """)
5789add_newdoc('numpy.core.multiarray', 'busdaycalendar', ('weekmask',
5790 """A copy of the seven-element boolean mask indicating valid days."""))
5792add_newdoc('numpy.core.multiarray', 'busdaycalendar', ('holidays',
5793 """A copy of the holiday array indicating additional invalid days."""))
5795add_newdoc('numpy.core.multiarray', 'normalize_axis_index',
5796 """
5797 normalize_axis_index(axis, ndim, msg_prefix=None)
5799 Normalizes an axis index, `axis`, such that is a valid positive index into
5800 the shape of array with `ndim` dimensions. Raises an AxisError with an
5801 appropriate message if this is not possible.
5803 Used internally by all axis-checking logic.
5805 .. versionadded:: 1.13.0
5807 Parameters
5808 ----------
5809 axis : int
5810 The un-normalized index of the axis. Can be negative
5811 ndim : int
5812 The number of dimensions of the array that `axis` should be normalized
5813 against
5814 msg_prefix : str
5815 A prefix to put before the message, typically the name of the argument
5817 Returns
5818 -------
5819 normalized_axis : int
5820 The normalized axis index, such that `0 <= normalized_axis < ndim`
5822 Raises
5823 ------
5824 AxisError
5825 If the axis index is invalid, when `-ndim <= axis < ndim` is false.
5827 Examples
5828 --------
5829 >>> normalize_axis_index(0, ndim=3)
5830 0
5831 >>> normalize_axis_index(1, ndim=3)
5832 1
5833 >>> normalize_axis_index(-1, ndim=3)
5834 2
5836 >>> normalize_axis_index(3, ndim=3)
5837 Traceback (most recent call last):
5838 ...
5839 AxisError: axis 3 is out of bounds for array of dimension 3
5840 >>> normalize_axis_index(-4, ndim=3, msg_prefix='axes_arg')
5841 Traceback (most recent call last):
5842 ...
5843 AxisError: axes_arg: axis -4 is out of bounds for array of dimension 3
5844 """)
5846add_newdoc('numpy.core.multiarray', 'datetime_data',
5847 """
5848 datetime_data(dtype, /)
5850 Get information about the step size of a date or time type.
5852 The returned tuple can be passed as the second argument of `numpy.datetime64` and
5853 `numpy.timedelta64`.
5855 Parameters
5856 ----------
5857 dtype : dtype
5858 The dtype object, which must be a `datetime64` or `timedelta64` type.
5860 Returns
5861 -------
5862 unit : str
5863 The :ref:`datetime unit <arrays.dtypes.dateunits>` on which this dtype
5864 is based.
5865 count : int
5866 The number of base units in a step.
5868 Examples
5869 --------
5870 >>> dt_25s = np.dtype('timedelta64[25s]')
5871 >>> np.datetime_data(dt_25s)
5872 ('s', 25)
5873 >>> np.array(10, dt_25s).astype('timedelta64[s]')
5874 array(250, dtype='timedelta64[s]')
5876 The result can be used to construct a datetime that uses the same units
5877 as a timedelta
5879 >>> np.datetime64('2010', np.datetime_data(dt_25s))
5880 numpy.datetime64('2010-01-01T00:00:00','25s')
5881 """)
5884##############################################################################
5885#
5886# Documentation for `generic` attributes and methods
5887#
5888##############################################################################
5890add_newdoc('numpy.core.numerictypes', 'generic',
5891 """
5892 Base class for numpy scalar types.
5894 Class from which most (all?) numpy scalar types are derived. For
5895 consistency, exposes the same API as `ndarray`, despite many
5896 consequent attributes being either "get-only," or completely irrelevant.
5897 This is the class from which it is strongly suggested users should derive
5898 custom scalar types.
5900 """)
5902# Attributes
5904add_newdoc('numpy.core.numerictypes', 'generic', ('T',
5905 """
5906 Not implemented (virtual attribute)
5908 Class generic exists solely to derive numpy scalars from, and possesses,
5909 albeit unimplemented, all the attributes of the ndarray class so as to
5910 provide a uniform API.
5912 See also the corresponding attribute of the derived class of interest.
5914 """))
5916add_newdoc('numpy.core.numerictypes', 'generic', ('base',
5917 """
5918 Not implemented (virtual attribute)
5920 Class generic exists solely to derive numpy scalars from, and possesses,
5921 albeit unimplemented, all the attributes of the ndarray class so as to
5922 a uniform API.
5924 See also the corresponding attribute of the derived class of interest.
5926 """))
5928add_newdoc('numpy.core.numerictypes', 'generic', ('data',
5929 """Pointer to start of data."""))
5931add_newdoc('numpy.core.numerictypes', 'generic', ('dtype',
5932 """Get array data-descriptor."""))
5934add_newdoc('numpy.core.numerictypes', 'generic', ('flags',
5935 """The integer value of flags."""))
5937add_newdoc('numpy.core.numerictypes', 'generic', ('flat',
5938 """A 1-D view of the scalar."""))
5940add_newdoc('numpy.core.numerictypes', 'generic', ('imag',
5941 """The imaginary part of the scalar."""))
5943add_newdoc('numpy.core.numerictypes', 'generic', ('itemsize',
5944 """The length of one element in bytes."""))
5946add_newdoc('numpy.core.numerictypes', 'generic', ('nbytes',
5947 """The length of the scalar in bytes."""))
5949add_newdoc('numpy.core.numerictypes', 'generic', ('ndim',
5950 """The number of array dimensions."""))
5952add_newdoc('numpy.core.numerictypes', 'generic', ('real',
5953 """The real part of the scalar."""))
5955add_newdoc('numpy.core.numerictypes', 'generic', ('shape',
5956 """Tuple of array dimensions."""))
5958add_newdoc('numpy.core.numerictypes', 'generic', ('size',
5959 """The number of elements in the gentype."""))
5961add_newdoc('numpy.core.numerictypes', 'generic', ('strides',
5962 """Tuple of bytes steps in each dimension."""))
5964# Methods
5966add_newdoc('numpy.core.numerictypes', 'generic', ('all',
5967 """
5968 Not implemented (virtual attribute)
5970 Class generic exists solely to derive numpy scalars from, and possesses,
5971 albeit unimplemented, all the attributes of the ndarray class
5972 so as to provide a uniform API.
5974 See also the corresponding attribute of the derived class of interest.
5976 """))
5978add_newdoc('numpy.core.numerictypes', 'generic', ('any',
5979 """
5980 Not implemented (virtual attribute)
5982 Class generic exists solely to derive numpy scalars from, and possesses,
5983 albeit unimplemented, all the attributes of the ndarray class
5984 so as to provide a uniform API.
5986 See also the corresponding attribute of the derived class of interest.
5988 """))
5990add_newdoc('numpy.core.numerictypes', 'generic', ('argmax',
5991 """
5992 Not implemented (virtual attribute)
5994 Class generic exists solely to derive numpy scalars from, and possesses,
5995 albeit unimplemented, all the attributes of the ndarray class
5996 so as to provide a uniform API.
5998 See also the corresponding attribute of the derived class of interest.
6000 """))
6002add_newdoc('numpy.core.numerictypes', 'generic', ('argmin',
6003 """
6004 Not implemented (virtual attribute)
6006 Class generic exists solely to derive numpy scalars from, and possesses,
6007 albeit unimplemented, all the attributes of the ndarray class
6008 so as to provide a uniform API.
6010 See also the corresponding attribute of the derived class of interest.
6012 """))
6014add_newdoc('numpy.core.numerictypes', 'generic', ('argsort',
6015 """
6016 Not implemented (virtual attribute)
6018 Class generic exists solely to derive numpy scalars from, and possesses,
6019 albeit unimplemented, all the attributes of the ndarray class
6020 so as to provide a uniform API.
6022 See also the corresponding attribute of the derived class of interest.
6024 """))
6026add_newdoc('numpy.core.numerictypes', 'generic', ('astype',
6027 """
6028 Not implemented (virtual attribute)
6030 Class generic exists solely to derive numpy scalars from, and possesses,
6031 albeit unimplemented, all the attributes of the ndarray class
6032 so as to provide a uniform API.
6034 See also the corresponding attribute of the derived class of interest.
6036 """))
6038add_newdoc('numpy.core.numerictypes', 'generic', ('byteswap',
6039 """
6040 Not implemented (virtual attribute)
6042 Class generic exists solely to derive numpy scalars from, and possesses,
6043 albeit unimplemented, all the attributes of the ndarray class so as to
6044 provide a uniform API.
6046 See also the corresponding attribute of the derived class of interest.
6048 """))
6050add_newdoc('numpy.core.numerictypes', 'generic', ('choose',
6051 """
6052 Not implemented (virtual attribute)
6054 Class generic exists solely to derive numpy scalars from, and possesses,
6055 albeit unimplemented, all the attributes of the ndarray class
6056 so as to provide a uniform API.
6058 See also the corresponding attribute of the derived class of interest.
6060 """))
6062add_newdoc('numpy.core.numerictypes', 'generic', ('clip',
6063 """
6064 Not implemented (virtual attribute)
6066 Class generic exists solely to derive numpy scalars from, and possesses,
6067 albeit unimplemented, all the attributes of the ndarray class
6068 so as to provide a uniform API.
6070 See also the corresponding attribute of the derived class of interest.
6072 """))
6074add_newdoc('numpy.core.numerictypes', 'generic', ('compress',
6075 """
6076 Not implemented (virtual attribute)
6078 Class generic exists solely to derive numpy scalars from, and possesses,
6079 albeit unimplemented, all the attributes of the ndarray class
6080 so as to provide a uniform API.
6082 See also the corresponding attribute of the derived class of interest.
6084 """))
6086add_newdoc('numpy.core.numerictypes', 'generic', ('conjugate',
6087 """
6088 Not implemented (virtual attribute)
6090 Class generic exists solely to derive numpy scalars from, and possesses,
6091 albeit unimplemented, all the attributes of the ndarray class
6092 so as to provide a uniform API.
6094 See also the corresponding attribute of the derived class of interest.
6096 """))
6098add_newdoc('numpy.core.numerictypes', 'generic', ('copy',
6099 """
6100 Not implemented (virtual attribute)
6102 Class generic exists solely to derive numpy scalars from, and possesses,
6103 albeit unimplemented, all the attributes of the ndarray class
6104 so as to provide a uniform API.
6106 See also the corresponding attribute of the derived class of interest.
6108 """))
6110add_newdoc('numpy.core.numerictypes', 'generic', ('cumprod',
6111 """
6112 Not implemented (virtual attribute)
6114 Class generic exists solely to derive numpy scalars from, and possesses,
6115 albeit unimplemented, all the attributes of the ndarray class
6116 so as to provide a uniform API.
6118 See also the corresponding attribute of the derived class of interest.
6120 """))
6122add_newdoc('numpy.core.numerictypes', 'generic', ('cumsum',
6123 """
6124 Not implemented (virtual attribute)
6126 Class generic exists solely to derive numpy scalars from, and possesses,
6127 albeit unimplemented, all the attributes of the ndarray class
6128 so as to provide a uniform API.
6130 See also the corresponding attribute of the derived class of interest.
6132 """))
6134add_newdoc('numpy.core.numerictypes', 'generic', ('diagonal',
6135 """
6136 Not implemented (virtual attribute)
6138 Class generic exists solely to derive numpy scalars from, and possesses,
6139 albeit unimplemented, all the attributes of the ndarray class
6140 so as to provide a uniform API.
6142 See also the corresponding attribute of the derived class of interest.
6144 """))
6146add_newdoc('numpy.core.numerictypes', 'generic', ('dump',
6147 """
6148 Not implemented (virtual attribute)
6150 Class generic exists solely to derive numpy scalars from, and possesses,
6151 albeit unimplemented, all the attributes of the ndarray class
6152 so as to provide a uniform API.
6154 See also the corresponding attribute of the derived class of interest.
6156 """))
6158add_newdoc('numpy.core.numerictypes', 'generic', ('dumps',
6159 """
6160 Not implemented (virtual attribute)
6162 Class generic exists solely to derive numpy scalars from, and possesses,
6163 albeit unimplemented, all the attributes of the ndarray class
6164 so as to provide a uniform API.
6166 See also the corresponding attribute of the derived class of interest.
6168 """))
6170add_newdoc('numpy.core.numerictypes', 'generic', ('fill',
6171 """
6172 Not implemented (virtual attribute)
6174 Class generic exists solely to derive numpy scalars from, and possesses,
6175 albeit unimplemented, all the attributes of the ndarray class
6176 so as to provide a uniform API.
6178 See also the corresponding attribute of the derived class of interest.
6180 """))
6182add_newdoc('numpy.core.numerictypes', 'generic', ('flatten',
6183 """
6184 Not implemented (virtual attribute)
6186 Class generic exists solely to derive numpy scalars from, and possesses,
6187 albeit unimplemented, all the attributes of the ndarray class
6188 so as to provide a uniform API.
6190 See also the corresponding attribute of the derived class of interest.
6192 """))
6194add_newdoc('numpy.core.numerictypes', 'generic', ('getfield',
6195 """
6196 Not implemented (virtual attribute)
6198 Class generic exists solely to derive numpy scalars from, and possesses,
6199 albeit unimplemented, all the attributes of the ndarray class
6200 so as to provide a uniform API.
6202 See also the corresponding attribute of the derived class of interest.
6204 """))
6206add_newdoc('numpy.core.numerictypes', 'generic', ('item',
6207 """
6208 Not implemented (virtual attribute)
6210 Class generic exists solely to derive numpy scalars from, and possesses,
6211 albeit unimplemented, all the attributes of the ndarray class
6212 so as to provide a uniform API.
6214 See also the corresponding attribute of the derived class of interest.
6216 """))
6218add_newdoc('numpy.core.numerictypes', 'generic', ('itemset',
6219 """
6220 Not implemented (virtual attribute)
6222 Class generic exists solely to derive numpy scalars from, and possesses,
6223 albeit unimplemented, all the attributes of the ndarray class
6224 so as to provide a uniform API.
6226 See also the corresponding attribute of the derived class of interest.
6228 """))
6230add_newdoc('numpy.core.numerictypes', 'generic', ('max',
6231 """
6232 Not implemented (virtual attribute)
6234 Class generic exists solely to derive numpy scalars from, and possesses,
6235 albeit unimplemented, all the attributes of the ndarray class
6236 so as to provide a uniform API.
6238 See also the corresponding attribute of the derived class of interest.
6240 """))
6242add_newdoc('numpy.core.numerictypes', 'generic', ('mean',
6243 """
6244 Not implemented (virtual attribute)
6246 Class generic exists solely to derive numpy scalars from, and possesses,
6247 albeit unimplemented, all the attributes of the ndarray class
6248 so as to provide a uniform API.
6250 See also the corresponding attribute of the derived class of interest.
6252 """))
6254add_newdoc('numpy.core.numerictypes', 'generic', ('min',
6255 """
6256 Not implemented (virtual attribute)
6258 Class generic exists solely to derive numpy scalars from, and possesses,
6259 albeit unimplemented, all the attributes of the ndarray class
6260 so as to provide a uniform API.
6262 See also the corresponding attribute of the derived class of interest.
6264 """))
6266add_newdoc('numpy.core.numerictypes', 'generic', ('newbyteorder',
6267 """
6268 newbyteorder(new_order='S')
6270 Return a new `dtype` with a different byte order.
6272 Changes are also made in all fields and sub-arrays of the data type.
6274 The `new_order` code can be any from the following:
6276 * 'S' - swap dtype from current to opposite endian
6277 * {'<', 'L'} - little endian
6278 * {'>', 'B'} - big endian
6279 * {'=', 'N'} - native order
6280 * {'|', 'I'} - ignore (no change to byte order)
6282 Parameters
6283 ----------
6284 new_order : str, optional
6285 Byte order to force; a value from the byte order specifications
6286 above. The default value ('S') results in swapping the current
6287 byte order. The code does a case-insensitive check on the first
6288 letter of `new_order` for the alternatives above. For example,
6289 any of 'B' or 'b' or 'biggish' are valid to specify big-endian.
6292 Returns
6293 -------
6294 new_dtype : dtype
6295 New `dtype` object with the given change to the byte order.
6297 """))
6299add_newdoc('numpy.core.numerictypes', 'generic', ('nonzero',
6300 """
6301 Not implemented (virtual attribute)
6303 Class generic exists solely to derive numpy scalars from, and possesses,
6304 albeit unimplemented, all the attributes of the ndarray class
6305 so as to provide a uniform API.
6307 See also the corresponding attribute of the derived class of interest.
6309 """))
6311add_newdoc('numpy.core.numerictypes', 'generic', ('prod',
6312 """
6313 Not implemented (virtual attribute)
6315 Class generic exists solely to derive numpy scalars from, and possesses,
6316 albeit unimplemented, all the attributes of the ndarray class
6317 so as to provide a uniform API.
6319 See also the corresponding attribute of the derived class of interest.
6321 """))
6323add_newdoc('numpy.core.numerictypes', 'generic', ('ptp',
6324 """
6325 Not implemented (virtual attribute)
6327 Class generic exists solely to derive numpy scalars from, and possesses,
6328 albeit unimplemented, all the attributes of the ndarray class
6329 so as to provide a uniform API.
6331 See also the corresponding attribute of the derived class of interest.
6333 """))
6335add_newdoc('numpy.core.numerictypes', 'generic', ('put',
6336 """
6337 Not implemented (virtual attribute)
6339 Class generic exists solely to derive numpy scalars from, and possesses,
6340 albeit unimplemented, all the attributes of the ndarray class
6341 so as to provide a uniform API.
6343 See also the corresponding attribute of the derived class of interest.
6345 """))
6347add_newdoc('numpy.core.numerictypes', 'generic', ('ravel',
6348 """
6349 Not implemented (virtual attribute)
6351 Class generic exists solely to derive numpy scalars from, and possesses,
6352 albeit unimplemented, all the attributes of the ndarray class
6353 so as to provide a uniform API.
6355 See also the corresponding attribute of the derived class of interest.
6357 """))
6359add_newdoc('numpy.core.numerictypes', 'generic', ('repeat',
6360 """
6361 Not implemented (virtual attribute)
6363 Class generic exists solely to derive numpy scalars from, and possesses,
6364 albeit unimplemented, all the attributes of the ndarray class
6365 so as to provide a uniform API.
6367 See also the corresponding attribute of the derived class of interest.
6369 """))
6371add_newdoc('numpy.core.numerictypes', 'generic', ('reshape',
6372 """
6373 Not implemented (virtual attribute)
6375 Class generic exists solely to derive numpy scalars from, and possesses,
6376 albeit unimplemented, all the attributes of the ndarray class
6377 so as to provide a uniform API.
6379 See also the corresponding attribute of the derived class of interest.
6381 """))
6383add_newdoc('numpy.core.numerictypes', 'generic', ('resize',
6384 """
6385 Not implemented (virtual attribute)
6387 Class generic exists solely to derive numpy scalars from, and possesses,
6388 albeit unimplemented, all the attributes of the ndarray class
6389 so as to provide a uniform API.
6391 See also the corresponding attribute of the derived class of interest.
6393 """))
6395add_newdoc('numpy.core.numerictypes', 'generic', ('round',
6396 """
6397 Not implemented (virtual attribute)
6399 Class generic exists solely to derive numpy scalars from, and possesses,
6400 albeit unimplemented, all the attributes of the ndarray class
6401 so as to provide a uniform API.
6403 See also the corresponding attribute of the derived class of interest.
6405 """))
6407add_newdoc('numpy.core.numerictypes', 'generic', ('searchsorted',
6408 """
6409 Not implemented (virtual attribute)
6411 Class generic exists solely to derive numpy scalars from, and possesses,
6412 albeit unimplemented, all the attributes of the ndarray class
6413 so as to provide a uniform API.
6415 See also the corresponding attribute of the derived class of interest.
6417 """))
6419add_newdoc('numpy.core.numerictypes', 'generic', ('setfield',
6420 """
6421 Not implemented (virtual attribute)
6423 Class generic exists solely to derive numpy scalars from, and possesses,
6424 albeit unimplemented, all the attributes of the ndarray class
6425 so as to provide a uniform API.
6427 See also the corresponding attribute of the derived class of interest.
6429 """))
6431add_newdoc('numpy.core.numerictypes', 'generic', ('setflags',
6432 """
6433 Not implemented (virtual attribute)
6435 Class generic exists solely to derive numpy scalars from, and possesses,
6436 albeit unimplemented, all the attributes of the ndarray class so as to
6437 provide a uniform API.
6439 See also the corresponding attribute of the derived class of interest.
6441 """))
6443add_newdoc('numpy.core.numerictypes', 'generic', ('sort',
6444 """
6445 Not implemented (virtual attribute)
6447 Class generic exists solely to derive numpy scalars from, and possesses,
6448 albeit unimplemented, all the attributes of the ndarray class
6449 so as to provide a uniform API.
6451 See also the corresponding attribute of the derived class of interest.
6453 """))
6455add_newdoc('numpy.core.numerictypes', 'generic', ('squeeze',
6456 """
6457 Not implemented (virtual attribute)
6459 Class generic exists solely to derive numpy scalars from, and possesses,
6460 albeit unimplemented, all the attributes of the ndarray class
6461 so as to provide a uniform API.
6463 See also the corresponding attribute of the derived class of interest.
6465 """))
6467add_newdoc('numpy.core.numerictypes', 'generic', ('std',
6468 """
6469 Not implemented (virtual attribute)
6471 Class generic exists solely to derive numpy scalars from, and possesses,
6472 albeit unimplemented, all the attributes of the ndarray class
6473 so as to provide a uniform API.
6475 See also the corresponding attribute of the derived class of interest.
6477 """))
6479add_newdoc('numpy.core.numerictypes', 'generic', ('sum',
6480 """
6481 Not implemented (virtual attribute)
6483 Class generic exists solely to derive numpy scalars from, and possesses,
6484 albeit unimplemented, all the attributes of the ndarray class
6485 so as to provide a uniform API.
6487 See also the corresponding attribute of the derived class of interest.
6489 """))
6491add_newdoc('numpy.core.numerictypes', 'generic', ('swapaxes',
6492 """
6493 Not implemented (virtual attribute)
6495 Class generic exists solely to derive numpy scalars from, and possesses,
6496 albeit unimplemented, all the attributes of the ndarray class
6497 so as to provide a uniform API.
6499 See also the corresponding attribute of the derived class of interest.
6501 """))
6503add_newdoc('numpy.core.numerictypes', 'generic', ('take',
6504 """
6505 Not implemented (virtual attribute)
6507 Class generic exists solely to derive numpy scalars from, and possesses,
6508 albeit unimplemented, all the attributes of the ndarray class
6509 so as to provide a uniform API.
6511 See also the corresponding attribute of the derived class of interest.
6513 """))
6515add_newdoc('numpy.core.numerictypes', 'generic', ('tofile',
6516 """
6517 Not implemented (virtual attribute)
6519 Class generic exists solely to derive numpy scalars from, and possesses,
6520 albeit unimplemented, all the attributes of the ndarray class
6521 so as to provide a uniform API.
6523 See also the corresponding attribute of the derived class of interest.
6525 """))
6527add_newdoc('numpy.core.numerictypes', 'generic', ('tolist',
6528 """
6529 Not implemented (virtual attribute)
6531 Class generic exists solely to derive numpy scalars from, and possesses,
6532 albeit unimplemented, all the attributes of the ndarray class
6533 so as to provide a uniform API.
6535 See also the corresponding attribute of the derived class of interest.
6537 """))
6539add_newdoc('numpy.core.numerictypes', 'generic', ('tostring',
6540 """
6541 Not implemented (virtual attribute)
6543 Class generic exists solely to derive numpy scalars from, and possesses,
6544 albeit unimplemented, all the attributes of the ndarray class
6545 so as to provide a uniform API.
6547 See also the corresponding attribute of the derived class of interest.
6549 """))
6551add_newdoc('numpy.core.numerictypes', 'generic', ('trace',
6552 """
6553 Not implemented (virtual attribute)
6555 Class generic exists solely to derive numpy scalars from, and possesses,
6556 albeit unimplemented, all the attributes of the ndarray class
6557 so as to provide a uniform API.
6559 See also the corresponding attribute of the derived class of interest.
6561 """))
6563add_newdoc('numpy.core.numerictypes', 'generic', ('transpose',
6564 """
6565 Not implemented (virtual attribute)
6567 Class generic exists solely to derive numpy scalars from, and possesses,
6568 albeit unimplemented, all the attributes of the ndarray class
6569 so as to provide a uniform API.
6571 See also the corresponding attribute of the derived class of interest.
6573 """))
6575add_newdoc('numpy.core.numerictypes', 'generic', ('var',
6576 """
6577 Not implemented (virtual attribute)
6579 Class generic exists solely to derive numpy scalars from, and possesses,
6580 albeit unimplemented, all the attributes of the ndarray class
6581 so as to provide a uniform API.
6583 See also the corresponding attribute of the derived class of interest.
6585 """))
6587add_newdoc('numpy.core.numerictypes', 'generic', ('view',
6588 """
6589 Not implemented (virtual attribute)
6591 Class generic exists solely to derive numpy scalars from, and possesses,
6592 albeit unimplemented, all the attributes of the ndarray class
6593 so as to provide a uniform API.
6595 See also the corresponding attribute of the derived class of interest.
6597 """))
6600##############################################################################
6601#
6602# Documentation for scalar type abstract base classes in type hierarchy
6603#
6604##############################################################################
6607add_newdoc('numpy.core.numerictypes', 'number',
6608 """
6609 Abstract base class of all numeric scalar types.
6611 """)
6613add_newdoc('numpy.core.numerictypes', 'integer',
6614 """
6615 Abstract base class of all integer scalar types.
6617 """)
6619add_newdoc('numpy.core.numerictypes', 'signedinteger',
6620 """
6621 Abstract base class of all signed integer scalar types.
6623 """)
6625add_newdoc('numpy.core.numerictypes', 'unsignedinteger',
6626 """
6627 Abstract base class of all unsigned integer scalar types.
6629 """)
6631add_newdoc('numpy.core.numerictypes', 'inexact',
6632 """
6633 Abstract base class of all numeric scalar types with a (potentially)
6634 inexact representation of the values in its range, such as
6635 floating-point numbers.
6637 """)
6639add_newdoc('numpy.core.numerictypes', 'floating',
6640 """
6641 Abstract base class of all floating-point scalar types.
6643 """)
6645add_newdoc('numpy.core.numerictypes', 'complexfloating',
6646 """
6647 Abstract base class of all complex number scalar types that are made up of
6648 floating-point numbers.
6650 """)
6652add_newdoc('numpy.core.numerictypes', 'flexible',
6653 """
6654 Abstract base class of all scalar types without predefined length.
6655 The actual size of these types depends on the specific `np.dtype`
6656 instantiation.
6658 """)
6660add_newdoc('numpy.core.numerictypes', 'character',
6661 """
6662 Abstract base class of all character string scalar types.
6664 """)
6667##############################################################################
6668#
6669# Documentation for concrete scalar classes
6670#
6671##############################################################################
6673def numeric_type_aliases(aliases):
6674 def type_aliases_gen():
6675 for alias, doc in aliases:
6676 try:
6677 alias_type = getattr(_numerictypes, alias)
6678 except AttributeError:
6679 # The set of aliases that actually exist varies between platforms
6680 pass
6681 else:
6682 yield (alias_type, alias, doc)
6683 return list(type_aliases_gen())
6686possible_aliases = numeric_type_aliases([
6687 ('int8', '8-bit signed integer (-128 to 127)'),
6688 ('int16', '16-bit signed integer (-32768 to 32767)'),
6689 ('int32', '32-bit signed integer (-2147483648 to 2147483647)'),
6690 ('int64', '64-bit signed integer (-9223372036854775808 to 9223372036854775807)'),
6691 ('intp', 'Signed integer large enough to fit pointer, compatible with C ``intptr_t``'),
6692 ('uint8', '8-bit unsigned integer (0 to 255)'),
6693 ('uint16', '16-bit unsigned integer (0 to 65535)'),
6694 ('uint32', '32-bit unsigned integer (0 to 4294967295)'),
6695 ('uint64', '64-bit unsigned integer (0 to 18446744073709551615)'),
6696 ('uintp', 'Unsigned integer large enough to fit pointer, compatible with C ``uintptr_t``'),
6697 ('float16', '16-bit-precision floating-point number type: sign bit, 5 bits exponent, 10 bits mantissa'),
6698 ('float32', '32-bit-precision floating-point number type: sign bit, 8 bits exponent, 23 bits mantissa'),
6699 ('float64', '64-bit precision floating-point number type: sign bit, 11 bits exponent, 52 bits mantissa'),
6700 ('float96', '96-bit extended-precision floating-point number type'),
6701 ('float128', '128-bit extended-precision floating-point number type'),
6702 ('complex64', 'Complex number type composed of 2 32-bit-precision floating-point numbers'),
6703 ('complex128', 'Complex number type composed of 2 64-bit-precision floating-point numbers'),
6704 ('complex192', 'Complex number type composed of 2 96-bit extended-precision floating-point numbers'),
6705 ('complex256', 'Complex number type composed of 2 128-bit extended-precision floating-point numbers'),
6706 ])
6709def add_newdoc_for_scalar_type(obj, fixed_aliases, doc):
6710 o = getattr(_numerictypes, obj)
6712 character_code = dtype(o).char
6713 canonical_name_doc = "" if obj == o.__name__ else "Canonical name: ``np.{}``.\n ".format(obj)
6714 alias_doc = ''.join("Alias: ``np.{}``.\n ".format(alias) for alias in fixed_aliases)
6715 alias_doc += ''.join("Alias *on this platform*: ``np.{}``: {}.\n ".format(alias, doc)
6716 for (alias_type, alias, doc) in possible_aliases if alias_type is o)
6718 docstring = """
6719 {doc}
6720 Character code: ``'{character_code}'``.
6721 {canonical_name_doc}{alias_doc}
6722 """.format(doc=doc.strip(), character_code=character_code,
6723 canonical_name_doc=canonical_name_doc, alias_doc=alias_doc)
6725 add_newdoc('numpy.core.numerictypes', obj, docstring)
6728add_newdoc_for_scalar_type('bool_', ['bool8'],
6729 """
6730 Boolean type (True or False), stored as a byte.
6731 """)
6733add_newdoc_for_scalar_type('byte', [],
6734 """
6735 Signed integer type, compatible with C ``char``.
6736 """)
6738add_newdoc_for_scalar_type('short', [],
6739 """
6740 Signed integer type, compatible with C ``short``.
6741 """)
6743add_newdoc_for_scalar_type('intc', [],
6744 """
6745 Signed integer type, compatible with C ``int``.
6746 """)
6748add_newdoc_for_scalar_type('int_', [],
6749 """
6750 Signed integer type, compatible with Python `int` anc C ``long``.
6751 """)
6753add_newdoc_for_scalar_type('longlong', [],
6754 """
6755 Signed integer type, compatible with C ``long long``.
6756 """)
6758add_newdoc_for_scalar_type('ubyte', [],
6759 """
6760 Unsigned integer type, compatible with C ``unsigned char``.
6761 """)
6763add_newdoc_for_scalar_type('ushort', [],
6764 """
6765 Unsigned integer type, compatible with C ``unsigned short``.
6766 """)
6768add_newdoc_for_scalar_type('uintc', [],
6769 """
6770 Unsigned integer type, compatible with C ``unsigned int``.
6771 """)
6773add_newdoc_for_scalar_type('uint', [],
6774 """
6775 Unsigned integer type, compatible with C ``unsigned long``.
6776 """)
6778add_newdoc_for_scalar_type('ulonglong', [],
6779 """
6780 Signed integer type, compatible with C ``unsigned long long``.
6781 """)
6783add_newdoc_for_scalar_type('half', [],
6784 """
6785 Half-precision floating-point number type.
6786 """)
6788add_newdoc_for_scalar_type('single', [],
6789 """
6790 Single-precision floating-point number type, compatible with C ``float``.
6791 """)
6793add_newdoc_for_scalar_type('double', ['float_'],
6794 """
6795 Double-precision floating-point number type, compatible with Python `float`
6796 and C ``double``.
6797 """)
6799add_newdoc_for_scalar_type('longdouble', ['longfloat'],
6800 """
6801 Extended-precision floating-point number type, compatible with C
6802 ``long double`` but not necessarily with IEEE 754 quadruple-precision.
6803 """)
6805add_newdoc_for_scalar_type('csingle', ['singlecomplex'],
6806 """
6807 Complex number type composed of two single-precision floating-point
6808 numbers.
6809 """)
6811add_newdoc_for_scalar_type('cdouble', ['cfloat', 'complex_'],
6812 """
6813 Complex number type composed of two double-precision floating-point
6814 numbers, compatible with Python `complex`.
6815 """)
6817add_newdoc_for_scalar_type('clongdouble', ['clongfloat', 'longcomplex'],
6818 """
6819 Complex number type composed of two extended-precision floating-point
6820 numbers.
6821 """)
6823add_newdoc_for_scalar_type('object_', [],
6824 """
6825 Any Python object.
6826 """)
6828# TODO: work out how to put this on the base class, np.floating
6829for float_name in ('half', 'single', 'double', 'longdouble'):
6830 add_newdoc('numpy.core.numerictypes', float_name, ('as_integer_ratio',
6831 """
6832 {ftype}.as_integer_ratio() -> (int, int)
6834 Return a pair of integers, whose ratio is exactly equal to the original
6835 floating point number, and with a positive denominator.
6836 Raise OverflowError on infinities and a ValueError on NaNs.
6838 >>> np.{ftype}(10.0).as_integer_ratio()
6839 (10, 1)
6840 >>> np.{ftype}(0.0).as_integer_ratio()
6841 (0, 1)
6842 >>> np.{ftype}(-.25).as_integer_ratio()
6843 (-1, 4)
6844 """.format(ftype=float_name)))