summaryrefslogtreecommitdiff
path: root/numpy/core/fromnumeric.py
diff options
context:
space:
mode:
Diffstat (limited to 'numpy/core/fromnumeric.py')
-rw-r--r--numpy/core/fromnumeric.py1381
1 files changed, 774 insertions, 607 deletions
diff --git a/numpy/core/fromnumeric.py b/numpy/core/fromnumeric.py
index d3d94b891..073614495 100644
--- a/numpy/core/fromnumeric.py
+++ b/numpy/core/fromnumeric.py
@@ -43,22 +43,24 @@ def _wrapit(obj, method, *args, **kwds):
def take(a, indices, axis=None, out=None, mode='raise'):
- """Return an array formed from the elements of a at the given indices.
+ """
+ Take elements from an array along a given axis.
- This function does the same thing as "fancy" indexing; however, it can
- be easier to use if you need to specify a given axis.
+ This function does the same thing as "fancy" indexing (indexing arrays
+ using arrays); however, it can be easier to use if you need to specify
+ a given axis.
Parameters
----------
- a : array
- The source array
+ a : ndarray
+ The source array.
indices : int array
The indices of the values to extract.
- axis : {None, int}, optional
- The axis over which to select values. None signifies that the
- operation should be performed over the flattened array.
- out : {None, array}, optional
- If provided, the result will be inserted into this array. It should
+ axis : int, optional
+ The axis over which to select values. By default, the
+ flattened input array is used.
+ out : ndarray, optional
+ If provided, the result will be placed in this array. It should
be of the appropriate shape and dtype.
mode : {'raise', 'wrap', 'clip'}, optional
Specifies how out-of-bounds indices will behave.
@@ -68,8 +70,8 @@ def take(a, indices, axis=None, out=None, mode='raise'):
Returns
-------
- subarray : array
- The returned array has the same type as a.
+ subarray : ndarray
+ The returned array has the same type as `a`.
See Also
--------
@@ -85,22 +87,23 @@ def take(a, indices, axis=None, out=None, mode='raise'):
# not deprecated --- copy if necessary, view otherwise
def reshape(a, newshape, order='C'):
- """Returns an array containing the data of a, but with a new shape.
+ """
+ Returns an array containing the data of a, but with a new shape.
Parameters
----------
- a : array
+ a : ndarray
Array to be reshaped.
- newshape : shape tuple or int
- The new shape should be compatible with the original shape. If an
- integer, then the result will be a 1D array of that length.
- order : {'C', 'FORTRAN'}, optional
+ newshape : {tuple, int}
+ The new shape should be compatible with the original shape. If an
+ integer, then the result will be a 1-D array of that length.
+ order : {'C', 'F'}, optional
Determines whether the array data should be viewed as in C
(row-major) order or FORTRAN (column-major) order.
Returns
-------
- reshaped_array : array
+ reshaped_array : ndarray
This will be a new view object if possible; otherwise, it will
be a copy.
@@ -108,6 +111,19 @@ def reshape(a, newshape, order='C'):
--------
ndarray.reshape : Equivalent method.
+ Examples
+ --------
+ >>> a = np.array([[1,2], [3,4]])
+ >>> a.reshape(4)
+ array([1, 2, 3, 4])
+ >>> a.reshape(4, order='F')
+ array([1, 3, 2, 4])
+ >>> a.reshape((4,1))
+ array([[1],
+ [2],
+ [3],
+ [4]])
+
"""
try:
reshape = a.reshape
@@ -117,8 +133,8 @@ def reshape(a, newshape, order='C'):
def choose(a, choices, out=None, mode='raise'):
- """Use an index array to construct a new array from a set of
- choices.
+ """
+ Use an index array to construct a new array from a set of choices.
Given an array of integers and a set of n choice arrays, this function
will create a new array that merges each of the choice arrays. Where a
@@ -137,14 +153,16 @@ def choose(a, choices, out=None, mode='raise'):
If provided, the result will be inserted into this array. It should
be of the appropriate shape and dtype
mode : {'raise', 'wrap', 'clip'}, optional
- Specifies how out-of-bounds indices will behave.
- 'raise' : raise an error
- 'wrap' : wrap around
- 'clip' : clip to the range
+ Specifies how out-of-bounds indices will behave:
+
+ * 'raise' : raise an error
+ * 'wrap' : wrap around
+ * 'clip' : clip to the range
Returns
-------
merged_array : array
+ The merged results.
See Also
--------
@@ -171,29 +189,29 @@ def choose(a, choices, out=None, mode='raise'):
def repeat(a, repeats, axis=None):
- """Repeat elements of an array.
+ """
+ Repeat elements of an array.
Parameters
----------
- a : {array_like}
+ a : array_like
Input array.
- repeats : {integer, integer_array}
- The number of repetitions for each element. If a plain integer, then
- it is applied to all elements. If an array, it needs to be of the
- same length as the chosen axis.
- axis : {None, integer}, optional
- The axis along which to repeat values. If None, then this function
- will operated on the flattened array `a` and return a similarly flat
- result.
+ repeats : {int, array of ints}
+ The number of repetitions for each element. `repeats` is broadcasted
+ to fit the shape of the given axis.
+ axis : int, optional
+ The axis along which to repeat values. By default, use the
+ flattened input array, and return a flat output array.
Returns
-------
- repeated_array : array
+ repeated_array : ndarray
+ Output array which has the same shape as `a`, except along
+ the given axis.
See Also
--------
- ndarray.repeat : equivalent method
- tile : tile an array
+ tile : Tile an array.
Examples
--------
@@ -217,8 +235,10 @@ def repeat(a, repeats, axis=None):
def put(a, ind, v, mode='raise'):
- """Set a.flat[n] = v[n] for all n in ind.
- If v is shorter than ind, it will repeat.
+ """
+ Set a.flat[n] = v[n] for all n in ind.
+
+ If `v` is shorter than `ind`, it will repeat.
Parameters
----------
@@ -230,15 +250,18 @@ def put(a, ind, v, mode='raise'):
Values to place in `a` at target indices.
mode : {'raise', 'wrap', 'clip'}, optional
Specifies how out-of-bounds indices will behave.
- 'raise' -- raise an error
- 'wrap' -- wrap around
- 'clip' -- clip to the range
+
+ * 'raise' -- raise an error
+ * 'wrap' -- wrap around
+ * 'clip' -- clip to the range
Notes
-----
- If v is shorter than mask it will be repeated as necessary. In particular v
- can be a scalar or length 1 array. The routine put is the equivalent of the
- following (although the loop is in C for speed):
+ If `v` is shorter than `mask` it will be repeated as necessary. In
+ particular `v` can be a scalar or length 1 array. The routine put
+ is the equivalent of the following (although the loop is in C for
+ speed):
+ ::
ind = array(indices, copy=False)
v = array(values, copy=False).astype(a.dtype)
@@ -256,7 +279,8 @@ def put(a, ind, v, mode='raise'):
def swapaxes(a, axis1, axis2):
- """Return a view of array a with axis1 and axis2 interchanged.
+ """
+ Interchange two axes of an array.
Parameters
----------
@@ -267,6 +291,12 @@ def swapaxes(a, axis1, axis2):
axis2 : int
Second axis.
+ Returns
+ -------
+ a_swapped : ndarray
+ If `a` is an ndarray, then a view on `a` is returned, otherwise
+ a new array is created.
+
Examples
--------
>>> x = np.array([[1,2,3]])
@@ -279,13 +309,14 @@ def swapaxes(a, axis1, axis2):
>>> x
array([[[0, 1],
[2, 3]],
-
+ <BLANKLINE>
[[4, 5],
[6, 7]]])
+
>>> np.swapaxes(x,0,2)
array([[[0, 4],
[2, 6]],
-
+ <BLANKLINE>
[[1, 5],
[3, 7]]])
@@ -298,15 +329,26 @@ def swapaxes(a, axis1, axis2):
def transpose(a, axes=None):
- """Return a view of the array with dimensions permuted.
+ """
+ Permute the dimensions of an array.
Parameters
----------
a : array_like
Input array.
- axes : {None, list of int}, optional
- If None (the default), reverse dimensions, otherwise permute
- axes according to the values given.
+ axes : list of ints, optional
+ By default, reverse the dimensions, otherwise permute the axes
+ according to the values given.
+
+ Returns
+ -------
+ p : ndarray
+ `a` with its axes permuted. A view is returned whenever
+ possible.
+
+ See Also
+ --------
+ rollaxis
Examples
--------
@@ -319,9 +361,9 @@ def transpose(a, axes=None):
array([[0, 2],
[1, 3]])
- >>> np.transpose(x,(0,1)) # no change, axes are kept in current order
- array([[0, 1],
- [2, 3]])
+ >>> x = np.ones((1, 2, 3))
+ >>> np.transpose(x, (1, 0, 2)).shape
+ (2, 1, 3)
"""
try:
@@ -332,28 +374,27 @@ def transpose(a, axes=None):
def sort(a, axis=-1, kind='quicksort', order=None):
- """Return copy of 'a' sorted along the given axis.
-
- Perform an inplace sort along the given axis using the algorithm
- specified by the kind keyword.
+ """
+ Return a sorted copy of an array.
Parameters
----------
- a : array
+ a : array-like
Array to be sorted.
- axis : {None, int} optional
- Axis along which to sort. None indicates that the flattened
- array should be used.
+ axis : int, optional
+ Axis along which to sort. If not specified, the flattened array
+ is used.
kind : {'quicksort', 'mergesort', 'heapsort'}, optional
- Sorting algorithm to use.
- order : {None, list type}, optional
- When a is an array with fields defined, this argument specifies
+ Sorting algorithm.
+ order : list, optional
+ When `a` is an ndarray with fields defined, this argument specifies
which fields to compare first, second, etc. Not all fields need be
specified.
Returns
-------
- sorted_array : array of same type as a
+ sorted_array : ndarray
+ Array of same type and shape as `a`.
See Also
--------
@@ -363,8 +404,8 @@ def sort(a, axis=-1, kind='quicksort', order=None):
Notes
-----
- The various sorts are characterized by average speed, worst case
- performance, need for work space, and whether they are stable. A
+ The various sorting algorithms are characterized by their average speed,
+ worst case performance, work space size, and whether they are stable. A
stable sort keeps items with the same key in the same relative
order. The three available algorithms have the following
properties:
@@ -378,9 +419,21 @@ def sort(a, axis=-1, kind='quicksort', order=None):
=========== ======= ============= ============ =======
All the sort algorithms make temporary copies of the data when
- the sort is not along the last axis. Consequently, sorts along
- the last axis are faster and use less space than sorts along
- other axis.
+ sorting along any but the last axis. Consequently, sorting along
+ the last axis is faster and uses less space than sorting along
+ any other axis.
+
+ Examples
+ --------
+ >>> a=np.array([[1,4],[3,1]])
+ >>> a.sort(1)
+ >>> a
+ array([[1, 4],
+ [1, 3]])
+ >>> a.sort(0)
+ >>> a
+ array([[1, 3],
+ [1, 4]])
"""
if axis is None:
@@ -393,58 +446,77 @@ def sort(a, axis=-1, kind='quicksort', order=None):
def argsort(a, axis=-1, kind='quicksort', order=None):
- """Returns array of indices that index 'a' in sorted order.
+ """
+ Returns the indices that would sort an array.
Perform an indirect sort along the given axis using the algorithm specified
- by the kind keyword. It returns an array of indices of the same shape as a
- that index data along the given axis in sorted order.
+ by the `kind` keyword. It returns an array of indices of the same shape as
+ `a` that index data along the given axis in sorted order.
Parameters
----------
- a : array
- Array to be sorted.
- axis : {None, int} optional
- Axis along which to sort. None indicates that the flattened
- array should be used.
+ a : array_like
+ Array to sort.
+ axis : int, optional
+ Axis along which to sort. If not given, the flattened array is used.
kind : {'quicksort', 'mergesort', 'heapsort'}, optional
- Sorting algorithm to use.
- order : {None, list type}, optional
- When a is an array with fields defined, this argument specifies
+ Sorting algorithm.
+ order : list, optional
+ When `a` is an array with fields defined, this argument specifies
which fields to compare first, second, etc. Not all fields need be
specified.
Returns
-------
- index_array : {integer_array}
- Array of indices that sort 'a' along the specified axis.
+ index_array : ndarray of ints
+ Array of indices that sort `a` along the specified axis.
+ In other words, ``a[index_array]`` yields a sorted `a`.
See Also
--------
+ sort : Describes sorting algorithms used.
lexsort : Indirect stable sort with multiple keys.
- sort : Inplace sort.
+ ndarray.sort : Inplace sort.
Notes
-----
- The various sorts are characterized by average speed, worst case
- performance, need for work space, and whether they are stable. A
- stable sort keeps items with the same key in the same relative
- order. The three available algorithms have the following
- properties:
+ See `sort` for notes on the different sorting algorithms.
- +-----------+-------+-------------+------------+-------+
- | kind | speed | worst case | work space | stable|
- +===========+=======+=============+============+=======+
- | quicksort | 1 | O(n^2) | 0 | no |
- +-----------+-------+-------------+------------+-------+
- | mergesort | 2 | O(n*log(n)) | ~n/2 | yes |
- +-----------+-------+-------------+------------+-------+
- | heapsort | 3 | O(n*log(n)) | 0 | no |
- +-----------+-------+-------------+------------+-------+
+ Examples
+ --------
+ One dimensional array:
- All the sort algorithms make temporary copies of the data when
- the sort is not along the last axis. Consequently, sorts along
- the last axis are faster and use less space than sorts along
- other axis.
+ >>> x = np.array([3, 1, 2])
+ >>> np.argsort(x)
+ array([1, 2, 0])
+
+ Two-dimensional array:
+
+ >>> x = np.array([[0, 3], [2, 2]])
+ >>> x
+ array([[0, 3],
+ [2, 2]])
+
+ >>> np.argsort(x, axis=0)
+ array([[0, 1],
+ [1, 0]])
+
+ >>> np.argsort(x, axis=1)
+ array([[0, 1],
+ [0, 1]])
+
+ Sorting with keys:
+
+ >>> x = np.array([(1, 0), (0, 1)], dtype=[('x', '<i4'), ('y', '<i4')])
+ >>> x
+ array([(1, 0), (0, 1)],
+ dtype=[('x', '<i4'), ('y', '<i4')])
+
+ >>> np.argsort(x, order=('x','y'))
+ array([1, 0])
+
+ >>> np.argsort(x, order=('y','x'))
+ array([0, 1])
"""
try:
@@ -455,28 +527,36 @@ def argsort(a, axis=-1, kind='quicksort', order=None):
def argmax(a, axis=None):
- """Returns array of indices of the maximum values of along the given axis.
+ """
+ Indices of the maximum values along a given axis.
Parameters
----------
- a : {array_like}
- Array to look in.
- axis : {None, integer}
- If None, the index is into the flattened array, otherwise along
- the specified axis
+ a : array_like
+ Input array.
+ axis : int, optional
+ By default, the index is into the flattened array, otherwise
+ along the specified axis.
Returns
-------
- index_array : {integer_array}
+ index_array : ndarray of ints
+ Array of indices into the array. It has the same shape `a`,
+ except with `axis` removed.
+
+ See Also
+ --------
+ amax : The maximum along a given axis.
+ unravel_index : Convert a flat index into an index tuple.
Examples
- --------
+ --------
>>> a = np.arange(6).reshape(2,3)
>>> np.argmax(a)
5
- >>> np.argmax(a,0)
+ >>> np.argmax(a, axis=0)
array([1, 1, 1])
- >>> np.argmax(a,1)
+ >>> np.argmax(a, axis=1)
array([2, 2])
"""
@@ -488,29 +568,10 @@ def argmax(a, axis=None):
def argmin(a, axis=None):
- """Return array of indices to the minimum values along the given axis.
-
- Parameters
- ----------
- a : {array_like}
- Array to look in.
- axis : {None, integer}
- If None, the index is into the flattened array, otherwise along
- the specified axis
-
- Returns
- -------
- index_array : {integer_array}
+ """
+ Return the indices of the minimum values along the given axis of `a`.
- Examples
- --------
- >>> a = np.arange(6).reshape(2,3)
- >>> np.argmin(a)
- 0
- >>> np.argmin(a,0)
- array([0, 0, 0])
- >>> np.argmin(a,1)
- array([0, 0])
+ Refer to `numpy.argmax` for detailed documentation.
"""
try:
@@ -521,47 +582,46 @@ def argmin(a, axis=None):
def searchsorted(a, v, side='left'):
- """Return indices where keys in v should be inserted to maintain order.
+ """
+ Find indices where elements should be inserted to maintain order.
- Find the indices into a sorted array such that if the corresponding keys in
- v were inserted before the indices the order of a would be preserved. If
- side='left', then the first such index is returned. If side='right', then
- the last such index is returned. If there is no such index because the key
- is out of bounds, then the length of a is returned, i.e., the key would need
- to be appended. The returned index array has the same shape as v.
+ Find the indices into a sorted array `a` such that, if the corresponding
+ elements in `v` were inserted before the indices, the order of `a` would
+ be preserved.
Parameters
----------
- a : 1-d array
- Array must be sorted in ascending order.
- v : array or list type
- Array of keys to be searched for in a.
+ a : 1-D array_like of shape (N,)
+ Input array, sorted in ascending order.
+ v : array_like
+ Values to insert into `a`.
side : {'left', 'right'}, optional
- If 'left', the index of the first location where the key could be
- inserted is found, if 'right', the index of the last such element is
- returned. If the is no such element, then either 0 or N is returned,
- where N is the size of the array.
+ If 'left', the index of the first suitable location found is given. If
+ 'right', return the last such index. If there is no suitable
+ index, return either 0 or N (where N is the length of `a`).
Returns
-------
- indices : integer array
- Array of insertion points with the same shape as v.
+ indices : array of ints
+ Array of insertion points with the same shape as `v`.
See Also
--------
- sort : Inplace sort.
- histogram : Produce histogram from 1-d data.
+ sort : In-place sort.
+ histogram : Produce histogram from 1-D data.
Notes
-----
- The array a must be 1-d and is assumed to be sorted in ascending
- order. Searchsorted uses binary search to find the required
- insertion points.
+ Binary search is used to find the required insertion points.
Examples
--------
- >>> np.searchsorted([1,2,3,4,5],[6,4,0])
- array([5, 3, 0])
+ >>> np.searchsorted([1,2,3,4,5], 3)
+ 2
+ >>> np.searchsorted([1,2,3,4,5], 3, side='right')
+ 3
+ >>> np.searchsorted([1,2,3,4,5], [-10, 10, 2, 3])
+ array([0, 5, 1, 2])
"""
try:
@@ -572,28 +632,40 @@ def searchsorted(a, v, side='left'):
def resize(a, new_shape):
- """Return a new array with the specified shape.
-
- The original array's total size can be any size. The new array is
- filled with repeated copies of a.
+ """
+ Return a new array with the specified shape.
- Note that a.resize(new_shape) will fill the array with 0's beyond
- current definition of a.
+ If the new array is larger than the original array, then the new array
+ is filled with repeated copied of `a`. Note that this behavior is different
+ from a.resize(new_shape) which fills with zeros instead of repeated
+ copies of `a`.
Parameters
----------
- a : {array_like}
- Array to be reshaped.
+ a : array_like
+ Array to be resized.
- new_shape : {tuple}
- Shape of reshaped array.
+ new_shape : {tuple, int}
+ Shape of resized array.
Returns
-------
- reshaped_array : {array}
+ reshaped_array : ndarray
The new array is formed from the data in the old array, repeated if
- necessary to fill out the required number of elements, with the new
- shape.
+ necessary to fill out the required number of elements.
+
+ See Also
+ --------
+ ndarray.resize : resize an array in-place.
+
+ Examples
+ --------
+ >>> a=np.array([[0,1],[2,3]])
+ >>> np.resize(a,(1,4))
+ array([[0, 1, 2, 3]])
+ >>> np.resize(a,(2,4))
+ array([[0, 1, 2, 3],
+ [0, 1, 2, 3]])
"""
if isinstance(new_shape, (int, nt.integer)):
@@ -620,15 +692,27 @@ def resize(a, new_shape):
def squeeze(a):
- """Remove single-dimensional entries from the shape of a.
+ """
+ Remove single-dimensional entries from the shape of an array.
+
+ Parameters
+ ----------
+ a : array-like
+ Input data.
+
+ Returns
+ -------
+ squeezed : ndarray
+ The input array, but with with all dimensions of length 1
+ removed. Whenever possible, a view on `a` is returned.
Examples
--------
- >>> x = np.array([[[1,1,1],[2,2,2],[3,3,3]]])
+ >>> x = np.array([[[0], [1], [2]]])
>>> x.shape
- (1, 3, 3)
+ (1, 3, 1)
>>> np.squeeze(x).shape
- (3, 3)
+ (3,)
"""
try:
@@ -639,39 +723,46 @@ def squeeze(a):
def diagonal(a, offset=0, axis1=0, axis2=1):
- """Return specified diagonals.
+ """
+ Return specified diagonals.
- If a is 2-d, returns the diagonal of self with the given offset, i.e., the
- collection of elements of the form a[i,i+offset]. If a has more than two
- dimensions, then the axes specified by axis1 and axis2 are used to determine
- the 2-d subarray whose diagonal is returned. The shape of the resulting
- array can be determined by removing axis1 and axis2 and appending an index
- to the right equal to the size of the resulting diagonals.
+ If `a` is 2-D, returns the diagonal of self with the given offset,
+ i.e., the collection of elements of the form `a[i,i+offset]`.
+ If `a` has more than two dimensions, then the axes specified
+ by `axis1` and `axis2` are used to determine the 2-D subarray
+ whose diagonal is returned. The shape of the resulting array
+ can be determined by removing `axis1` and `axis2` and appending
+ an index to the right equal to the size of the resulting diagonals.
Parameters
----------
- a : {array_like}
- Array from whis the diagonals are taken.
- offset : {0, integer}, optional
+ a : array_like
+ Array from which the diagonals are taken.
+ offset : int, optional
Offset of the diagonal from the main diagonal. Can be both positive
- and negative. Defaults to main diagonal.
- axis1 : {0, integer}, optional
- Axis to be used as the first axis of the 2-d subarrays from which
- the diagonals should be taken. Defaults to first axis.
- axis2 : {1, integer}, optional
- Axis to be used as the second axis of the 2-d subarrays from which
- the diagonals should be taken. Defaults to second axis.
+ and negative. Defaults to main diagonal (0).
+ axis1 : int, optional
+ Axis to be used as the first axis of the 2-D subarrays from which
+ the diagonals should be taken. Defaults to first axis (0).
+ axis2 : int, optional
+ Axis to be used as the second axis of the 2-D subarrays from which
+ the diagonals should be taken. Defaults to second axis (1).
Returns
-------
- array_of_diagonals : array of same type as a
- If a is 2-d, a 1-d array containing the diagonal is
- returned. If a has larger dimensions, then an array of
+ array_of_diagonals : ndarray
+ If `a` is 2-D, a 1-D array containing the diagonal is
+ returned. If `a` has larger dimensions, then an array of
diagonals is returned.
+ Raises
+ ------
+ ValueError
+ If the dimension of `a` is less than 2.
+
See Also
--------
- diag : Matlab workalike for 1-d and 2-d arrays.
+ diag : Matlab workalike for 1-D and 2-D arrays.
diagflat : Create diagonal arrays.
trace : Sum along diagonals.
@@ -690,7 +781,7 @@ def diagonal(a, offset=0, axis1=0, axis2=1):
>>> a
array([[[0, 1],
[2, 3]],
-
+ <BLANKLINE>
[[4, 5],
[6, 7]]])
>>> a.diagonal(0,-2,-1)
@@ -702,35 +793,37 @@ def diagonal(a, offset=0, axis1=0, axis2=1):
def trace(a, offset=0, axis1=0, axis2=1, dtype=None, out=None):
- """Return the sum along diagonals of the array.
+ """
+ Return the sum along diagonals of the array.
- If a is 2-d, returns the sum along the diagonal of self with the given offset, i.e., the
- collection of elements of the form a[i,i+offset]. If a has more than two
- dimensions, then the axes specified by axis1 and axis2 are used to determine
- the 2-d subarray whose trace is returned. The shape of the resulting
- array can be determined by removing axis1 and axis2 and appending an index
- to the right equal to the size of the resulting diagonals.
+ If a is 2-d, returns the sum along the diagonal of self with the given
+ offset, i.e., the collection of elements of the form a[i,i+offset]. If
+ a has more than two dimensions, then the axes specified by axis1 and
+ axis2 are used to determine the 2-d subarray whose trace is returned.
+ The shape of the resulting array can be determined by removing axis1
+ and axis2 and appending an index to the right equal to the size of the
+ resulting diagonals.
Parameters
----------
- a : {array_like}
+ a : array_like
Array from whis the diagonals are taken.
- offset : {0, integer}, optional
+ offset : integer, optional
Offset of the diagonal from the main diagonal. Can be both positive
and negative. Defaults to main diagonal.
- axis1 : {0, integer}, optional
+ axis1 : integer, optional
Axis to be used as the first axis of the 2-d subarrays from which
the diagonals should be taken. Defaults to first axis.
- axis2 : {1, integer}, optional
+ axis2 : integer, optional
Axis to be used as the second axis of the 2-d subarrays from which
the diagonals should be taken. Defaults to second axis.
- dtype : {None, dtype}, optional
+ dtype : dtype, optional
Determines the type of the returned array and of the accumulator
where the elements are summed. If dtype has the value None and a is
of integer type of precision less than the default integer
precision, then the default integer precision is used. Otherwise,
the precision is the same as that of a.
- out : {None, array}, optional
+ out : array, optional
Array into which the sum can be placed. Its type is preserved and
it must be of the right shape to hold the output.
@@ -753,61 +846,112 @@ def trace(a, offset=0, axis1=0, axis2=1, dtype=None, out=None):
return asarray(a).trace(offset, axis1, axis2, dtype, out)
def ravel(a, order='C'):
- """Return a 1d array containing the elements of a (copy only if needed).
+ """
+ Return a flattened array.
- Returns the elements of a as a 1d array. The elements in the new array
- are taken in the order specified by the order keyword. The new array is
- a view of a if possible, otherwise it is a copy.
+ A 1-d array, containing the elements of the input, is returned. A copy is
+ made only if needed.
Parameters
----------
- a : {array_like}
-
+ a : array_like
+ Input array. The elements in `a` are read in the order specified by
+ `order`, and packed as a 1-dimensional array.
order : {'C','F'}, optional
- If order is 'C' the elements are taken in row major order. If order
- is 'F' they are taken in column major order.
+ The elements of `a` are read in this order. It can be either
+ 'C' for row-major order, or `F` for column-major order.
+ By default, row-major order is used.
Returns
-------
- 1d_array : {array}
+ 1d_array : ndarray
+ Output of the same dtype as `a`, and of shape ``(a.size(),)`` (or
+ ``(np.prod(a.shape),)``).
See Also
--------
- ndarray.flat : 1d iterator over the array.
- ndarray.flatten : 1d array copy of the elements of a in C order.
+ ndarray.flat : 1-D iterator over an array.
+ ndarray.flatten : 1-D array copy of the elements of an array
+ in row-major order.
+
+ Notes
+ -----
+ In row-major order, the row index varies the slowest, and the column
+ index the quickest. This can be generalised to multiple dimensions,
+ where row-major order implies that the index along the first axis
+ varies slowest, and the index along the last quickest. The opposite holds
+ for Fortran-, or column-major, mode.
Examples
--------
- >>> x = np.array([[1,2,3],[4,5,6]])
- >>> x
- array([[1, 2, 3],
- [4, 5, 6]])
- >>> np.ravel(x)
- array([1, 2, 3, 4, 5, 6])
+ If an array is in C-order (default), then `ravel` is equivalent
+ to ``reshape(-1)``:
+
+ >>> x = np.array([[1, 2, 3], [4, 5, 6]])
+ >>> print x.reshape(-1)
+ [1 2 3 4 5 6]
+
+ >>> print np.ravel(x)
+ [1 2 3 4 5 6]
+
+ When flattening using Fortran-order, however, we see
+
+ >>> print np.ravel(x, order='F')
+ [1 4 2 5 3 6]
"""
return asarray(a).ravel(order)
def nonzero(a):
- """Return the indices of the elements of a which are not zero.
+ """
+ Return the indices of the elements that are non-zero.
+
+ Returns a tuple of arrays, one for each dimension of `a`, containing
+ the indices of the non-zero elements in that dimension. The
+ corresponding non-zero values can be obtained with::
+
+ a[nonzero(a)]
+
+ To group the indices by element, rather than dimension, use::
+
+ transpose(nonzero(a))
+
+ The result of this is always a 2-D array, with a row for
+ each non-zero element.
Parameters
----------
- a : {array_like}
+ a : array_like
+ Input array.
Returns
-------
- tuple_of_arrays : {tuple}
+ tuple_of_arrays : tuple
+ Indices of elements that are non-zero.
+
+ See Also
+ --------
+ flatnonzero :
+ Return indices that are non-zero in the flattened version of the input
+ array.
Examples
--------
- >>> np.eye(3)[np.nonzero(np.eye(3))]
- array([ 1., 1., 1.])
- >>> np.nonzero(np.eye(3))
+ >>> x = np.eye(3)
+ >>> x
+ array([[ 1., 0., 0.],
+ [ 0., 1., 0.],
+ [ 0., 0., 1.]])
+ >>> np.nonzero(x)
(array([0, 1, 2]), array([0, 1, 2]))
- >>> np.eye(3)[np.nonzero(np.eye(3))]
+
+ >>> x[np.nonzero(x)]
array([ 1., 1., 1.])
+ >>> np.transpose(np.nonzero(x))
+ array([[0, 0],
+ [1, 1],
+ [2, 2]])
"""
try:
@@ -820,19 +964,23 @@ def nonzero(a):
def shape(a):
- """Return the shape of a.
+ """
+ Return the shape of an array.
Parameters
----------
- a : {array_like}
- Array whose shape is desired. If a is not an array, a conversion is
- attempted.
+ a : array_like
+ Input array.
Returns
-------
- tuple_of_integers :
- The elements of the tuple are the length of the corresponding array
- dimension.
+ shape : tuple
+ The elements of the tuple give the lengths of the corresponding array
+ dimensions.
+
+ See Also
+ --------
+ ndarray.shape : array method
Examples
--------
@@ -840,6 +988,16 @@ def shape(a):
(3, 3)
>>> np.shape([[1,2]])
(1, 2)
+ >>> np.shape([0])
+ (1,)
+ >>> np.shape(0)
+ ()
+
+ >>> x = np.array([(1,2),(3,4)], dtype=[('x', 'i4'), ('y', 'i4')])
+ >>> np.shape(x)
+ (2,)
+ >>> x.shape
+ (2,)
"""
try:
@@ -850,7 +1008,8 @@ def shape(a):
def compress(condition, a, axis=None, out=None):
- """Return selected slices of an array along given axis.
+ """
+ Return selected slices of an array along given axis.
Parameters
----------
@@ -869,7 +1028,8 @@ def compress(condition, a, axis=None, out=None):
Returns
-------
compressed_array : array
- A copy of a, without the slices along axis for which condition is false.
+ A copy of `a` without the slices along axis for which `condition`
+ is false.
Examples
--------
@@ -891,25 +1051,34 @@ def compress(condition, a, axis=None, out=None):
def clip(a, a_min, a_max, out=None):
- """Return an array whose values are limited to [a_min, a_max].
+ """
+ Clip (limit) the values in an array.
+
+ Given an interval, values outside the interval are clipped to
+ the interval edges. For example, if an interval of ``[0, 1]``
+ is specified, values smaller than 0 become 0, and values larger
+ than 1 become 1.
Parameters
----------
- a : {array_like}
+ a : array_like
Array containing elements to clip.
- a_min :
- Minimum value
- a_max :
- Maximum value
- out : array, optional
- The results will be placed in this array. It may be the input array for
- inplace clipping.
+ a_min : scalar or array_like
+ Minimum value.
+ a_max : scalar or array_like
+ Maximum value. If `a_min` or `a_max` are array_like, then they will
+ be broadcasted to the shape of `a`.
+ out : ndarray, optional
+ The results will be placed in this array. It may be the input
+ array for in-place clipping. `out` must be of the right shape
+ to hold the output. Its type is preserved.
Returns
-------
- clipped_array : {array}
- A new array whose elements are same as for a, but values
- < a_min are replaced with a_min, and > a_max with a_max.
+ clipped_array : ndarray
+ An array with the elements of `a`, but where values
+ < `a_min` are replaced with `a_min`, and those > `a_max`
+ with `a_max`.
Examples
--------
@@ -922,6 +1091,8 @@ def clip(a, a_min, a_max, out=None):
array([3, 3, 3, 3, 4, 5, 6, 6, 6, 6])
>>> a
array([3, 3, 3, 3, 4, 5, 6, 6, 6, 6])
+ >>> np.clip(a, [3,4,1,1,1,4,4,4,4,4], 8)
+ array([3, 4, 2, 3, 4, 5, 6, 7, 8, 8])
"""
try:
@@ -932,37 +1103,45 @@ def clip(a, a_min, a_max, out=None):
def sum(a, axis=None, dtype=None, out=None):
- """Return the sum of the array elements over the given axis
+ """
+ Return the sum of array elements over a given axis.
Parameters
----------
- a : {array_type}
- Array containing elements whose sum is desired. If a is not an array, a
- conversion is attempted.
- axis : {None, integer}
- Axis over which the sum is taken. If None is used, then the sum is
- over all the array elements.
- dtype : {None, dtype}, optional
- Determines the type of the returned array and of the accumulator
- where the elements are summed. If dtype has the value None and the
- type of a is an integer type of precision less than the default
- platform integer, then the default platform integer precision is
- used. Otherwise, the dtype is the same as that of a.
- out : {None, array}, optional
- Array into which the sum can be placed. Its type is preserved and
- it must be of the right shape to hold the output.
+ a : array_like
+ Elements to sum.
+ axis : integer, optional
+ Axis over which the sum is taken. By default `axis` is None,
+ and all elements are summed.
+ dtype : dtype, optional
+ The type of the returned array and of the accumulator in which
+ the elements are summed. By default, the dtype of `a` is used.
+ An exception is when `a` has an integer type with less precision
+ than the default platform integer. In that case, the default
+ platform integer is used instead.
+ out : ndarray, optional
+ Array into which the output is placed. By default, a new array is
+ created. If `out` is given, it must be of the appropriate shape
+ (the shape of `a` with `axis` removed, i.e.,
+ ``numpy.delete(a.shape, axis)``). Its type is preserved.
Returns
-------
- sum_along_axis : {array, scalar}, see dtype parameter above.
- Returns an array whose shape is the same as a with the specified
- axis removed. Returns a 0d array when a is 1d or axis=None.
- Returns a reference to the specified output array if specified.
+ sum_along_axis : ndarray or scalar
+ An array with the same shape as `a`, with the specified
+ axis removed. If `a` is a 0-d array, or if `axis` is None, a scalar
+ is returned. If an output array is specified, a reference to
+ `out` is returned.
See Also
--------
ndarray.sum : equivalent method
+ Notes
+ -----
+ Arithmetic is modular when using integer types, and no error is
+ raised on overflow.
+
Examples
--------
>>> np.sum([0.5, 1.5])
@@ -973,13 +1152,11 @@ def sum(a, axis=None, dtype=None, out=None):
6
>>> np.sum([[0, 1], [0, 5]], axis=1)
array([1, 5])
- >>> np.ones(128, dtype=np.int8).sum(dtype=np.int8) # overflow!
- -128
- Notes
- -----
- Arithmetic is modular when using integer types, and no error is
- raised on overflow.
+ If the accumulator is too small, overflow occurs:
+
+ >>> np.ones(128, dtype=np.int8).sum(dtype=np.int8)
+ -128
"""
if isinstance(a, _gentype):
@@ -996,53 +1173,14 @@ def sum(a, axis=None, dtype=None, out=None):
def product (a, axis=None, dtype=None, out=None):
- """Return the product of the array elements over the given axis
-
- Parameters
- ----------
- a : {array_like}
- Array containing elements whose product is desired. If a is not an array, a
- conversion is attempted.
- axis : {None, integer}
- Axis over which the product is taken. If None is used, then the
- product is over all the array elements.
- dtype : {None, dtype}, optional
- Determines the type of the returned array and of the accumulator
- where the elements are multiplied. If dtype has the value None and
- the type of a is an integer type of precision less than the default
- platform integer, then the default platform integer precision is
- used. Otherwise, the dtype is the same as that of a.
- out : {None, array}, optional
- Alternative output array in which to place the result. It must have
- the same shape as the expected output but the type will be cast if
- necessary.
+ """
+ Return the product of array elements over a given axis.
- Returns
- -------
- product_along_axis : {array, scalar}, see dtype parameter above.
- Returns an array whose shape is the same as a with the specified
- axis removed. Returns a 0d array when a is 1d or axis=None.
- Returns a reference to the specified output array if specified.
+ Refer to `numpy.prod` for full documentation.
See Also
--------
- ndarray.prod : equivalent method
-
- Examples
- --------
- >>> np.product([1.,2.])
- 2.0
- >>> np.product([1.,2.], dtype=np.int32)
- 2
- >>> np.product([[1.,2.],[3.,4.]])
- 24.0
- >>> np.product([[1.,2.],[3.,4.]], axis=1)
- array([ 2., 12.])
-
- Notes
- -----
- Arithmetic is modular when using integer types, and no error is
- raised on overflow.
+ prod : equivalent function
"""
try:
@@ -1054,33 +1192,13 @@ def product (a, axis=None, dtype=None, out=None):
def sometrue(a, axis=None, out=None):
"""
- Assert whether some values are true.
-
- `sometrue` performs a logical_or over the given axis.
+ Check whether some values are true.
- Parameters
- ----------
- a : array_like
- Array on which to operate.
- axis : {None, integer}
- Axis to perform the operation over.
- If `None` (default), perform over flattened array.
- out : {None, array}, optional
- Array into which the product can be placed. Its type is preserved
- and it must be of the right shape to hold the output.
+ Refer to `any` for full documentation.
See Also
--------
- ndarray.any : equivalent method
-
- Examples
- --------
- >>> b = np.array([True, False, True, True])
- >>> np.sometrue(b)
- True
- >>> a = np.array([1, 5, 2, 7])
- >>> np.sometrue(a >= 5)
- True
+ any : equivalent function
"""
try:
@@ -1091,23 +1209,15 @@ def sometrue(a, axis=None, out=None):
def alltrue (a, axis=None, out=None):
- """Check if all of the elements of `a` are true.
-
- Performs a logical_and over the given axis and returns the result
+ """
+ Check if all of the elements of `a` are true.
- Parameters
- ----------
- a : array_like
- axis : {None, integer}
- Axis to perform the operation over.
- If None, perform over flattened array.
- out : {None, array}, optional
- Array into which the product can be placed. Its type is preserved
- and it must be of the right shape to hold the output.
+ Please refer to the `numpy.all` documentation. `numpy.all` is
+ the same function.
See Also
--------
- ndarray.all : equivalent method
+ numpy.all : equivalent function
"""
try:
@@ -1118,24 +1228,48 @@ def alltrue (a, axis=None, out=None):
def any(a,axis=None, out=None):
- """Check if any of the elements of `a` are true.
-
- Performs a logical_or over the given axis and returns the result
+ """
+ Test whether any elements of an array evaluate to true along a given axis.
Parameters
----------
a : array_like
- axis : {None, integer}
- Axis to perform the operation over.
- If None, perform over flattened array and return a scalar.
- out : {None, array}, optional
- Array into which the product can be placed. Its type is preserved
+ Input array.
+ axis : int, optional
+ Axis over which to perform the operation.
+ If None, use a flattened input array and return a bool.
+ out : ndarray, optional
+ Array into which the result is placed. Its type is preserved
and it must be of the right shape to hold the output.
+ Returns
+ -------
+ out : ndarray
+ A logical OR is performed along `axis`, and the result placed
+ in `out`. If `out` was not specified, a new output array is created.
+
See Also
--------
ndarray.any : equivalent method
+ Notes
+ -----
+ Since NaN is not equal to zero, NaN evaluates to True.
+
+ Examples
+ --------
+ >>> np.any([[True, False], [True, True]])
+ True
+
+ >>> np.any([[True, False], [False, False]], axis=0)
+ array([ True, False], dtype=bool)
+
+ >>> np.any([-1, 0, 5])
+ True
+
+ >>> np.any(np.nan)
+ True
+
"""
try:
any = a.any
@@ -1145,24 +1279,48 @@ def any(a,axis=None, out=None):
def all(a,axis=None, out=None):
- """Check if all of the elements of `a` are true.
-
- Performs a logical_and over the given axis and returns the result
+ """
+ Test whether all elements of an array evaluate to true along a given axis.
Parameters
----------
a : array_like
- axis : {None, integer}
- Axis to perform the operation over.
- If None, perform over flattened array and return a scalar.
- out : {None, array}, optional
- Array into which the product can be placed. Its type is preserved
+ Input array.
+ axis : int, optional
+ Axis over which to perform the operation.
+ If None, use a flattened input array and return a bool.
+ out : ndarray, optional
+ Array into which the result is placed. Its type is preserved
and it must be of the right shape to hold the output.
+ Returns
+ -------
+ out : ndarray
+ A logical AND is performed along `axis`, and the result placed
+ in `out`. If `out` was not specified, a new output array is created.
+
See Also
--------
ndarray.all : equivalent method
+ Notes
+ -----
+ Since NaN is not equal to zero, NaN evaluates to True.
+
+ Examples
+ --------
+ >>> np.all([[True,False],[True,True]])
+ False
+
+ >>> np.all([[True,False],[True,True]], axis=0)
+ array([ True, False], dtype=bool)
+
+ >>> np.all([-1, 4, 5])
+ True
+
+ >>> np.all([1.0, np.nan])
+ True
+
"""
try:
all = a.all
@@ -1179,10 +1337,12 @@ def cumsum (a, axis=None, dtype=None, out=None):
----------
a : array-like
Input array or object that can be converted to an array.
- axis : {None, -1, int}, optional
- Axis along which the sum is computed. The default
- (`axis` = `None`) is to compute over the flattened array.
- dtype : {None, dtype}, optional
+ axis : int, optional
+ Axis along which the cumulative sum is computed. The default
+ (`axis` = `None`) is to compute the cumsum over the flattened
+ array. `axis` may be negative, in which case it counts from the
+ last to the first axis.
+ dtype : dtype, optional
Type of the returned array and of the accumulator in which the
elements are summed. If `dtype` is not specified, it defaults
to the dtype of `a`, unless `a` has an integer dtype with a
@@ -1204,11 +1364,10 @@ def cumsum (a, axis=None, dtype=None, out=None):
Arithmetic is modular when using integer types, and no error is
raised on overflow.
-
Examples
--------
- >>> a=np.array([[1,2,3],[4,5,6]])
- >>> np.cumsum(a) # cumulative sum = intermediate summing results & total sum. Default axis=None results in raveling the array first.
+ >>> a = np.array([[1,2,3],[4,5,6]])
+ >>> np.cumsum(a)
array([ 1, 3, 6, 10, 15, 21])
>>> np.cumsum(a,dtype=float) # specifies type of output value(s)
array([ 1., 3., 6., 10., 15., 21.])
@@ -1228,7 +1387,10 @@ def cumsum (a, axis=None, dtype=None, out=None):
def cumproduct(a, axis=None, dtype=None, out=None):
- """Return the cumulative product over the given axis.
+ """
+ Return the cumulative product over the given axis.
+
+ See `cumprod` for full documentation.
See Also
--------
@@ -1243,26 +1405,26 @@ def cumproduct(a, axis=None, dtype=None, out=None):
def ptp(a, axis=None, out=None):
- """Return (maximum - minimum) along the the given dimension
- (i.e. peak-to-peak value).
+ """
+ Peak to peak (maximum - minimum) value along a given axis.
Parameters
----------
a : array_like
Input values.
- axis : {None, int}, optional
- Axis along which to find the peaks. If None (default) the
- flattened array is used.
+ axis : int, optional
+ Axis along which to find the peaks. By default, flatten the
+ array.
out : array_like
Alternative output array in which to place the result. It must
- have the same shape and buffer length as the expected output
- but the type will be cast if necessary.
+ have the same shape and buffer length as the expected output,
+ but the type of the output values will be cast if necessary.
Returns
-------
- ptp : ndarray.
- A new array holding the result, unless ``out`` was
- specified, in which case a reference to ``out`` is returned.
+ ptp : ndarray
+ A new array holding the result, unless `out` was
+ specified, in which case a reference to `out` is returned.
Examples
--------
@@ -1270,9 +1432,11 @@ def ptp(a, axis=None, out=None):
>>> x
array([[0, 1],
[2, 3]])
- >>> np.ptp(x,0)
+
+ >>> np.ptp(x, axis=0)
array([2, 2])
- >>> np.ptp(x,1)
+
+ >>> np.ptp(x, axis=1)
array([1, 1])
"""
@@ -1284,23 +1448,24 @@ def ptp(a, axis=None, out=None):
def amax(a, axis=None, out=None):
- """Return the maximum along a given axis.
+ """
+ Return the maximum along a given axis.
Parameters
----------
a : array_like
Input data.
- axis : {None, int}, optional
- Axis along which to operate. By default, ``axis`` is None and the
- flattened input is used.
- out : array_like, optional
+ axis : int, optional
+ Axis along which to operate. By default flattened input is used.
+ out : ndarray, optional
Alternative output array in which to place the result. Must
be of the same shape and buffer length as the expected output.
Returns
-------
- amax : array_like
- New array holding the result, unless ``out`` was specified.
+ amax : {ndarray, scalar}
+ A new array or a scalar with the result, or a reference to `out`
+ if it was specified.
Examples
--------
@@ -1322,23 +1487,24 @@ def amax(a, axis=None, out=None):
def amin(a, axis=None, out=None):
- """Return the minimum along a given axis.
+ """
+ Return the minimum along a given axis.
Parameters
----------
a : array_like
Input data.
- axis : {None, int}, optional
- Axis along which to operate. By default, ``axis`` is None and the
- flattened input is used.
- out : array_like, optional
+ axis : int, optional
+ Axis along which to operate. By default a flattened input is used.
+ out : ndarray, optional
Alternative output array in which to place the result. Must
be of the same shape and buffer length as the expected output.
Returns
-------
- amin : array_like
- New array holding the result, unless ``out`` was specified.
+ amin : {ndarray, scalar}
+ A new array or a scalar with the result, or a reference to `out` if it
+ was specified.
Examples
--------
@@ -1361,12 +1527,12 @@ def amin(a, axis=None, out=None):
def alen(a):
"""
- Return the length of a Python object interpreted as an array
- of at least 1 dimension.
+ Return the length of an array_like as an array of at least 1 dimension.
Parameters
----------
a : array_like
+ Input array.
Returns
-------
@@ -1389,53 +1555,74 @@ def alen(a):
def prod(a, axis=None, dtype=None, out=None):
- """Return the product of the array elements over the given axis
+ """
+ Return the product of array elements over a given axis.
Parameters
----------
- a : {array_like}
- Array containing elements whose product is desired. If a is not an array, a
- conversion is attempted.
- axis : {None, integer}
- Axis over which the product is taken. If None is used, then the
- product is over all the array elements.
- dtype : {None, dtype}, optional
- Determines the type of the returned array and of the accumulator
- where the elements are multiplied. If dtype has the value None and
- the type of a is an integer type of precision less than the default
- platform integer, then the default platform integer precision is
- used. Otherwise, the dtype is the same as that of a.
- out : {None, array}, optional
+ a : array_like
+ Input data.
+ axis : int, optional
+ Axis over which the product is taken. By default, the product
+ of all elements is calculated.
+ dtype : data-type, optional
+ The data-type of the returned array, as well as of the accumulator
+ in which the elements are multiplied. By default, if `a` is of
+ integer type, `dtype` is the default platform integer (note: if
+ the type of `a` is unsigned, then so is `dtype`). Otherwise,
+ the dtype is the same as that of `a`.
+ out : ndarray, optional
Alternative output array in which to place the result. It must have
- the same shape as the expected output but the type will be cast if
- necessary.
+ the same shape as the expected output, but the type of the
+ output values will be cast if necessary.
Returns
-------
- product_along_axis : {array, scalar}, see dtype parameter above.
- Returns an array whose shape is the same as a with the specified
- axis removed. Returns a 0d array when a is 1d or axis=None.
- Returns a reference to the specified output array if specified.
+ product_along_axis : {ndarray, scalar}, see `dtype` parameter above.
+ An array shaped as `a` but with the specified axis removed.
+ Returns a reference to `out` if specified.
See Also
--------
ndarray.prod : equivalent method
+ Notes
+ -----
+ Arithmetic is modular when using integer types, and no error is
+ raised on overflow. That means that, on a 32-bit platform:
+
+ >>> x = np.array([536870910, 536870910, 536870910, 536870910])
+ >>> np.prod(x) #random
+ 16
+
Examples
--------
+ By default, calculate the product of all elements:
+
>>> np.prod([1.,2.])
2.0
- >>> np.prod([1.,2.], dtype=np.int32)
- 2
+
+ Even when the input array is two-dimensional:
+
>>> np.prod([[1.,2.],[3.,4.]])
24.0
+
+ But we can also specify the axis over which to multiply:
+
>>> np.prod([[1.,2.],[3.,4.]], axis=1)
array([ 2., 12.])
- Notes
- -----
- Arithmetic is modular when using integer types, and no error is
- raised on overflow.
+ If the type of `x` is unsigned, then the output type is
+ the unsigned platform integer:
+
+ >>> x = np.array([1, 2, 3], dtype=np.uint8)
+ >>> np.prod(x).dtype == np.uint
+
+ If `x` is of a signed integer type, then the output type
+ is the default platform integer:
+
+ >>> x = np.array([1, 2, 3], dtype=np.int8)
+ >>> np.prod(x).dtype == np.int
"""
try:
@@ -1447,28 +1634,25 @@ def prod(a, axis=None, dtype=None, out=None):
def cumprod(a, axis=None, dtype=None, out=None):
"""
- Return the cumulative product of the elements along the given axis.
-
- The cumulative product is taken over the flattened array by
- default, otherwise over the specified axis.
+ Return the cumulative product of elements along a given axis.
Parameters
----------
a : array-like
- Input array or object that can be converted to an array.
- axis : {None, -1, int}, optional
- Axis along which the product is computed. The default
- (`axis` = `None`) is to compute over the flattened array.
- dtype : {None, dtype}, optional
- Type of the returned array and of the accumulator
- where the elements are multiplied. If `dtype` has the value `None` and
- the type of `a` is an integer type of precision less than the default
- platform integer, then the default platform integer precision is
- used. Otherwise, the `dtype` is the same as that of `a`.
+ Input array.
+ axis : int, optional
+ Axis along which the cumulative product is computed. By default the
+ input is flattened.
+ dtype : dtype, optional
+ Type of the returned array, as well as of the accumulator in which
+ the elements are multiplied. If dtype is not specified, it defaults
+ to the dtype of `a`, unless `a` has an integer dtype with a precision
+ less than that of the default platform integer. In that case, the
+ default platform integer is used instead.
out : ndarray, optional
Alternative output array in which to place the result. It must
have the same shape and buffer length as the expected output
- but the type will be cast if necessary.
+ but the type of the resulting values will be cast if necessary.
Returns
-------
@@ -1483,20 +1667,25 @@ def cumprod(a, axis=None, dtype=None, out=None):
Examples
--------
- >>> a=np.array([[1,2,3],[4,5,6]])
- >>> a=np.array([1,2,3])
+ >>> a = np.array([1,2,3])
>>> np.cumprod(a) # intermediate results 1, 1*2
- ... # total product 1*2*3 = 6
+ ... # total product 1*2*3 = 6
array([1, 2, 6])
- >>> a=np.array([[1,2,3],[4,5,6]])
- >>> np.cumprod(a,dtype=float) # specify type of output
+ >>> a = np.array([[1, 2, 3], [4, 5, 6]])
+ >>> np.cumprod(a, dtype=float) # specify type of output
array([ 1., 2., 6., 24., 120., 720.])
- >>> np.cumprod(a,axis=0) # for each of the 3 columns:
- ... # product and intermediate results
+
+ The cumulative product for each column (i.e., over the rows of)
+ `a`:
+
+ >>> np.cumprod(a, axis=0)
array([[ 1, 2, 3],
[ 4, 10, 18]])
- >>> np.cumprod(a,axis=1) # for each of the two rows:
- ... # product and intermediate results
+
+ The cumulative product for each row (i.e. over the columns of)
+ `a`:
+
+ >>> np.cumprod(a,axis=1)
array([[ 1, 2, 6],
[ 4, 20, 120]])
@@ -1509,25 +1698,22 @@ def cumprod(a, axis=None, dtype=None, out=None):
def ndim(a):
- """Return the number of dimensions of a.
-
- If a is not already an array, a conversion is attempted. Scalars are zero
- dimensional.
+ """
+ Return the number of dimensions of an array.
Parameters
----------
- a : {array_like}
- Array whose number of dimensions are desired. If a is not an
- array, a conversion is attempted.
+ a : array_like
+ Input array. If it is not already an ndarray, a conversion is
+ attempted.
Returns
-------
- number_of_dimensions : {integer}
- Returns the number of dimensions.
+ number_of_dimensions : int
+ The number of dimensions in `a`. Scalars are zero-dimensional.
See Also
--------
- rank : equivalent function.
ndarray.ndim : equivalent method
shape : dimensions of array
ndarray.shape : dimensions of array
@@ -1549,34 +1735,39 @@ def ndim(a):
def rank(a):
- """Return the number of dimensions of a.
+ """
+ Return the number of dimensions of an array.
- In old Numeric, rank was the term used for the number of dimensions. If a is
- not already an array, a conversion is attempted. Scalars are zero
- dimensional.
+ If `a` is not already an array, a conversion is attempted.
+ Scalars are zero dimensional.
Parameters
----------
- a : {array_like}
- Array whose number of dimensions is desired. If a is not an array, a
- conversion is attempted.
+ a : array_like
+ Array whose number of dimensions is desired. If `a` is not an array,
+ a conversion is attempted.
Returns
-------
- number_of_dimensions : {integer}
- Returns the number of dimensions.
+ number_of_dimensions : int
+ The number of dimensions in the array.
See Also
--------
ndim : equivalent function
- ndarray.ndim : equivalent method
+ ndarray.ndim : equivalent property
shape : dimensions of array
ndarray.shape : dimensions of array
+ Notes
+ -----
+ In the old Numeric package, `rank` was the term used for the number of
+ dimensions, but in Numpy `ndim` is used instead.
+
Examples
--------
- >>> np.rank([[1,2,3],[4,5,6]])
- 2
+ >>> np.rank([1,2,3])
+ 1
>>> np.rank(np.array([[1,2,3],[4,5,6]]))
2
>>> np.rank(1)
@@ -1590,21 +1781,21 @@ def rank(a):
def size(a, axis=None):
- """Return the number of elements along given axis.
+ """
+ Return the number of elements along a given axis.
Parameters
----------
- a : {array_like}
- Array whose axis size is desired. If a is not an array, a
- conversion is attempted.
- axis : {None, integer}, optional
- Axis along which the elements are counted. None means all
- elements in the array.
+ a : array_like
+ Input data.
+ axis : int, optional
+ Axis along which the elements are counted. By default, give
+ the total number of elements.
Returns
-------
- element_count : {integer}
- Count of elements along specified axis.
+ element_count : int
+ Number of elements along the specified axis.
See Also
--------
@@ -1636,44 +1827,52 @@ def size(a, axis=None):
def around(a, decimals=0, out=None):
- """Round a to the given number of decimals.
-
- The real and imaginary parts of complex numbers are rounded separately. The
- result of rounding a float is a float so the type must be cast if integers
- are desired. Nothing is done if the input is an integer array and the
- decimals parameter has a value >= 0.
+ """
+ Evenly round to the given number of decimals.
Parameters
----------
- a : {array_like}
- Array containing numbers whose rounded values are desired. If a is
- not an array, a conversion is attempted.
- decimals : {0, int}, optional
- Number of decimal places to round to. When decimals is negative it
- specifies the number of positions to the left of the decimal point.
- out : {None, array}, optional
+ a : array_like
+ Input data.
+ decimals : int, optional
+ Number of decimal places to round to (default: 0). If
+ decimals is negative, it specifies the number of positions to
+ the left of the decimal point.
+ out : ndarray, optional
Alternative output array in which to place the result. It must have
- the same shape as the expected output but the type will be cast if
- necessary. Numpy rounds floats to floats by default.
+ the same shape as the expected output, but the type of the output
+ values will be cast if necessary.
Returns
-------
rounded_array : {array}
- If out=None, returns a new array of the same type as a containing
- the rounded values, otherwise a reference to the output array is
- returned.
+ An array of the same type as `a`, containing the rounded values.
+ Unless `a` was specified, a new array is created. A reference to
+ the result is returned.
+
+ The real and imaginary parts of complex numbers are rounded
+ separately. The result of rounding a float is a float.
See Also
--------
- round_ : equivalent function
ndarray.round : equivalent method
Notes
-----
- Numpy rounds to even. Thus 1.5 and 2.5 round to 2.0, -0.5 and 0.5 round
- to 0.0, etc. Results may also be surprising due to the inexact
- representation of decimal fractions in IEEE floating point and the
- errors introduced when scaling by powers of ten.
+ For values exactly halfway between rounded decimal values, Numpy
+ rounds to the nearest even value. Thus 1.5 and 2.5 round to 2.0,
+ -0.5 and 0.5 round to 0.0, etc. Results may also be surprising due
+ to the inexact representation of decimal fractions in the IEEE
+ floating point standard [1]_ and errors introduced when scaling
+ by powers of ten.
+
+ References
+ ----------
+ .. [1] "Lecture Notes on the Status of IEEE 754", William Kahan,
+ http://www.cs.berkeley.edu/~wkahan/ieee754status/IEEE754.PDF
+ .. [2] "How Futile are Mindless Assessments of
+ Roundoff in Floating-Point Computation?", William Kahan,
+ http://www.cs.berkeley.edu/~wkahan/Mindless.pdf
Examples
--------
@@ -1693,53 +1892,14 @@ def around(a, decimals=0, out=None):
def round_(a, decimals=0, out=None):
- """Round a to the given number of decimals.
-
- The real and imaginary parts of complex numbers are rounded separately. The
- result of rounding a float is a float so the type must be cast if integers
- are desired. Nothing is done if the input is an integer array and the
- decimals parameter has a value >= 0.
-
- Parameters
- ----------
- a : {array_like}
- Array containing numbers whose rounded values are desired. If a is
- not an array, a conversion is attempted.
- decimals : {0, integer}, optional
- Number of decimal places to round to. When decimals is negative it
- specifies the number of positions to the left of the decimal point.
- out : {None, array}, optional
- Alternative output array in which to place the result. It must have
- the same shape as the expected output but the type will be cast if
- necessary.
+ """
+ Round an array to the given number of decimals.
- Returns
- -------
- rounded_array : {array}
- If out=None, returns a new array of the same type as a containing
- the rounded values, otherwise a reference to the output array is
- returned.
+ Refer to `around` for full documentation.
See Also
--------
around : equivalent function
- ndarray.round : equivalent method
-
- Notes
- -----
- Numpy rounds to even. Thus 1.5 and 2.5 round to 2.0, -0.5 and 0.5 round
- to 0.0, etc. Results may also be surprising due to the inexact
- representation of decimal fractions in IEEE floating point and the
- errors introduced when scaling by powers of ten.
-
- Examples
- --------
- >>> np.round_([.5, 1.5, 2.5, 3.5, 4.5])
- array([ 0., 2., 2., 4., 4.])
- >>> np.round_([1,2,3,11], decimals=1)
- array([ 1, 2, 3, 11])
- >>> np.round_([1,2,3,11], decimals=-1)
- array([ 0, 0, 0, 10])
"""
try:
@@ -1750,33 +1910,35 @@ def round_(a, decimals=0, out=None):
def mean(a, axis=None, dtype=None, out=None):
- """Compute the mean along the specified axis.
+ """
+ Compute the arithmetic mean along the specified axis.
Returns the average of the array elements. The average is taken
over the flattened array by default, otherwise over the specified
- axis. The dtype returned for integer type arrays is float.
+ axis. float64 intermediate and return values are used for integer
+ inputs.
Parameters
----------
- a : {array_like}
- Array containing numbers whose mean is desired. If a is not an
+ a : array_like
+ Array containing numbers whose mean is desired. If `a` is not an
array, a conversion is attempted.
- axis : {None, integer}, optional
+ axis : {None, int}, optional
Axis along which the means are computed. The default is to compute
the mean of the flattened array.
dtype : {None, dtype}, optional
- Type to use in computing the mean. For arrays of integer type the
- default is float32, for arrays of float types it is the same as the
- array type.
- out : {None, array}, optional
+ Type to use in computing the mean. For integer inputs the default
+ is float64; for floating point inputs it is the same as the input
+ dtype.
+ out : {None, ndarray}, optional
Alternative output array in which to place the result. It must have
the same shape as the expected output but the type will be cast if
necessary.
Returns
-------
- mean : {array, scalar}, see dtype parameter above
- If out=None, returns a new array containing the mean values,
+ mean : {ndarray, scalar}, see dtype parameter above
+ If `out=None`, returns a new array containing the mean values,
otherwise a reference to the output array is returned.
See Also
@@ -1785,8 +1947,8 @@ def mean(a, axis=None, dtype=None, out=None):
Notes
-----
- The mean is the sum of the elements along the axis divided by the
- number of elements.
+ The arithmetic mean is the sum of the elements along the axis divided
+ by the number of elements.
Examples
--------
@@ -1807,60 +1969,64 @@ def mean(a, axis=None, dtype=None, out=None):
def std(a, axis=None, dtype=None, out=None, ddof=0):
- """Compute the standard deviation along the specified axis.
+ """
+ Compute the standard deviation along the specified axis.
- Returns the standard deviation of the array elements, a measure of the
- spread of a distribution. The standard deviation is computed for the
+ Returns the standard deviation, a measure of the spread of a distribution,
+ of the array elements. The standard deviation is computed for the
flattened array by default, otherwise over the specified axis.
Parameters
----------
- a : {array_like}
- Array containing numbers whose standard deviation is desired. If a
- is not an array, a conversion is attempted.
- axis : {None, integer}, optional
+ a : array_like
+ Calculate the standard deviation of these values.
+ axis : int, optional
Axis along which the standard deviation is computed. The default is
to compute the standard deviation of the flattened array.
- dtype : {None, dtype}, optional
+ dtype : dtype, optional
Type to use in computing the standard deviation. For arrays of
- integer type the default is float32, for arrays of float types it is
+ integer type the default is float64, for arrays of float types it is
the same as the array type.
- out : {None, array}, optional
+ out : ndarray, optional
Alternative output array in which to place the result. It must have
- the same shape as the expected output but the type will be cast if
- necessary.
- ddof : {0, integer}
+ the same shape as the expected output but the type (of the calculated
+ values) will be cast if necessary.
+ ddof : int, optional
Means Delta Degrees of Freedom. The divisor used in calculations
- is N-ddof.
+ is ``N - ddof``, where ``N`` represents the number of elements.
+ By default `ddof` is zero (biased estimate).
Returns
-------
- standard_deviation : {array, scalar}, see dtype parameter above.
- If out=None, returns a new array containing the standard deviation,
- otherwise a reference to the output array is returned.
+ standard_deviation : {ndarray, scalar}; see dtype parameter above.
+ If `out` is None, return a new array containing the standard deviation,
+ otherwise return a reference to the output array.
See Also
--------
- var : Variance
- mean : Average
+ numpy.var : Variance
+ numpy.mean : Average
Notes
-----
The standard deviation is the square root of the average of the squared
- deviations from the mean, i.e. var = sqrt(mean(abs(x - x.mean())**2)).
- The computed standard deviation is computed by dividing by the number of
- elements, N-ddof. The option ddof defaults to zero, that is, a
- biased estimate. Note that for complex numbers std takes the absolute
+ deviations from the mean, i.e., ``var = sqrt(mean(abs(x - x.mean())**2))``.
+
+ The mean is normally calculated as ``x.sum() / N``, where
+ ``N = len(x)``. If, however, `ddof` is specified, the divisor ``N - ddof``
+ is used instead.
+
+ Note that, for complex numbers, std takes the absolute
value before squaring, so that the result is always real and nonnegative.
Examples
--------
- >>> a = np.array([[1,2],[3,4]])
+ >>> a = np.array([[1, 2], [3, 4]])
>>> np.std(a)
1.1180339887498949
- >>> np.std(a,0)
+ >>> np.std(a, 0)
array([ 1., 1.])
- >>> np.std(a,1)
+ >>> np.std(a, 1)
array([ 0.5, 0.5])
"""
@@ -1872,7 +2038,8 @@ def std(a, axis=None, dtype=None, out=None, ddof=0):
def var(a, axis=None, dtype=None, out=None, ddof=0):
- """Compute the variance along the specified axis.
+ """
+ Compute the variance along the specified axis.
Returns the variance of the array elements, a measure of the spread of a
distribution. The variance is computed for the flattened array by default,
@@ -1880,27 +2047,27 @@ def var(a, axis=None, dtype=None, out=None, ddof=0):
Parameters
----------
- a : {array_like}
+ a : array_like
Array containing numbers whose variance is desired. If a is not an
array, a conversion is attempted.
- axis : {None, integer}, optional
+ axis : int, optional
Axis along which the variance is computed. The default is to compute
the variance of the flattened array.
- dtype : {None, dtype}, optional
+ dtype : dtype, optional
Type to use in computing the variance. For arrays of integer type
the default is float32, for arrays of float types it is the same as
the array type.
- out : {None, array}, optional
+ out : ndarray, optional
Alternative output array in which to place the result. It must have
the same shape as the expected output but the type will be cast if
necessary.
- ddof : {0, integer},
+ ddof : positive int,optional
Means Delta Degrees of Freedom. The divisor used in calculation is
N - ddof.
Returns
-------
- variance : {array, scalar}, see dtype parameter above
+ variance : {ndarray, scalar}, see dtype parameter above
If out=None, returns a new array containing the variance, otherwise
a reference to the output array is returned.