summaryrefslogtreecommitdiff
path: root/numpy/add_newdocs.py
diff options
context:
space:
mode:
Diffstat (limited to 'numpy/add_newdocs.py')
-rw-r--r--numpy/add_newdocs.py336
1 files changed, 285 insertions, 51 deletions
diff --git a/numpy/add_newdocs.py b/numpy/add_newdocs.py
index eba532735..9740292bb 100644
--- a/numpy/add_newdocs.py
+++ b/numpy/add_newdocs.py
@@ -463,6 +463,67 @@ add_newdoc('numpy.core', 'nditer', ('reset',
"""))
+add_newdoc('numpy.core', 'nested_iters',
+ """
+ Create nditers for use in nested loops
+
+ Create a tuple of `nditer` objects which iterate in nested loops over
+ different axes of the op argument. The first iterator is used in the
+ outermost loop, the last in the innermost loop. Advancing one will change
+ the subsequent iterators to point at its new element.
+
+ Parameters
+ ----------
+ op : ndarray or sequence of array_like
+ The array(s) to iterate over.
+
+ axes : list of list of int
+ Each item is used as an "op_axes" argument to an nditer
+
+ flags, op_flags, op_dtypes, order, casting, buffersize (optional)
+ See `nditer` parameters of the same name
+
+ Returns
+ -------
+ iters : tuple of nditer
+ An nditer for each item in `axes`, outermost first
+
+ See Also
+ --------
+ nditer
+
+ Examples
+ --------
+
+ Basic usage. Note how y is the "flattened" version of
+ [a[:, 0, :], a[:, 1, 0], a[:, 2, :]] since we specified
+ the first iter's axes as [1]
+
+ >>> a = np.arange(12).reshape(2, 3, 2)
+ >>> i, j = np.nested_iters(a, [[1], [0, 2]], flags=["multi_index"])
+ >>> for x in i:
+ ... print(i.multi_index)
+ ... for y in j:
+ ... print('', j.multi_index, y)
+
+ (0,)
+ (0, 0) 0
+ (0, 1) 1
+ (1, 0) 6
+ (1, 1) 7
+ (1,)
+ (0, 0) 2
+ (0, 1) 3
+ (1, 0) 8
+ (1, 1) 9
+ (2,)
+ (0, 0) 4
+ (0, 1) 5
+ (1, 0) 10
+ (1, 1) 11
+
+ """)
+
###############################################################################
@@ -823,24 +884,24 @@ add_newdoc('numpy.core.multiarray', 'empty',
add_newdoc('numpy.core.multiarray', 'empty_like',
"""
- empty_like(a, dtype=None, order='K', subok=True)
+ empty_like(prototype, dtype=None, order='K', subok=True)
Return a new array with the same shape and type as a given array.
Parameters
----------
- a : array_like
- The shape and data-type of `a` define these same attributes of the
- returned array.
+ prototype : array_like
+ The shape and data-type of `prototype` define these same attributes
+ of the returned array.
dtype : data-type, optional
Overrides the data type of the result.
.. versionadded:: 1.6.0
order : {'C', 'F', 'A', or 'K'}, optional
Overrides the memory layout of the result. 'C' means C-order,
- 'F' means F-order, 'A' means 'F' if ``a`` is Fortran contiguous,
- 'C' otherwise. 'K' means match the layout of ``a`` as closely
- as possible.
+ 'F' means F-order, 'A' means 'F' if ``prototype`` is Fortran
+ contiguous, 'C' otherwise. 'K' means match the layout of ``prototype``
+ as closely as possible.
.. versionadded:: 1.6.0
subok : bool, optional.
@@ -852,7 +913,7 @@ add_newdoc('numpy.core.multiarray', 'empty_like',
-------
out : ndarray
Array of uninitialized (arbitrary) data with the same
- shape and type as `a`.
+ shape and type as `prototype`.
See Also
--------
@@ -1171,7 +1232,8 @@ add_newdoc('numpy.core.multiarray', 'concatenate',
The arrays must have the same shape, except in the dimension
corresponding to `axis` (the first, by default).
axis : int, optional
- The axis along which the arrays will be joined. Default is 0.
+ The axis along which the arrays will be joined. If axis is None,
+ arrays are flattened before use. Default is 0.
out : ndarray, optional
If provided, the destination to place the result. The shape must be
correct, matching that of what concatenate would have returned if no
@@ -1215,6 +1277,8 @@ add_newdoc('numpy.core.multiarray', 'concatenate',
>>> np.concatenate((a, b.T), axis=1)
array([[1, 2, 5],
[3, 4, 6]])
+ >>> np.concatenate((a, b), axis=None)
+ array([1, 2, 3, 4, 5, 6])
This function will not preserve masking of MaskedArray inputs.
@@ -1512,7 +1576,7 @@ add_newdoc('numpy.core.multiarray', 'where',
>>> ix
array([[False, False, False],
[ True, True, False],
- [False, True, False]], dtype=bool)
+ [False, True, False]])
>>> np.where(ix)
(array([1, 1, 2]), array([0, 1, 1]))
@@ -1711,7 +1775,7 @@ add_newdoc('numpy.core.multiarray', 'promote_types',
kind to which both ``type1`` and ``type2`` may be safely cast.
The returned data type is always in native byte order.
- This function is symmetric and associative.
+ This function is symmetric, but rarely associative.
Parameters
----------
@@ -1753,6 +1817,14 @@ add_newdoc('numpy.core.multiarray', 'promote_types',
>>> np.promote_types('i4', 'S8')
dtype('S11')
+ An example of a non-associative case:
+
+ >>> p = np.promote_types
+ >>> p('S', p('i1', 'u1'))
+ dtype('S6')
+ >>> p(p('S', 'i1'), 'u1')
+ dtype('S4')
+
""")
add_newdoc('numpy.core.multiarray', 'min_scalar_type',
@@ -1928,12 +2000,22 @@ add_newdoc('numpy.core', 'dot',
"""
dot(a, b, out=None)
- Dot product of two arrays.
+ Dot product of two arrays. Specifically,
+
+ - If both `a` and `b` are 1-D arrays, it is inner product of vectors
+ (without complex conjugation).
+
+ - If both `a` and `b` are 2-D arrays, it is matrix multiplication,
+ but using :func:`matmul` or ``a @ b`` is preferred.
+
+ - If either `a` or `b` is 0-D (scalar), it is equivalent to :func:`multiply`
+ and using ``numpy.multiply(a, b)`` or ``a * b`` is preferred.
- For 2-D arrays it is equivalent to matrix multiplication, and for 1-D
- arrays to inner product of vectors (without complex conjugation). For
- N dimensions it is a sum product over the last axis of `a` and
- the second-to-last of `b`::
+ - If `a` is an N-D array and `b` is a 1-D array, it is a sum product over
+ the last axis of `a` and `b`.
+
+ - If `a` is an N-D array and `b` is an M-D array (where ``M>=2``), it is a
+ sum product over the last axis of `a` and the second-to-last axis of `b`::
dot(a, b)[i,j,k,m] = sum(a[i,j,:] * b[k,:,m])
@@ -2782,8 +2864,13 @@ add_newdoc('numpy.core.multiarray', 'ndarray', ('flags',
array raises a RuntimeError exception.
ALIGNED (A)
The data and all elements are aligned appropriately for the hardware.
+ WRITEBACKIFCOPY (X)
+ This array is a copy of some other array. The C-API function
+ PyArray_ResolveWritebackIfCopy must be called before deallocating
+ to the base array will be updated with the contents of this array.
UPDATEIFCOPY (U)
- This array is a copy of some other array. When this array is
+ (Deprecated, use WRITEBACKIFCOPY) This array is a copy of some other array.
+ When this array is
deallocated, the base array will be updated with the contents of
this array.
FNC
@@ -2803,13 +2890,14 @@ add_newdoc('numpy.core.multiarray', 'ndarray', ('flags',
or by using lowercased attribute names (as in ``a.flags.writeable``). Short flag
names are only supported in dictionary access.
- Only the UPDATEIFCOPY, WRITEABLE, and ALIGNED flags can be changed by
- the user, via direct assignment to the attribute or dictionary entry,
- or by calling `ndarray.setflags`.
+ Only the WRITEBACKIFCOPY, UPDATEIFCOPY, WRITEABLE, and ALIGNED flags can be
+ changed by the user, via direct assignment to the attribute or dictionary
+ entry, or by calling `ndarray.setflags`.
The array flags cannot be set arbitrarily:
- UPDATEIFCOPY can only be set ``False``.
+ - WRITEBACKIFCOPY can only be set ``False``.
- ALIGNED can only be set ``True`` if the data is truly aligned.
- WRITEABLE can only be set ``True`` if the array owns its own memory
or the ultimate owner of the memory exposes a writeable buffer
@@ -3102,7 +3190,7 @@ add_newdoc('numpy.core.multiarray', 'ndarray', ('__copy__',
"""a.__copy__()
Used if :func:`copy.copy` is called on an array. Returns a copy of the array.
-
+
Equivalent to ``a.copy(order='K')``.
"""))
@@ -3128,7 +3216,7 @@ add_newdoc('numpy.core.multiarray', 'ndarray', ('__setstate__',
"""a.__setstate__(state, /)
For unpickling.
-
+
The `state` argument must be a sequence that contains the following
elements:
@@ -3978,7 +4066,7 @@ add_newdoc('numpy.core.multiarray', 'ndarray', ('prod',
add_newdoc('numpy.core.multiarray', 'ndarray', ('ptp',
"""
- a.ptp(axis=None, out=None)
+ a.ptp(axis=None, out=None, keepdims=False)
Peak to peak (maximum - minimum) value along a given axis.
@@ -4007,7 +4095,7 @@ add_newdoc('numpy.core.multiarray', 'ndarray', ('put',
add_newdoc('numpy.core.multiarray', 'copyto',
"""
- copyto(dst, src, casting='same_kind', where=None)
+ copyto(dst, src, casting='same_kind', where=True)
Copies values from one array to another, broadcasting as necessary.
@@ -4312,16 +4400,17 @@ add_newdoc('numpy.core.multiarray', 'ndarray', ('setflags',
"""
a.setflags(write=None, align=None, uic=None)
- Set array flags WRITEABLE, ALIGNED, and UPDATEIFCOPY, respectively.
+ Set array flags WRITEABLE, ALIGNED, (WRITEBACKIFCOPY and UPDATEIFCOPY),
+ respectively.
These Boolean-valued flags affect how numpy interprets the memory
area used by `a` (see Notes below). The ALIGNED flag can only
be set to True if the data is actually aligned according to the type.
- The UPDATEIFCOPY flag can never be set to True. The flag WRITEABLE
- can only be set to True if the array owns its own memory, or the
- ultimate owner of the memory exposes a writeable buffer interface,
- or is a string. (The exception for string is made so that unpickling
- can be done without copying memory.)
+ The WRITEBACKIFCOPY and (deprecated) UPDATEIFCOPY flags can never be set
+ to True. The flag WRITEABLE can only be set to True if the array owns its
+ own memory, or the ultimate owner of the memory exposes a writeable buffer
+ interface, or is a string. (The exception for string is made so that
+ unpickling can be done without copying memory.)
Parameters
----------
@@ -4335,20 +4424,22 @@ add_newdoc('numpy.core.multiarray', 'ndarray', ('setflags',
Notes
-----
Array flags provide information about how the memory area used
- for the array is to be interpreted. There are 6 Boolean flags
- in use, only three of which can be changed by the user:
- UPDATEIFCOPY, WRITEABLE, and ALIGNED.
+ for the array is to be interpreted. There are 7 Boolean flags
+ in use, only four of which can be changed by the user:
+ WRITEBACKIFCOPY, UPDATEIFCOPY, WRITEABLE, and ALIGNED.
WRITEABLE (W) the data area can be written to;
ALIGNED (A) the data and strides are aligned appropriately for the hardware
(as determined by the compiler);
- UPDATEIFCOPY (U) this array is a copy of some other array (referenced
- by .base). When this array is deallocated, the base array will be
- updated with the contents of this array.
+ UPDATEIFCOPY (U) (deprecated), replaced by WRITEBACKIFCOPY;
- All flags can be accessed using their first (upper case) letter as well
+ WRITEBACKIFCOPY (X) this array is a copy of some other array (referenced
+ by .base). When the C-API function PyArray_ResolveWritebackIfCopy is
+ called, the base array will be updated with the contents of this array.
+
+ All flags can be accessed using the single (upper case) letter as well
as the full name.
Examples
@@ -4363,6 +4454,7 @@ add_newdoc('numpy.core.multiarray', 'ndarray', ('setflags',
OWNDATA : True
WRITEABLE : True
ALIGNED : True
+ WRITEBACKIFCOPY : False
UPDATEIFCOPY : False
>>> y.setflags(write=0, align=0)
>>> y.flags
@@ -4371,11 +4463,12 @@ add_newdoc('numpy.core.multiarray', 'ndarray', ('setflags',
OWNDATA : True
WRITEABLE : False
ALIGNED : False
+ WRITEBACKIFCOPY : False
UPDATEIFCOPY : False
>>> y.setflags(uic=1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
- ValueError: cannot set UPDATEIFCOPY flag to True
+ ValueError: cannot set WRITEBACKIFCOPY flag to True
"""))
@@ -4440,7 +4533,7 @@ add_newdoc('numpy.core.multiarray', 'ndarray', ('partition',
"""
a.partition(kth, axis=-1, kind='introselect', order=None)
- Rearranges the elements in the array in such a way that value of the
+ Rearranges the elements in the array in such a way that the value of the
element in kth position is in the position it would be in a sorted array.
All elements smaller than the kth element are moved before this element and
all equal or greater are moved behind it. The ordering of the elements in
@@ -4454,7 +4547,7 @@ add_newdoc('numpy.core.multiarray', 'ndarray', ('partition',
Element index to partition by. The kth element value will be in its
final sorted position and all smaller elements will be moved before it
and all equal or greater elements behind it.
- The order all elements in the partitions is undefined.
+ The order of all elements in the partitions is undefined.
If provided with a sequence of kth it will partition all elements
indexed by kth of them into their sorted position at once.
axis : int, optional
@@ -4464,8 +4557,8 @@ add_newdoc('numpy.core.multiarray', 'ndarray', ('partition',
Selection algorithm. Default is 'introselect'.
order : str or list of str, optional
When `a` is an array with fields defined, this argument specifies
- which fields to compare first, second, etc. A single field can
- be specified as a string, and not all fields need be specified,
+ which fields to compare first, second, etc. A single field can
+ be specified as a string, and not all fields need to be specified,
but unspecified fields will still be used, in the order in which
they come up in the dtype, to break ties.
@@ -5054,13 +5147,17 @@ add_newdoc('numpy.core.multiarray', 'digitize',
Return the indices of the bins to which each value in input array belongs.
- Each index ``i`` returned is such that ``bins[i-1] <= x < bins[i]`` if
- `bins` is monotonically increasing, or ``bins[i-1] > x >= bins[i]`` if
- `bins` is monotonically decreasing. If values in `x` are beyond the
- bounds of `bins`, 0 or ``len(bins)`` is returned as appropriate. If right
- is True, then the right bin is closed so that the index ``i`` is such
- that ``bins[i-1] < x <= bins[i]`` or ``bins[i-1] >= x > bins[i]`` if `bins`
- is monotonically increasing or decreasing, respectively.
+ ========= ============= ============================
+ `right` order of bins returned index `i` satisfies
+ ========= ============= ============================
+ ``False`` increasing ``bins[i-1] <= x < bins[i]``
+ ``True`` increasing ``bins[i-1] < x <= bins[i]``
+ ``False`` decreasing ``bins[i-1] > x >= bins[i]``
+ ``True`` decreasing ``bins[i-1] >= x > bins[i]``
+ ========= ============= ============================
+
+ If values in `x` are beyond the bounds of `bins`, 0 or ``len(bins)`` is
+ returned as appropriate.
Parameters
----------
@@ -5078,7 +5175,7 @@ add_newdoc('numpy.core.multiarray', 'digitize',
Returns
-------
- out : ndarray of ints
+ indices : ndarray of ints
Output array of indices, of same shape as `x`.
Raises
@@ -5105,6 +5202,15 @@ add_newdoc('numpy.core.multiarray', 'digitize',
for larger number of bins than the previous linear search. It also removes
the requirement for the input array to be 1-dimensional.
+ For monotonically _increasing_ `bins`, the following are equivalent::
+
+ np.digitize(x, bins, right=True)
+ np.searchsorted(bins, x, side='left')
+
+ Note that as the order of the arguments are reversed, the side must be too.
+ The `searchsorted` call is marginally faster, as it does not do any
+ monotonicity checks. Perhaps more importantly, it supports all dtypes.
+
Examples
--------
>>> x = np.array([0.2, 6.4, 3.0, 1.6])
@@ -5401,7 +5507,7 @@ add_newdoc('numpy.core.multiarray', 'unpackbits',
axis : int, optional
The dimension over which bit-unpacking is done.
``None`` implies unpacking the flattened array.
-
+
Returns
-------
unpacked : ndarray, uint8 type
@@ -5642,6 +5748,36 @@ add_newdoc('numpy.core', 'ufunc', ('types',
"""))
+add_newdoc('numpy.core', 'ufunc', ('signature',
+ """
+ Definition of the core elements a generalized ufunc operates on.
+
+ The signature determines how the dimensions of each input/output array
+ are split into core and loop dimensions:
+
+ 1. Each dimension in the signature is matched to a dimension of the
+ corresponding passed-in array, starting from the end of the shape tuple.
+ 2. Core dimensions assigned to the same label in the signature must have
+ exactly matching sizes, no broadcasting is performed.
+ 3. The core dimensions are removed from all inputs and the remaining
+ dimensions are broadcast together, defining the loop dimensions.
+
+ Notes
+ -----
+ Generalized ufuncs are used internally in many linalg functions, and in
+ the testing suite; the examples below are taken from these.
+ For ufuncs that operate on scalars, the signature is `None`, which is
+ equivalent to '()' for every argument.
+
+ Examples
+ --------
+ >>> np.core.umath_tests.matrix_multiply.signature
+ '(m,n),(n,p)->(m,p)'
+ >>> np.linalg._umath_linalg.det.signature
+ '(m,m)->()'
+ >>> np.add.signature is None
+ True # equivalent to '(),()->()'
+ """))
##############################################################################
#
@@ -6811,6 +6947,104 @@ add_newdoc('numpy.core.multiarray', 'normalize_axis_index',
AxisError: axes_arg: axis -4 is out of bounds for array of dimension 3
""")
+add_newdoc('numpy.core.multiarray', 'datetime_as_string',
+ """
+ datetime_as_string(arr, unit=None, timezone='naive', casting='same_kind')
+
+ Convert an array of datetimes into an array of strings.
+
+ Parameters
+ ----------
+ arr : array_like of datetime64
+ The array of UTC timestamps to format.
+ unit : str
+ One of None, 'auto', or a datetime unit.
+ timezone : {'naive', 'UTC', 'local'} or tzinfo
+ Timezone information to use when displaying the datetime. If 'UTC', end
+ with a Z to indicate UTC time. If 'local', convert to the local timezone
+ first, and suffix with a +-#### timezone offset. If a tzinfo object,
+ then do as with 'local', but use the specified timezone.
+ casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}
+ Casting to allow when changing between datetime units.
+
+ Returns
+ -------
+ str_arr : ndarray
+ An array of strings the same shape as `arr`.
+
+ Examples
+ --------
+ >>> d = np.arange('2002-10-27T04:30', 4*60, 60, dtype='M8[m]')
+ >>> d
+ array(['2002-10-27T04:30', '2002-10-27T05:30', '2002-10-27T06:30',
+ '2002-10-27T07:30'], dtype='datetime64[m]')
+
+ Setting the timezone to UTC shows the same information, but with a Z suffix
+
+ >>> np.datetime_as_string(d, timezone='UTC')
+ array(['2002-10-27T04:30Z', '2002-10-27T05:30Z', '2002-10-27T06:30Z',
+ '2002-10-27T07:30Z'], dtype='<U35')
+
+ Note that we picked datetimes that cross a DST boundary. Passing in a
+ ``pytz`` timezone object will print the appropriate offset::
+
+ >>> np.datetime_as_string(d, timezone=pytz.timezone('US/Eastern'))
+ array(['2002-10-27T00:30-0400', '2002-10-27T01:30-0400',
+ '2002-10-27T01:30-0500', '2002-10-27T02:30-0500'], dtype='<U39')
+
+ Passing in a unit will change the precision::
+
+ >>> np.datetime_as_string(d, unit='h')
+ array(['2002-10-27T04', '2002-10-27T05', '2002-10-27T06', '2002-10-27T07'],
+ dtype='<U32')
+ >>> np.datetime_as_string(d, unit='s')
+ array(['2002-10-27T04:30:00', '2002-10-27T05:30:00', '2002-10-27T06:30:00',
+ '2002-10-27T07:30:00'], dtype='<U38')
+
+ But can be made to not lose precision::
+
+ >>> np.datetime_as_string(d, unit='h', casting='safe')
+ TypeError: Cannot create a datetime string as units 'h' from a NumPy
+ datetime with units 'm' according to the rule 'safe'
+ """)
+
+add_newdoc('numpy.core.multiarray', 'datetime_data',
+ """
+ datetime_data(dtype, /)
+
+ Get information about the step size of a date or time type.
+
+ The returned tuple can be passed as the second argument of `datetime64` and
+ `timedelta64`.
+
+ Parameters
+ ----------
+ dtype : dtype
+ The dtype object, which must be a `datetime64` or `timedelta64` type.
+
+ Returns
+ -------
+ unit : str
+ The :ref:`datetime unit <arrays.dtypes.dateunits>` on which this dtype
+ is based.
+ count : int
+ The number of base units in a step.
+
+ Examples
+ --------
+ >>> dt_25s = np.dtype('timedelta64[25s]')
+ >>> np.datetime_data(dt_25s)
+ ('s', 25)
+ >>> np.array(10, dt_25s).astype('timedelta64[s]')
+ array(250, dtype='timedelta64[s]')
+
+ The result can be used to construct a datetime that uses the same units
+ as a timedelta::
+
+ >>> np.datetime64('2010', np.datetime_data(dt_25s))
+ numpy.datetime64('2010-01-01T00:00:00','25s')
+ """)
+
##############################################################################
#
# nd_grid instances