summaryrefslogtreecommitdiff
path: root/numpy
diff options
context:
space:
mode:
authorPauli Virtanen <pav@iki.fi>2009-10-02 19:36:37 +0000
committerPauli Virtanen <pav@iki.fi>2009-10-02 19:36:37 +0000
commit094a81e1352fb6b3a7a614fc8df23d0080cf7cb5 (patch)
tree0ec0b833b714ccf87085a43de363287edec5c7ee /numpy
parentd8f0614a886488b875e34555c590e6469e24102a (diff)
downloadnumpy-094a81e1352fb6b3a7a614fc8df23d0080cf7cb5.tar.gz
Docstring update: core
Diffstat (limited to 'numpy')
-rw-r--r--numpy/core/arrayprint.py4
-rw-r--r--numpy/core/code_generators/ufunc_docstrings.py294
-rw-r--r--numpy/core/defchararray.py469
-rw-r--r--numpy/core/fromnumeric.py225
-rw-r--r--numpy/core/getlimits.py10
-rw-r--r--numpy/core/machar.py26
-rw-r--r--numpy/core/memmap.py37
-rw-r--r--numpy/core/numeric.py313
-rw-r--r--numpy/core/numerictypes.py192
-rw-r--r--numpy/core/records.py67
10 files changed, 1382 insertions, 255 deletions
diff --git a/numpy/core/arrayprint.py b/numpy/core/arrayprint.py
index c8bc9438a..df5662b1b 100644
--- a/numpy/core/arrayprint.py
+++ b/numpy/core/arrayprint.py
@@ -125,9 +125,11 @@ def get_printoptions():
- nanstr : string
- infstr : string
+ For a full description of these options, see `set_printoptions`.
+
See Also
--------
- set_printoptions : parameter descriptions
+ set_printoptions, set_string_function
"""
d = dict(precision=_float_output_precision,
diff --git a/numpy/core/code_generators/ufunc_docstrings.py b/numpy/core/code_generators/ufunc_docstrings.py
index 5df2df53d..f536845cf 100644
--- a/numpy/core/code_generators/ufunc_docstrings.py
+++ b/numpy/core/code_generators/ufunc_docstrings.py
@@ -94,7 +94,8 @@ add_newdoc('numpy.core.umath', 'arccos',
For real arguments, the domain is [-1, 1].
out : ndarray, optional
- Array to store results in.
+ Array of the same shape as `a`, to store results in. See
+ `doc.ufuncs` (Section "Output arguments") for more details.
Returns
-------
@@ -106,7 +107,7 @@ add_newdoc('numpy.core.umath', 'arccos',
See Also
--------
- cos, arctan, arcsin
+ cos, arctan, arcsin, emath.arccos
Notes
-----
@@ -129,7 +130,7 @@ add_newdoc('numpy.core.umath', 'arccos',
.. [1] M. Abramowitz and I.A. Stegun, "Handbook of Mathematical Functions",
10th printing, 1964, pp. 79. http://www.math.sfu.ca/~cbm/aands/
.. [2] Wikipedia, "Inverse trigonometric function",
- http://en.wikipedia.org/wiki/Arccos
+ http://en.wikipedia.org/wiki/Inverse_trigonometric_function
Examples
--------
@@ -210,6 +211,10 @@ add_newdoc('numpy.core.umath', 'arcsin',
x : array_like
`y`-coordinate on the unit circle.
+ out : ndarray, optional
+ Array of the same shape as `x`, to store results in. See
+ `doc.ufuncs` (Section "Output arguments") for more details.
+
Returns
-------
angle : ndarray
@@ -219,7 +224,7 @@ add_newdoc('numpy.core.umath', 'arcsin',
See Also
--------
- sin, arctan, arctan2
+ sin, cos, arccos, tan, arctan, arctan2, emath.arcsin
Notes
-----
@@ -242,7 +247,7 @@ add_newdoc('numpy.core.umath', 'arcsin',
.. [1] M. Abramowitz and I.A. Stegun, "Handbook of Mathematical Functions",
10th printing, 1964, pp. 79. http://www.math.sfu.ca/~cbm/aands/
.. [2] Wikipedia, "Inverse trigonometric function",
- http://en.wikipedia.org/wiki/Arcsin
+ http://en.wikipedia.org/wiki/Inverse_trigonometric_function
Examples
--------
@@ -450,6 +455,10 @@ add_newdoc('numpy.core.umath', 'arctanh',
out : ndarray
Array of the same shape as `x`.
+ See Also
+ --------
+ emath.arctanh
+
Notes
-----
`arctanh` is a multivalued function: for each `x` there are infinitely
@@ -577,6 +586,8 @@ add_newdoc('numpy.core.umath', 'bitwise_or',
>>> np.bitwise_or(np.array([2, 5, 255]), np.array([4, 4, 4]))
array([ 6, 5, 255])
+ >>> np.array([2, 5, 255]) | np.array([4, 4, 4])
+ array([ 6, 5, 255])
>>> np.bitwise_or(np.array([2, 5, 255, 2147483647L], dtype=np.int32),
... np.array([4, 4, 4, 2147483647L], dtype=np.int32))
array([ 6, 5, 255, 2147483647])
@@ -649,7 +660,7 @@ add_newdoc('numpy.core.umath', 'ceil',
Returns
-------
y : {ndarray, scalar}
- The ceiling of each element in `x`.
+ The ceiling of each element in `x`, with `float` dtype.
See Also
--------
@@ -685,16 +696,16 @@ add_newdoc('numpy.core.umath', 'trunc',
--------
ceil, floor, rint
+ Notes
+ -----
+ .. versionadded:: 1.3.0
+
Examples
--------
>>> a = np.array([-1.7, -1.5, -0.2, 0.2, 1.5, 1.7, 2.0])
>>> np.trunc(a)
array([-1., -1., -0., 0., 1., 1., 2.])
- Notes
- -----
- .. versionadded:: 1.3.0
-
""")
add_newdoc('numpy.core.umath', 'conjugate',
@@ -804,9 +815,33 @@ add_newdoc('numpy.core.umath', 'degrees',
"""
Convert angles from radians to degrees.
+ Parameters
+ ----------
+ x : array_like
+ Input array in radians.
+ out : ndarray, optional
+ Output array of same shape as x.
+
+ Returns
+ -------
+ y : ndarray
+ The corresponding degree values.
+
See Also
--------
- rad2deg : equivalent function; see for documentation.
+ rad2deg : equivalent function
+
+ Examples
+ --------
+ Convert a radian array to degrees
+
+ >>> rad = np.arange(12.)*np.pi/6
+ >>> np.degrees(rad)
+ array([ 0., 30., 60., 90., 120., 150., 180., 210., 240.,
+ 270., 300., 330.])
+
+ >>> foo = np.zeros((rad.shape))
+ >>> degrees(rad, foo)
""")
@@ -1016,7 +1051,7 @@ add_newdoc('numpy.core.umath', 'exp2',
Input values.
out : ndarray, optional
- \tArray to insert results into.
+ Array to insert results into.
Returns
-------
@@ -1035,8 +1070,8 @@ add_newdoc('numpy.core.umath', 'exp2',
Examples
--------
- >>> np.exp2([2,3])
- array([4,9])
+ >>> np.exp2([2, 3])
+ array([ 4., 8.])
""")
@@ -1178,9 +1213,9 @@ add_newdoc('numpy.core.umath', 'floor_divide',
add_newdoc('numpy.core.umath', 'fmod',
"""
- Return the remainder of division.
+ Return the element-wise remainder of division.
- This is the NumPy implementation of the C modulo operator `%`.
+ This is the NumPy implementation of the Python modulo operator `%`.
Parameters
----------
@@ -1196,22 +1231,35 @@ add_newdoc('numpy.core.umath', 'fmod',
See Also
--------
- mod : Modulo operation where the quotient is `floor(x1,x2)`.
+ remainder : Modulo operation where the quotient is `floor(x1/x2)`.
+ divide
Notes
-----
The result of the modulo operation for negative dividend and divisors is
bound by conventions. In `fmod`, the sign of the remainder is the sign of
- the dividend, and the sign of the divisor has no influence on the results.
+ the dividend: in contrast to `remainder`, the sign of the divisor has no
+ influence on the sign of the result.
Examples
--------
>>> np.fmod([-3, -2, -1, 1, 2, 3], 2)
array([-1, 0, -1, 1, 0, 1])
-
- >>> np.mod([-3, -2, -1, 1, 2, 3], 2)
+ >>> np.remainder([-3, -2, -1, 1, 2, 3], 2)
array([1, 0, 1, 1, 0, 1])
+ >>> np.fmod([5, 3], [2, 2.])
+ array([ 1., 1.])
+ >>> a = np.arange(-3, 3).reshape(3, 2)
+ >>> a
+ array([[-3, -2],
+ [-1, 0],
+ [ 1, 2]])
+ >>> np.fmod(a, [2,2])
+ array([[-1, 0],
+ [-1, 0],
+ [ 1, 0]])
+
""")
add_newdoc('numpy.core.umath', 'greater',
@@ -1273,24 +1321,39 @@ add_newdoc('numpy.core.umath', 'greater_equal',
add_newdoc('numpy.core.umath', 'hypot',
"""
- Given two sides of a right triangle, return its hypotenuse.
+ Given the "legs" of a right triangle, return its hypotenuse.
+
+ Equivalent to ``sqrt(x1**2 + x2**2)``, element-wise. If `x1` or
+ `x2` is scalar_like (i.e., unambiguously cast-able to a scalar type),
+ it is broadcast for use with each element of the other argument.
+ (See Examples)
Parameters
----------
- x : array_like
- Base of the triangle.
- y : array_like
- Height of the triangle.
+ x1, x2 : array_like
+ Leg of the triangle(s).
+ out : ndarray, optional
+ Array into which the output is placed. Its type is preserved and it
+ must be of the right shape to hold the output. See doc.ufuncs.
Returns
-------
z : ndarray
- Hypotenuse of the triangle: sqrt(x**2 + y**2)
+ The hypotenuse of the triangle(s).
Examples
--------
- >>> np.hypot(3,4)
- 5.0
+ >>> np.hypot(3*np.ones((3, 3)), 4*np.ones((3, 3)))
+ array([[ 5., 5., 5.],
+ [ 5., 5., 5.],
+ [ 5., 5., 5.]])
+
+ Example showing broadcast of scalar_like argument:
+
+ >>> np.hypot(3*np.ones((3, 3)), [4])
+ array([[ 5., 5., 5.],
+ [ 5., 5., 5.],
+ [ 5., 5., 5.]])
""")
@@ -1376,16 +1439,17 @@ add_newdoc('numpy.core.umath', 'invert',
add_newdoc('numpy.core.umath', 'isfinite',
"""
- Test element-wise for finite-ness (not infinity or not Not a Number),
- return result as bool array.
+ Test element-wise for finite-ness (not infinity or not Not a Number).
+
+ The result is returned as a boolean array.
Parameters
----------
x : array_like
Input values.
- y : array_like, optional
- A boolean array with the same shape and type as `x` to store the
- result.
+ out : ndarray, optional
+ Array into which the output is placed. Its type is preserved and it
+ must be of the right shape to hold the output. See `doc.ufuncs`.
Returns
-------
@@ -1397,11 +1461,7 @@ add_newdoc('numpy.core.umath', 'isfinite',
For array input, the result is a boolean array with the same
dimensions as the input and the values are True if the corresponding
element of the input is finite; otherwise the values are False (element
- is either positive infinity, negative infinity or Not a Number). If a
- second argument is supplied the result is stored there. If the type of
- that array is a numeric type the result is represented as zeros and
- ones, if the type is boolean then as False and True. The return value
- `y` is then a reference to that array.
+ is either positive infinity, negative infinity or Not a Number).
See Also
--------
@@ -1592,7 +1652,7 @@ add_newdoc('numpy.core.umath', 'less',
Returns
-------
- Out : {ndarray, bool}
+ Out : ndarray of bools
Output array of bools, or a single bool if `x1` and `x2` are scalars.
See Also
@@ -1650,7 +1710,7 @@ add_newdoc('numpy.core.umath', 'log',
See Also
--------
- log10, log2, log1p
+ log10, log2, log1p, emath.log
Notes
-----
@@ -1695,6 +1755,10 @@ add_newdoc('numpy.core.umath', 'log10',
The logarithm to the base 10 of `x`, element-wise. NaNs are
returned where x is negative.
+ See Also
+ --------
+ emath.log10
+
Notes
-----
Logarithm is a multivalued function: for each `x` there is an infinite
@@ -1739,12 +1803,25 @@ add_newdoc('numpy.core.umath', 'log2',
See Also
--------
- log, log10, log1p
+ log, log10, log1p, emath.log2
Notes
-----
.. versionadded:: 1.3.0
+ Logarithm is a multivalued function: for each `x` there is an infinite
+ number of `z` such that `2**z = x`. The convention is to return the `z`
+ whose imaginary part lies in `[-pi, pi]`.
+
+ For real-valued input data types, `log2` always returns real output. For
+ each value that cannot be expressed as a real number or infinity, it
+ yields ``nan`` and sets the `invalid` floating point error flag.
+
+ For complex-valued input, `log2` is a complex analytical function that
+ has a branch cut `[-inf, 0]` and is continuous from above on it. `log2`
+ handles the floating-point negative zero as an infinitesimal negative
+ number, conforming to the C99 standard.
+
""")
add_newdoc('numpy.core.umath', 'logaddexp',
@@ -2021,12 +2098,19 @@ add_newdoc('numpy.core.umath', 'maximum',
Element-wise maximum of array elements.
Compare two arrays and returns a new array containing
- the element-wise maxima.
+ the element-wise maxima. If one of the elements being
+ compared is a nan, then that element is returned. If
+ both elements are nans then the first is returned. The
+ latter distinction is important for complex nans,
+ which are defined as at least one of the real or
+ imaginary parts being a nan. The net effect is that
+ nans are propagated.
Parameters
----------
x1, x2 : array_like
- The arrays holding the elements to be compared.
+ The arrays holding the elements to be compared. They must have
+ the same shape, or shapes that can be broadcast to a single shape.
Returns
-------
@@ -2039,6 +2123,12 @@ add_newdoc('numpy.core.umath', 'maximum',
minimum :
element-wise minimum
+ fmax :
+ element-wise maximum that ignores nans unless both inputs are nans.
+
+ fmin :
+ element-wise minimum that ignores nans unless both inputs are nans.
+
Notes
-----
Equivalent to ``np.where(x1 > x2, x1, x2)`` but faster and does proper
@@ -2053,6 +2143,11 @@ add_newdoc('numpy.core.umath', 'maximum',
array([[ 1. , 2. ],
[ 0.5, 2. ]])
+ >>> np.maximum([np.nan, 0, np.nan], [0, np.nan, np.nan])
+ array([ NaN, NaN, NaN])
+ >>> np.maximum(np.Inf, 1)
+ inf
+
""")
add_newdoc('numpy.core.umath', 'minimum',
@@ -2070,7 +2165,7 @@ add_newdoc('numpy.core.umath', 'minimum',
----------
x1, x2 : array_like
The arrays holding the elements to be compared. They must have
- the same shape.
+ the same shape, or shapes that can be broadcast to a single shape.
Returns
-------
@@ -2097,7 +2192,7 @@ add_newdoc('numpy.core.umath', 'minimum',
>>> np.minimum([2, 3, 4], [1, 5, 2])
array([1, 3, 2])
- >>> np.minimum(np.eye(2), [0.5, 2])
+ >>> np.minimum(np.eye(2), [0.5, 2]) # broadcasting
array([[ 0.5, 0. ],
[ 0. , 1. ]])
@@ -2310,6 +2405,7 @@ add_newdoc('numpy.core.umath', 'not_equal',
Input arrays.
out : ndarray, optional
A placeholder the same shape as `x1` to store the result.
+ See `doc.ufuncs` (Section "Output arguments") for more details.
Returns
-------
@@ -2326,6 +2422,9 @@ add_newdoc('numpy.core.umath', 'not_equal',
--------
>>> np.not_equal([1.,2.], [1., 3.])
array([False, True], dtype=bool)
+ >>> np.not_equal([1, 2], [[1, 3],[1, 4]])
+ array([[False, True],
+ [False, True]], dtype=bool)
""")
@@ -2401,9 +2500,34 @@ add_newdoc('numpy.core.umath', 'radians',
"""
Convert angles from degrees to radians.
+ Parameters
+ ----------
+ x : array_like
+ Input array in degrees.
+ out : ndarray, optional
+ Output array of same shape as x.
+
+ Returns
+ -------
+ y : ndarray
+ The corresponding radian values.
+
See Also
--------
- deg2rad : equivalent function; see for documentation.
+ deg2rad : equivalent function
+
+ Examples
+ --------
+ Convert a degree array to radians
+
+ >>> deg = np.arange(12.) * 30.
+ >>> np.radians(deg)
+ array([ 0. , 0.52359878, 1.04719755, 1.57079633, 2.0943951 ,
+ 2.61799388, 3.14159265, 3.66519143, 4.1887902 , 4.71238898,
+ 5.23598776, 5.75958653])
+
+ >>> foo = np.zeros((deg.shape))
+ >>> radians(deg, foo)
""")
@@ -2475,7 +2599,7 @@ add_newdoc('numpy.core.umath', 'reciprocal',
add_newdoc('numpy.core.umath', 'remainder',
"""
- Returns element-wise remainder of division.
+ Return element-wise remainder of division.
Computes ``x1 - floor(x1/x2)*x2``.
@@ -2625,19 +2749,23 @@ add_newdoc('numpy.core.umath', 'signbit',
add_newdoc('numpy.core.umath', 'copysign',
"""
- Change the sign of x to that of y element-wise.
+ Change the sign of x1 to that of x2, element-wise.
+
+ If both arguments are arrays or sequences, they have to be of the same
+ length. If `x2` is a scalar, its sign will be copied to all elements of
+ `x1`.
Parameters
----------
- x: array_like
+ x1: array_like
Values to change the sign of.
- y: array_like
- The sign of y is copied to x.
+ x2: array_like
+ The sign of `x2` is copied to `x1`.
Returns
-------
out : array_like
- values of x with the sign of y
+ The values of `x1` with the sign of `x2`.
Examples
--------
@@ -2648,6 +2776,11 @@ add_newdoc('numpy.core.umath', 'copysign',
>>> 1/np.copysign(0, -1)
-inf
+ >>> np.copysign([-1, 0, 1], -1.1)
+ array([-1., -0., -1.])
+ >>> np.copysign([-1, 0, 1], np.arange(3)-1)
+ array([-1., 0., 1.])
+
""")
add_newdoc('numpy.core.umath', 'sin',
@@ -2742,20 +2875,19 @@ add_newdoc('numpy.core.umath', 'sinh',
Examples
--------
- >>> import numpy as np
>>> np.sinh(0)
0.0
>>> np.sinh(np.pi*1j/2)
1j
- >>> np.sinh(np.pi*1j)
- 1.2246063538223773e-016j (exact value is 0)
+ >>> np.sinh(np.pi*1j) # (exact value is 0)
+ 1.2246063538223773e-016j
>>> # Discrepancy due to vagaries of floating point arithmetic.
- >>>
+
>>> # Example of providing the optional output parameter
>>> out2 = np.sinh([0.1], out1)
>>> out2 is out1
True
- >>>
+
>>> # Example of ValueError due to provision of shape mis-matched `out`
>>> np.sinh(np.zeros((3,3)),np.zeros((2,2)))
Traceback (most recent call last):
@@ -2948,21 +3080,24 @@ add_newdoc('numpy.core.umath', 'tanh',
References
----------
- M. Abramowitz and I. A. Stegun, Handbook of Mathematical Functions.
- New York, NY: Dover, 1972, pg. 83.
+ .. [1] M. Abramowitz and I. A. Stegun, Handbook of Mathematical Functions.
+ New York, NY: Dover, 1972, pg. 83.
+ http://www.math.sfu.ca/~cbm/aands/
+
+ .. [2] Wikipedia, "Hyperbolic function",
+ http://en.wikipedia.org/wiki/Hyperbolic_function
Examples
--------
- >>> import numpy as np
>>> np.tanh((0, np.pi*1j, np.pi*1j/2))
array([ 0. +0.00000000e+00j, 0. -1.22460635e-16j, 0. +1.63317787e+16j])
- >>>
+
>>> # Example of providing the optional output parameter illustrating
>>> # that what is returned is a reference to said parameter
>>> out2 = np.tanh([0.1], out1)
>>> out2 is out1
True
- >>>
+
>>> # Example of ValueError due to provision of shape mis-matched `out`
>>> np.tanh(np.zeros((3,3)),np.zeros((2,2)))
Traceback (most recent call last):
@@ -2973,7 +3108,7 @@ add_newdoc('numpy.core.umath', 'tanh',
add_newdoc('numpy.core.umath', 'true_divide',
"""
- Returns an element-wise, true division of the inputs.
+ Returns a true division of the inputs, element-wise.
Instead of the Python traditional 'floor division', this returns a true
division. True division adjusts the output type to present the best
@@ -2982,9 +3117,9 @@ add_newdoc('numpy.core.umath', 'true_divide',
Parameters
----------
x1 : array_like
- Dividend
+ Dividend array.
x2 : array_like
- Divisor
+ Divisor array.
Returns
-------
@@ -2993,13 +3128,30 @@ add_newdoc('numpy.core.umath', 'true_divide',
Notes
-----
- The floor division operator ('//') was added in Python 2.2 making '//'
- and '/' equivalent operators. The default floor division operation of
- '/' can be replaced by true division with
- 'from __future__ import division'.
+ The floor division operator ``//`` was added in Python 2.2 making ``//``
+ and ``/`` equivalent operators. The default floor division operation of
+ ``/`` can be replaced by true division with
+ ``from __future__ import division``.
- In Python 3.0, '//' will be the floor division operator and '/' will be
- the true division operator. The 'true_divide(`x1`, `x2`)' function is
+ In Python 3.0, ``//`` is the floor division operator and ``/`` the
+ true division operator. The ``true_divide(x1, x2)`` function is
equivalent to true division in Python.
+ Examples
+ --------
+ >>> x = np.arange(5)
+ >>> np.true_divide(x, 4)
+ array([ 0. , 0.25, 0.5 , 0.75, 1. ])
+
+ >>> x/4
+ array([0, 0, 0, 0, 1])
+ >>> x//4
+ array([0, 0, 0, 0, 1])
+
+ >>> from __future__ import division
+ >>> x/4
+ array([ 0. , 0.25, 0.5 , 0.75, 1. ])
+ >>> x//4
+ array([0, 0, 0, 0, 1])
+
""")
diff --git a/numpy/core/defchararray.py b/numpy/core/defchararray.py
index 9866954c1..580bde59a 100644
--- a/numpy/core/defchararray.py
+++ b/numpy/core/defchararray.py
@@ -1,3 +1,14 @@
+"""
+Module for character arrays.
+
+.. note::
+ The chararray module exists for backwards compatibility with Numarray,
+ it is not recommended for new development. If one needs arrays of
+ strings, use arrays of `dtype` object.
+
+The preferred alias for `defchararray` is `numpy.char`.
+
+"""
import sys
from numerictypes import string_, unicode_, integer, object_
from numeric import ndarray, broadcast, empty, compare_chararrays
@@ -20,14 +31,62 @@ class chararray(ndarray):
chararray(shape, itemsize=1, unicode=False, buffer=None, offset=0,
strides=None, order=None)
- A character array of string or unicode type.
-
- The array items will be `itemsize` characters long.
-
- Create the array using buffer (with offset and strides) if it is
- not None. If buffer is None, then construct a new array with strides
- in Fortran order if len(shape) >=2 and order is 'Fortran' (otherwise
- the strides will be in 'C' order).
+ An array of fixed size (perhaps unicode) strings.
+
+ .. note::
+ The chararray module exists for backwards compatibility with Numarray,
+ it is not recommended for new development. If one needs arrays of
+ strings, use arrays of `dtype` object.
+
+ Create the array, using `buffer` (with `offset` and `strides`) if it is
+ not ``None``. If `buffer` is ``None``, then construct a new array with
+ `strides` in "C order," unless both ``len(shape) >= 2`` and
+ ``order='Fortran'``, in which case `strides` is in "Fortran order."
+
+ Parameters
+ ----------
+ shape : tuple
+ Shape of the array.
+
+ itemsize : int_like, > 0, optional
+ Length of each array element, in number of characters. Default is 1.
+
+ unicode : {True, False}, optional
+ Are the array elements of unicode-type (``True``) or string-type
+ (``False``, the default).
+
+ buffer : integer, > 0, optional
+ Memory address of the start of the array data. If ``None`` (the
+ default), a new array is created.
+
+ offset : integer, >= 0, optional
+ Fixed stride displacement from the beginning of an axis? Default is
+ 0.
+
+ strides : array_like(?), optional
+ Strides for the array (see `numpy.ndarray.strides` for full
+ description), default is ``None``.
+
+ order : {'C', 'F'}, optional
+ The order in which the array data is stored in memory: 'C' -> "row
+ major" order (the default), 'F' -> "column major" (Fortran) order
+
+ Examples
+ --------
+ >>> charar = np.chararray((3, 3))
+ >>> charar[:,:] = 'abc'
+ >>> charar
+ chararray([['a', 'a', 'a'],
+ ['a', 'a', 'a'],
+ ['a', 'a', 'a']],
+ dtype='|S1')
+ >>> charar = np.chararray(charar.shape, itemsize=5)
+ >>> charar[:,:] = 'abc'
+ >>> charar
+ chararray([['abc', 'abc', 'abc'],
+ ['abc', 'abc', 'abc'],
+ ['abc', 'abc', 'abc']],
+ dtype='|S5')
"""
def __new__(subtype, shape, itemsize=1, unicode=False, buffer=None,
@@ -144,6 +203,23 @@ class chararray(ndarray):
return NotImplemented
def argsort(self, axis=-1, kind='quicksort', order=None):
+ """
+ Return the indices that sort the array lexicographically.
+
+ For full documentation see `numpy.argsort`, for which this method is
+ in fact merely a "thin wrapper."
+
+ Examples
+ --------
+ >>> c = np.array(['a1b c', '1b ca', 'b ca1', 'Ca1b'], 'S5')
+ >>> c = c.view(np.chararray); c
+ chararray(['a1b c', '1b ca', 'b ca1', 'Ca1b'],
+ dtype='|S5')
+ >>> c[c.argsort()]
+ chararray(['1b ca', 'Ca1b', 'a1b c', 'b ca1'],
+ dtype='|S5')
+
+ """
return self.__array__().argsort(axis, kind, order)
def _generalmethod(self, name, myiter):
@@ -184,6 +260,33 @@ class chararray(ndarray):
return result
def capitalize(self):
+ """
+ Capitalize the first character of each array element.
+
+ For each element of `self`, if the first character is a letter
+ possessing both "upper-case" and "lower-case" forms, and it is
+ presently in lower-case, change it to upper-case; otherwise, leave
+ it untouched.
+
+ Parameters
+ ----------
+ None
+
+ Returns
+ -------
+ ret : chararray
+ `self` with each element "title-cased."
+
+ Examples
+ --------
+ >>> c = np.array(['a1b2','1b2a','b2a1','2a1b'],'S4').view(np.chararray); c
+ chararray(['a1b2', '1b2a', 'b2a1', '2a1b'],
+ dtype='|S4')
+ >>> c.capitalize()
+ chararray(['A1b2', '1b2a', 'B2a1', '2a1b'],
+ dtype='|S4')
+
+ """
return self._samemethod('capitalize')
if sys.version[:3] >= '2.4':
@@ -208,15 +311,161 @@ class chararray(ndarray):
return self._generalmethod('center', broadcast(self, width))
def count(self, sub, start=None, end=None):
+ """
+ Return the number of occurrences of a sub-string in each array element.
+
+ Parameters
+ ----------
+ sub : string
+ The sub-string to count.
+ start : int, optional
+ The string index at which to start counting in each element.
+ end : int, optional
+ The string index at which to end counting in each element.
+
+ Returns
+ -------
+ ret : ndarray of ints
+ Array whose elements are the number of occurrences of `sub` in each
+ element of `self`.
+
+ Examples
+ --------
+ >>> c = np.array(['aAaAaA', ' aA ', 'abBABba']).view(np.chararray)
+ >>> c
+ chararray(['aAaAaA', ' aA', 'abBABba'],
+ dtype='|S7')
+ >>> c.count('A')
+ array([3, 1, 1])
+ >>> c.count('aA')
+ array([3, 1, 0])
+ >>> c.count('A', start=1, end=4)
+ array([2, 1, 1])
+ >>> c.count('A', start=1, end=3)
+ array([1, 0, 0])
+
+ """
return self._typedmethod('count', broadcast(self, sub, start, end), int)
def decode(self,encoding=None,errors=None):
+ """
+ Return elements decoded according to the value of `encoding`.
+
+ Parameters
+ ----------
+ encoding : string, optional
+ The encoding to use; for a list of acceptable values, see the
+ Python docstring for the package 'encodings'
+ error : Python exception object?, optional
+ The exception to raise if decoding fails?
+
+ Returns
+ -------
+ ret : chararray
+ A view of `self`, suitably decoded.
+
+ See Also
+ --------
+ encode
+ encodings
+ (package)
+
+ Examples
+ --------
+ >>> c = np.array(['aAaAaA', ' aA ', 'abBABba']).view(np.chararray)
+ >>> c
+ chararray(['aAaAaA', ' aA', 'abBABba'],
+ dtype='|S7')
+ >>> c = c.encode(encoding='cp037'); c
+ chararray(['\\x81\\xc1\\x81\\xc1\\x81\\xc1', '@@\\x81\\xc1@@',
+ '\\x81\\x82\\xc2\\xc1\\xc2\\x82\\x81'],
+ dtype='|S7')
+ >>> c.decode(encoding='cp037')
+ chararray(['aAaAaA', ' aA', 'abBABba'],
+ dtype='|S7')
+
+ """
return self._generalmethod('decode', broadcast(self, encoding, errors))
def encode(self,encoding=None,errors=None):
+ """
+ Return elements encoded according to the value of `encoding`.
+
+ Parameters
+ ----------
+ encoding : string, optional
+ The encoding to use; for a list of acceptable values, see the
+ Python docstring for `encodings`.
+ error : Python exception object, optional
+ The exception to raise if encoding fails.
+
+ Returns
+ -------
+ ret : chararray
+ A view of `self`, suitably encoded.
+
+ See Also
+ --------
+ decode
+
+ Examples
+ --------
+ >>> c = np.array(['aAaAaA', ' aA ', 'abBABba']).view(np.chararray)
+ >>> c
+ chararray(['aAaAaA', ' aA', 'abBABba'],
+ dtype='|S7')
+ >>> c.encode(encoding='cp037')
+ chararray(['\\x81\\xc1\\x81\\xc1\\x81\\xc1', '@@\\x81\\xc1@@',
+ '\\x81\\x82\\xc2\\xc1\\xc2\\x82\\x81'],
+ dtype='|S7')
+
+ """
return self._generalmethod('encode', broadcast(self, encoding, errors))
def endswith(self, suffix, start=None, end=None):
+ """
+ Check whether elements end with specified suffix
+
+ Given an array of strings, return a new bool array of same shape with
+ the result of comparing suffix against each element; each element
+ of bool array is ``True`` if element ends with specified suffix and
+ ``False`` otherwise.
+
+ Parameters
+ ----------
+ suffix : string
+ Compare each element in array to this.
+ start : int, optional
+ For each element, start searching from this position.
+ end : int, optional
+ For each element, stop comparing at this position.
+
+ Returns
+ -------
+ endswith : ndarray
+ Output array of bools
+
+ See Also
+ --------
+ count
+ find
+ index
+ startswith
+
+ Examples
+ --------
+ >>> s = chararray(3, itemsize=3)
+ >>> s[0] = 'foo'
+ >>> s[1] = 'bar'
+ >>> s
+ chararray(['foo', 'bar'],
+ dtype='|S3')
+ >>> s.endswith('ar')
+ array([False, True], dtype=bool)
+ >>> s.endswith('a', start=1, end=2)
+ array([False, True], dtype=bool)
+
+ """
return self._typedmethod('endswith', broadcast(self, suffix, start, end), bool)
def expandtabs(self, tabsize=None):
@@ -261,9 +510,76 @@ class chararray(ndarray):
return self._generalmethod('join', broadcast(self, seq))
def lower(self):
+ """
+ Assure that every character of each array element is lower-case.
+
+ For each character possessing both "upper-case" and "lower-case" forms,
+ if it is in upper-case, change it to lower; otherwise, leave it unchanged.
+
+ Parameters
+ ----------
+ None
+
+ Returns
+ -------
+ ret : chararray
+ `self` with all capital letters changed to lower-case.
+
+ Examples
+ --------
+ >>> c = np.array(['A1B C', '1BCA', 'BCA1']).view(np.chararray); c
+ chararray(['A1B C', '1BCA', 'BCA1'],
+ dtype='|S5')
+ >>> c.lower()
+ chararray(['a1b c', '1bca', 'bca1'],
+ dtype='|S5')
+
+ """
return self._samemethod('lower')
def lstrip(self, chars):
+ """
+ Remove leading characters from each element.
+
+ Returns a view of ``self`` with `chars` stripped from the start of
+ each element. Note: **No Default** - `chars` must be specified (but if
+ it is explicitly ``None`` or the empty string '', leading whitespace is
+ removed).
+
+ Parameters
+ ----------
+ chars : string_like or None
+ Character(s) to strip; whitespace stripped if `chars` == ``None``
+ or `chars` == ''.
+
+ Returns
+ -------
+ ret : chararray
+ View of ``self``, each element suitably stripped.
+
+ Raises
+ ------
+ TypeError: lstrip() takes exactly 2 arguments (1 given)
+ If `chars` is not supplied.
+
+ Examples
+ --------
+ >>> c = np.array(['aAaAaA', ' aA ', 'abBABba']).view(np.chararray)
+ >>> c
+ chararray(['aAaAaA', ' aA', 'abBABba'],
+ dtype='|S7')
+ >>> c.lstrip('a') # 'a' unstripped from c[1] because whitespace leading
+ chararray(['AaAaA', ' aA', 'bBABba'],
+ dtype='|S6')
+ >>> c.lstrip('A') # leaves c unchanged
+ chararray(['aAaAaA', ' aA', 'abBABba'],
+ dtype='|S7')
+ >>> (c.lstrip(' ') == c.lstrip('')).all()
+ True
+ >>> (c.lstrip(' ') == c.lstrip(None)).all()
+ True
+
+ """
return self._generalmethod('lstrip', broadcast(self, chars))
def replace(self, old, new, count=None):
@@ -276,6 +592,35 @@ class chararray(ndarray):
return self._typedmethod('rindex', broadcast(self, sub, start, end), int)
def rstrip(self, chars=None):
+ """
+ Remove trailing characters.
+
+ Returns a view of ``self`` with `chars` stripped from the end of each
+ element.
+
+ Parameters
+ ----------
+ chars : string_like, optional, default=None
+ Character(s) to remove.
+
+ Returns
+ -------
+ ret : chararray
+ View of ``self``, each element suitably stripped.
+
+ Examples
+ --------
+ >>> c = np.array(['aAaAaA', 'abBABba'], dtype='S7').view(np.chararray); c
+ chararray(['aAaAaA', 'abBABba'],
+ dtype='|S7')
+ >>> c.rstrip('a')
+ chararray(['aAaAaA', 'abBABb'],
+ dtype='|S6')
+ >>> c.rstrip('A')
+ chararray(['aAaAa', 'abBABba'],
+ dtype='|S7')
+
+ """
return self._generalmethod('rstrip', broadcast(self, chars))
def split(self, sep=None, maxsplit=None):
@@ -288,12 +633,95 @@ class chararray(ndarray):
return self._typedmethod('startswith', broadcast(self, prefix, start, end), bool)
def strip(self, chars=None):
+ """
+ Remove leading and trailing characters, whitespace by default.
+
+ Returns a view of ``self`` with `chars` stripped from the start and end of
+ each element; by default leading and trailing whitespace is removed.
+
+ Parameters
+ ----------
+ chars : string_like, optional, default=None
+ Character(s) to strip; whitespace by default.
+
+ Returns
+ -------
+ ret : chararray
+ View of ``self``, each element suitably stripped.
+
+ Examples
+ --------
+ >>> c = np.array(['aAaAaA', ' aA ', 'abBABba']).view(np.chararray)
+ >>> c
+ chararray(['aAaAaA', ' aA', 'abBABba'],
+ dtype='|S7')
+ >>> c.strip()
+ chararray(['aAaAaA', 'aA', 'abBABba'],
+ dtype='|S7')
+ >>> c.strip('a') # 'a' unstripped from c[1] because whitespace leads
+ chararray(['AaAaA', ' aA', 'bBABb'],
+ dtype='|S6')
+ >>> c.strip('A') # 'A' unstripped from c[1] because (unprinted) ws trails
+ chararray(['aAaAa', ' aA', 'abBABba'],
+ dtype='|S7')
+
+ """
return self._generalmethod('strip', broadcast(self, chars))
def swapcase(self):
+ """
+ Switch upper-case letters to lower-case, and vice-versa.
+
+ Parameters
+ ----------
+ None
+
+ Returns
+ -------
+ ret : chararray
+ `self` with all lower-case letters capitalized and all upper-case
+ changed to lower case.
+
+ Examples
+ --------
+ >>> c=np.array(['a1B c','1b Ca','b Ca1','cA1b'],'S5').view(np.chararray);c
+ chararray(['a1B c', '1b Ca', 'b Ca1', 'cA1b'],
+ dtype='|S5')
+ >>> c.swapcase()
+ chararray(['A1b C', '1B cA', 'B cA1', 'Ca1B'],
+ dtype='|S5')
+
+ """
return self._samemethod('swapcase')
def title(self):
+ """
+ Capitalize the first character of each array element.
+
+ For each element of `self`, if the first character is a letter
+ possessing both "upper-case" and "lower-case" forms, and it is
+ presently in lower-case, change it to upper-case; otherwise, leave
+ it untouched.
+
+ Parameters
+ ----------
+ None
+
+ Returns
+ -------
+ ret : chararray
+ `self` with
+
+ Examples
+ --------
+ >>> c=np.array(['a1b c','1b ca','b ca1','ca1b'],'S5').view(np.chararray);c
+ chararray(['a1b c', '1b ca', 'b ca1', 'ca1b'],
+ dtype='|S5')
+ >>> c.title()
+ chararray(['A1B C', '1B Ca', 'B Ca1', 'Ca1B'],
+ dtype='|S5')
+
+ """
return self._samemethod('title')
def translate(self, table, deletechars=None):
@@ -303,6 +731,31 @@ class chararray(ndarray):
return self._generalmethod('translate', broadcast(self, table, deletechars))
def upper(self):
+ """
+ Capitalize every character of each array element.
+
+ For each character possessing both "upper-case" and "lower-case" forms,
+ if it is in lower-case, change it to upper; otherwise, leave it unchanged.
+
+ Parameters
+ ----------
+ None
+
+ Returns
+ -------
+ ret : chararray
+ `self` with all characters capitalized.
+
+ Examples
+ --------
+ >>> c = np.array(['a1b c', '1bca', 'bca1']).view(np.chararray); c
+ chararray(['a1b c', '1bca', 'bca1'],
+ dtype='|S5')
+ >>> c.upper()
+ chararray(['A1B C', '1BCA', 'BCA1'],
+ dtype='|S5')
+
+ """
return self._samemethod('upper')
def zfill(self, width):
diff --git a/numpy/core/fromnumeric.py b/numpy/core/fromnumeric.py
index de8a27d08..eb7da718a 100644
--- a/numpy/core/fromnumeric.py
+++ b/numpy/core/fromnumeric.py
@@ -112,7 +112,7 @@ def reshape(a, newshape, order='C'):
----------
a : array_like
Array to be reshaped.
- newshape : {tuple, int}
+ newshape : int or tuple of ints
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.
One shape dimension can be -1. In this case, the value is inferred
@@ -187,6 +187,7 @@ def choose(a, choices, out=None, mode='raise'):
See Also
--------
ndarray.choose : equivalent method
+ numpy.doc.ufuncs : Section "Output arguments"
Examples
--------
@@ -457,10 +458,10 @@ def sort(a, axis=-1, kind='quicksort', order=None):
Previous to numpy 1.4.0 sorting real and complex arrays containing nan
values led to undefined behaviour. In numpy versions >= 1.4.0 nan
values are sorted to the end. The extended sort order is:
-
- Real: [R, nan]
- Complex: [R + Rj, R + nanj, nan + Rj, nan + nanj]
-
+
+ * Real: [R, nan]
+ * Complex: [R + Rj, R + nanj, nan + Rj, nan + nanj]
+
where R is a non-nan real value. Complex values with the same nan
placements are sorted according to the non-nan part if it exists.
Non-nan values are sorted as before.
@@ -544,8 +545,8 @@ def argsort(a, axis=-1, kind='quicksort', order=None):
-----
See `sort` for notes on the different sorting algorithms.
- As of Numpy 1.4.0 argsort works with real/complex arrays containing
- nan values. The enhanced sort order is documented in the numpy.sort.
+ As of NumPy 1.4.0 `argsort` works with real/complex arrays containing
+ nan values. The enhanced sort order is documented in `sort`.
Examples
--------
@@ -605,19 +606,27 @@ def argmax(a, axis=None):
Returns
-------
- index_array : ndarray, int
- Array of indices into the array. It has the same shape as `a`,
- except with `axis` removed.
+ index_array : ndarray of ints
+ Array of indices into the array. It has the same shape as `a.shape`
+ with the dimension along `axis` removed.
See Also
--------
- argmin : Indices of the minimum values along an axis.
+ ndarray.argmax, argmin
amax : The maximum value along a given axis.
unravel_index : Convert a flat index into an index tuple.
+ Notes
+ -----
+ In case of multiple occurrences of the maximum values, the indices
+ corresponding to the first occurrence are returned.
+
Examples
--------
>>> a = np.arange(6).reshape(2,3)
+ >>> a
+ array([[0, 1, 2],
+ [3, 4, 5]])
>>> np.argmax(a)
5
>>> np.argmax(a, axis=0)
@@ -625,6 +634,13 @@ def argmax(a, axis=None):
>>> np.argmax(a, axis=1)
array([2, 2])
+ >>> b = np.arange(6)
+ >>> b[1] = 5
+ >>> b
+ array([0, 5, 2, 3, 4, 5])
+ >>> np.argmax(b) # Only the first occurrence is returned.
+ 1
+
"""
try:
argmax = a.argmax
@@ -683,8 +699,8 @@ def searchsorted(a, v, side='left'):
-----
Binary search is used to find the required insertion points.
- As of Numpy 1.4.0 searchsorted works with real/complex arrays containing
- nan values. The enhanced sort order is documented in the numpy.sort.
+ As of Numpy 1.4.0 `searchsorted` works with real/complex arrays containing
+ `nan` values. The enhanced sort order is documented in `sort`.
Examples
--------
@@ -723,8 +739,9 @@ def resize(a, new_shape):
Returns
-------
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.
+ The new array is formed from the data in the old array, repeated
+ if necessary to fill out the required number of elements. The data
+ are repeated in the order that the data are stored in memory.
See Also
--------
@@ -1069,27 +1086,27 @@ def shape(a):
Returns
-------
- shape : tuple
- The elements of the tuple give the lengths of the corresponding array
- dimensions.
+ shape : tuple of ints
+ The elements of the shape tuple give the lengths of the
+ corresponding array dimensions.
See Also
--------
- alen,
- ndarray.shape : array method
+ alen
+ ndarray.shape : Equivalent array method.
Examples
--------
>>> np.shape(np.eye(3))
(3, 3)
- >>> np.shape([[1,2]])
+ >>> np.shape([[1, 2]])
(1, 2)
>>> np.shape([0])
(1,)
>>> np.shape(0)
()
- >>> a = np.array([(1,2),(3,4)], dtype=[('x', 'i4'), ('y', 'i4')])
+ >>> a = np.array([(1, 2), (3, 4)], dtype=[('x', 'i4'), ('y', 'i4')])
>>> np.shape(a)
(2,)
>>> a.shape
@@ -1136,6 +1153,7 @@ def compress(condition, a, axis=None, out=None):
--------
take, choose, diag, diagonal, select
ndarray.compress : Equivalent method.
+ numpy.doc.ufuncs : Section "Output arguments"
Examples
--------
@@ -1198,6 +1216,10 @@ def clip(a, a_min, a_max, out=None):
< `a_min` are replaced with `a_min`, and those > `a_max`
with `a_max`.
+ See Also
+ --------
+ numpy.doc.ufuncs : Section "Output arguments"
+
Examples
--------
>>> a = np.arange(10)
@@ -1222,7 +1244,7 @@ def clip(a, a_min, a_max, out=None):
def sum(a, axis=None, dtype=None, out=None):
"""
- Return the sum of array elements over a given axis.
+ Sum of array elements over a given axis.
Parameters
----------
@@ -1241,7 +1263,8 @@ def sum(a, axis=None, dtype=None, out=None):
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.
+ ``numpy.delete(a.shape, axis)``). Its type is preserved. See
+ `doc.ufuncs` (Section "Output arguments") for more details.
Returns
-------
@@ -1253,7 +1276,13 @@ def sum(a, axis=None, dtype=None, out=None):
See Also
--------
- ndarray.sum : equivalent method
+ ndarray.sum : Equivalent method.
+
+ cumsum : Cumulative sum of array elements.
+
+ trapz : Integration of array values using the composite trapezoidal rule.
+
+ mean, average
Notes
-----
@@ -1264,10 +1293,12 @@ def sum(a, axis=None, dtype=None, out=None):
--------
>>> np.sum([0.5, 1.5])
2.0
- >>> np.sum([0.5, 1.5], dtype=np.int32)
+ >>> np.sum([0.5, 0.7, 0.2, 1.5], dtype=np.int32)
1
>>> np.sum([[0, 1], [0, 5]])
6
+ >>> np.sum([[0, 1], [0, 5]], axis=0)
+ array([0, 6])
>>> np.sum([[0, 1], [0, 5]], axis=1)
array([1, 5])
@@ -1420,14 +1451,15 @@ def all(a,axis=None, out=None):
a : array_like
Input array or object that can be converted to an array.
axis : int, optional
- Axis along which an logical AND is performed.
+ Axis along which a logical AND is performed.
The default (`axis` = `None`) is to perform a logical AND
over a flattened input array. `axis` may be negative, in which
case it counts from the last to the first axis.
out : ndarray, optional
Alternative output array in which to place the result.
It must have the same shape as the expected output and
- the type is preserved.
+ the type is preserved. See `doc.ufuncs` (Section "Output
+ arguments") for more details.
Returns
-------
@@ -1439,6 +1471,8 @@ def all(a,axis=None, out=None):
--------
ndarray.all : equivalent method
+ any : Test whether any array element along a given axis evaluates to True.
+
Notes
-----
Not a Number (NaN), positive infinity and negative infinity
@@ -1491,13 +1525,23 @@ def cumsum (a, axis=None, dtype=None, out=None):
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 will be cast if necessary. See `doc.ufuncs`
+ (Section "Output arguments") for more details.
Returns
-------
- cumsum : ndarray.
+ cumsum_along_axis : ndarray.
A new array holding the result is returned unless `out` is
- specified, in which case a reference to `out` is returned.
+ specified, in which case a reference to `out` is returned. The
+ result has the same size as `a`, and the same shape as `a` if
+ `axis` is not None or `a` is a 1-d array.
+
+
+ See Also
+ --------
+ sum : Sum array elements.
+
+ trapz : Integration of array values using the composite trapezoidal rule.
Notes
-----
@@ -1507,6 +1551,9 @@ def cumsum (a, axis=None, dtype=None, out=None):
Examples
--------
>>> a = np.array([[1,2,3], [4,5,6]])
+ >>> a
+ 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)
@@ -1602,6 +1649,7 @@ def amax(a, axis=None, out=None):
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.
+ See `doc.ufuncs` (Section "Output arguments") for more details.
Returns
-------
@@ -1611,8 +1659,9 @@ def amax(a, axis=None, out=None):
See Also
--------
- nanmax: nan values are ignored instead of being propagated
- fmax: same behavior as the C99 fmax function
+ nanmax : nan values are ignored instead of being propagated
+ fmax : same behavior as the C99 fmax function
+ argmax : Indices of the maximum values.
Notes
-----
@@ -1626,11 +1675,20 @@ def amax(a, axis=None, out=None):
>>> a
array([[0, 1],
[2, 3]])
+ >>> np.amax(a)
+ 3
>>> np.amax(a, axis=0)
array([2, 3])
>>> np.amax(a, axis=1)
array([1, 3])
+ >>> b = np.arange(5, dtype=np.float)
+ >>> b[2] = np.NaN
+ >>> np.amax(b)
+ nan
+ >>> np.nanmax(b)
+ 4.0
+
"""
try:
amax = a.max
@@ -1652,6 +1710,7 @@ def amin(a, axis=None, out=None):
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.
+ See `doc.ufuncs` (Section "Output arguments") for more details.
Returns
-------
@@ -1663,6 +1722,9 @@ def amin(a, axis=None, out=None):
--------
nanmin: nan values are ignored instead of being propagated
fmin: same behavior as the C99 fmin function
+ argmin: Return the indices of the minimum values.
+
+ amax, nanmax, fmax
Notes
-----
@@ -1683,6 +1745,13 @@ def amin(a, axis=None, out=None):
>>> np.amin(a, axis=1) # Minima along the second axis
array([0, 2])
+ >>> b = np.arange(5, dtype=np.float)
+ >>> b[2] = np.NaN
+ >>> np.amin(b)
+ nan
+ >>> np.nanmin(b)
+ 0.0
+
"""
try:
amin = a.min
@@ -1755,6 +1824,7 @@ def prod(a, axis=None, dtype=None, out=None):
See Also
--------
ndarray.prod : equivalent method
+ numpy.doc.ufuncs : Section "Output arguments"
Notes
-----
@@ -1832,6 +1902,10 @@ def cumprod(a, axis=None, dtype=None, out=None):
A new array holding the result is returned unless `out` is
specified, in which case a reference to out is returned.
+ See Also
+ --------
+ numpy.doc.ufuncs : Section "Output arguments"
+
Notes
-----
Arithmetic is modular when using integer types, and no error is
@@ -2013,7 +2087,8 @@ def around(a, decimals=0, out=None):
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 of the output
- values will be cast if necessary.
+ values will be cast if necessary. See `doc.ufuncs` (Section
+ "Output arguments") for details.
Returns
-------
@@ -2029,6 +2104,9 @@ def around(a, decimals=0, out=None):
--------
ndarray.round : equivalent method
+ ceil, fix, floor, rint, trunc
+
+
Notes
-----
For values exactly halfway between rounded decimal values, Numpy
@@ -2048,9 +2126,13 @@ def around(a, decimals=0, out=None):
Examples
--------
- >>> np.around([.5, 1.5, 2.5, 3.5, 4.5])
+ >>> np.around([0.37, 1.64])
+ array([ 0., 2.])
+ >>> np.around([0.37, 1.64], decimals=1)
+ array([ 0.4, 1.6])
+ >>> np.around([.5, 1.5, 2.5, 3.5, 4.5]) # rounds to nearest even value
array([ 0., 2., 2., 4., 4.])
- >>> np.around([1,2,3,11], decimals=1)
+ >>> np.around([1,2,3,11], decimals=1) # ndarray of ints is returned
array([ 1, 2, 3, 11])
>>> np.around([1,2,3,11], decimals=-1)
array([ 0, 0, 0, 10])
@@ -2105,11 +2187,11 @@ def mean(a, axis=None, dtype=None, out=None):
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.
+ necessary. See `doc.ufuncs` for details.
Returns
-------
- mean : ndarray, see dtype parameter above
+ m : ndarray, see dtype parameter above
If `out=None`, returns a new array containing the mean values,
otherwise a reference to the output array is returned.
@@ -2122,16 +2204,35 @@ def mean(a, axis=None, dtype=None, out=None):
The arithmetic mean is the sum of the elements along the axis divided
by the number of elements.
+ Note that for floating-point input, the mean is computed using the same
+ precision the input has. Depending on the input data, this can cause
+ the results to be inaccurate, especially for float32 (see example below).
+ Specifying a higher-accuracy accumulator using the `dtype` keyword can
+ alleviate this issue.
+
Examples
--------
- >>> a = np.array([[1,2],[3,4]])
+ >>> a = np.array([[1, 2], [3, 4]])
>>> np.mean(a)
2.5
- >>> np.mean(a,0)
+ >>> np.mean(a, axis=0)
array([ 2., 3.])
- >>> np.mean(a,1)
+ >>> np.mean(a, axis=1)
array([ 1.5, 3.5])
+ In single precision, `mean` can be inaccurate:
+
+ >>> a = np.zeros((2, 512*512), dtype=np.float32)
+ >>> a[0, :] = 1.0
+ >>> a[1, :] = 0.1
+ >>> np.mean(a)
+ 0.546875
+
+ Computing the mean in float64 is more accurate:
+
+ >>> np.mean(a, dtype=np.float64)
+ 0.55000000074505806
+
"""
try:
mean = a.mean
@@ -2177,6 +2278,7 @@ def std(a, axis=None, dtype=None, out=None, ddof=0):
See Also
--------
var, mean
+ numpy.doc.ufuncs : Section "Output arguments"
Notes
-----
@@ -2195,6 +2297,12 @@ def std(a, axis=None, dtype=None, out=None, ddof=0):
Note that, for complex numbers, `std` takes the absolute
value before squaring, so that the result is always real and nonnegative.
+ For floating-point input, the *std* is computed using the same
+ precision the input has. Depending on the input data, this can cause
+ the results to be inaccurate, especially for float32 (see example below).
+ Specifying a higher-accuracy accumulator using the `dtype` keyword can
+ alleviate this issue.
+
Examples
--------
>>> a = np.array([[1, 2], [3, 4]])
@@ -2205,6 +2313,19 @@ def std(a, axis=None, dtype=None, out=None, ddof=0):
>>> np.std(a, axis=1)
array([ 0.5, 0.5])
+ In single precision, std() can be inaccurate:
+
+ >>> a = np.zeros((2,512*512), dtype=np.float32)
+ >>> a[0,:] = 1.0
+ >>> a[1,:] = 0.1
+ >>> np.std(a)
+ 0.45172946707416706
+
+ Computing the standard deviation in float64 is more accurate:
+
+ >>> np.std(a, dtype=np.float64)
+ 0.44999999925552653
+
"""
try:
std = a.std
@@ -2252,6 +2373,7 @@ def var(a, axis=None, dtype=None, out=None, ddof=0):
--------
std : Standard deviation
mean : Average
+ numpy.doc.ufuncs : Section "Output arguments"
Notes
-----
@@ -2268,6 +2390,12 @@ def var(a, axis=None, dtype=None, out=None, ddof=0):
Note that for complex numbers, the absolute value is taken before
squaring, so that the result is always real and nonnegative.
+ For floating-point input, the variance is computed using the same
+ precision the input has. Depending on the input data, this can cause
+ the results to be inaccurate, especially for float32 (see example below).
+ Specifying a higher-accuracy accumulator using the `dtype` keyword can
+ alleviate this issue.
+
Examples
--------
>>> a = np.array([[1,2],[3,4]])
@@ -2278,6 +2406,21 @@ def var(a, axis=None, dtype=None, out=None, ddof=0):
>>> np.var(a,1)
array([ 0.25, 0.25])
+ In single precision, var() can be inaccurate:
+
+ >>> a = np.zeros((2,512*512), dtype=np.float32)
+ >>> a[0,:] = 1.0
+ >>> a[1,:] = 0.1
+ >>> np.var(a)
+ 0.20405951142311096
+
+ Computing the standard deviation in float64 is more accurate:
+
+ >>> np.var(a, dtype=np.float64)
+ 0.20249999932997387
+ >>> ((1-0.55)**2 + (0.1-0.55)**2)/2
+ 0.20250000000000001
+
"""
try:
var = a.var
diff --git a/numpy/core/getlimits.py b/numpy/core/getlimits.py
index 7d9034e58..97c12cc6b 100644
--- a/numpy/core/getlimits.py
+++ b/numpy/core/getlimits.py
@@ -47,7 +47,7 @@ class finfo(object):
The smallest representable number, typically ``-max``.
minexp : int
The most negative power of the base (2) consistent with there being
- no leading 0s in the mantissa.
+ no leading 0's in the mantissa.
negep : int
The exponent that yields ``epsneg``.
nexp : int
@@ -70,14 +70,12 @@ class finfo(object):
See Also
--------
- numpy.lib.machar.MachAr :
- The implementation of the tests that produce this information.
- iinfo :
- The equivalent for integer data types.
+ MachAr : The implementation of the tests that produce this information.
+ iinfo : The equivalent for integer data types.
Notes
-----
- For developers of numpy: do not instantiate this at the module level. The
+ For developers of NumPy: do not instantiate this at the module level. The
initial calculation of these parameters is expensive and negatively impacts
import times. These objects are cached, so calling ``finfo()`` repeatedly
inside your functions is not a problem.
diff --git a/numpy/core/machar.py b/numpy/core/machar.py
index facade612..290f33746 100644
--- a/numpy/core/machar.py
+++ b/numpy/core/machar.py
@@ -51,7 +51,6 @@ class MachAr(object):
ngrd : int
Number of 'guard digits' used when truncating the product
of two mantissas to fit the representation.
-
epsilon : float
Same as `eps`.
tiny : float
@@ -61,7 +60,30 @@ class MachAr(object):
precision : float
``- int(-log10(eps))``
resolution : float
- `` - 10**(-precision)``
+ ``- 10**(-precision)``
+
+ Parameters
+ ----------
+ float_conv : function, optional
+ Function that converts an integer or integer array to a float
+ or float array. Default is `float`.
+ int_conv : function, optional
+ Function that converts a float or float array to an integer or
+ integer array. Default is `int`.
+ float_to_float : function, optional
+ Function that converts a float array to float. Default is `float`.
+ Note that this does not seem to do anything useful in the current
+ implementation.
+ float_to_str : function, optional
+ Function that converts a single float to a string. Default is
+ ``lambda v:'%24.16e' %v``.
+ title : str, optional
+ Title that is printed in the string representation of `MachAr`.
+
+ See Also
+ --------
+ finfo : Machine limits for floating point types.
+ iinfo : Machine limits for integer types.
References
----------
diff --git a/numpy/core/memmap.py b/numpy/core/memmap.py
index 2392c3aa7..c11859fad 100644
--- a/numpy/core/memmap.py
+++ b/numpy/core/memmap.py
@@ -49,9 +49,9 @@ class memmap(ndarray):
Default is 'r+'.
offset : integer, optional
- In the file, array data starts at this offset. `offset` should be
- a multiple of the byte-size of `dtype`. Requires `shape=None`.
- The default is 0.
+ In the file, array data starts at this offset. Since `offset` is
+ measured in bytes, it should be a multiple of the byte-size of
+ `dtype`. Requires `shape=None`. The default is 0.
shape : tuple, optional
The desired shape of the array. By default, the returned array will be
1-D with the number of elements determined by file size and data-type.
@@ -75,10 +75,7 @@ class memmap(ndarray):
Given a memmap ``fp``, ``isinstance(fp, numpy.ndarray)`` returns
``True``.
- Notes
- -----
-
- Memory-mapped arrays use the the Python memory-map object which
+ Memory-mapped arrays use the Python memory-map object which
(prior to Python 2.5) does not allow files to be larger than a
certain size depending on the platform. This size is always < 2GB
even on 64-bit systems.
@@ -129,13 +126,6 @@ class memmap(ndarray):
>>> fpr.flags.writeable
False
- Cannot assign to read-only, obviously:
-
- >>> fpr[0, 3] = 56
- Traceback (most recent call last):
- ...
- RuntimeError: array is not writeable
-
Copy-on-write memmap:
>>> fpc = np.memmap(filename, dtype='float32', mode='c', shape=(3,4))
@@ -245,7 +235,24 @@ class memmap(ndarray):
self._mmap = None
def flush(self):
- """Flush any changes in the array to the file on disk."""
+ """
+ Write any changes in the array to the file on disk.
+
+ For further information, see `memmap`.
+
+ Parameters
+ ----------
+ None
+
+ See Also
+ --------
+ memmap
+
+ Examples
+ --------
+ Awaiting one...
+
+ """
if self._mmap is not None:
self._mmap.flush()
diff --git a/numpy/core/numeric.py b/numpy/core/numeric.py
index abe26aac3..3ca2d988f 100644
--- a/numpy/core/numeric.py
+++ b/numpy/core/numeric.py
@@ -197,8 +197,8 @@ def asarray(a, dtype=None, order=None):
dtype : data-type, optional
By default, the data-type is inferred from the input data.
order : {'C', 'F'}, optional
- Whether to use row-major ('C') or column-major ('FORTRAN') memory
- representation. Defaults to 'C'.
+ Whether to use row-major ('C') or column-major ('F' for FORTRAN)
+ memory representation. Defaults to 'C'.
Returns
-------
@@ -233,6 +233,16 @@ def asarray(a, dtype=None, order=None):
>>> np.asarray(a) is a
True
+ Contrary to `asanyarray`, ndarray subclasses are not passed through:
+
+ >>> issubclass(np.matrix, np.ndarray)
+ True
+ >>> a = np.matrix([[1, 2]])
+ >>> np.asarray(a) is a
+ False
+ >>> np.asanyarray(a) is a
+ True
+
"""
return array(a, dtype, copy=False, order=order)
@@ -618,16 +628,19 @@ def correlate(a,v,mode='valid',old_behavior=True):
--------
convolve : Discrete, linear convolution of two
one-dimensional sequences.
+ acorrelate : Discrete correlation following the usual signal processing
+ definition for complex arrays, and without assuming that
+ ``correlate(a, b) == correlate(b, a)``.
- Note
- ----
- If old_behavior is False, this function computes the correlation as
+ Notes
+ -----
+ If `old_behavior` is False, this function computes the correlation as
generally defined in signal processing texts::
z[k] = sum_n a[n] * conj(v[n+k])
- with a and v sequences being zero-padded where necessary and conj being the
- conjugate.
+ with a and v sequences being zero-padded where necessary and conj being
+ the conjugate.
Examples
--------
@@ -747,10 +760,11 @@ def convolve(a,v,mode='full'):
def outer(a,b):
"""
- Returns the outer product of two vectors.
+ Compute the outer product of two vectors.
- Given two vectors, ``[a0, a1, ..., aM]`` and ``[b0, b1, ..., bN]``,
- the outer product becomes::
+ Given two vectors, ``a = [a0, a1, ..., aM]`` and
+ ``b = [b0, b1, ..., bN]``,
+ the outer product [1]_ is::
[[a0*b0 a0*b1 ... a0*bN ]
[a1*b0 .
@@ -759,25 +773,50 @@ def outer(a,b):
Parameters
----------
- a : array_like, shaped (M,)
- First input vector. If either of the input vectors are not
- 1-dimensional, they are flattened.
- b : array_like, shaped (N,)
- Second input vector.
+ a, b : array_like, shape (M,), (N,)
+ First and second input vectors. Inputs are flattened if they
+ are not already 1-dimensional.
Returns
-------
- out : ndarray, shaped (M, N)
+ out : ndarray, shape (M, N)
``out[i, j] = a[i] * b[j]``
- Notes
- -----
- The outer product of vectors is a special case of the Kronecker product.
+ References
+ ----------
+ .. [1] : G. H. Golub and C. F. van Loan, *Matrix Computations*, 3rd
+ ed., Baltimore, MD, Johns Hopkins University Press, 1996,
+ pg. 8.
Examples
--------
- >>> x = np.array(['a', 'b', 'c'], dtype=object)
+ Make a (*very* coarse) grid for computing a Mandelbrot set:
+
+ >>> rl = np.outer(np.ones((5,)), np.linspace(-2, 2, 5))
+ >>> rl
+ array([[-2., -1., 0., 1., 2.],
+ [-2., -1., 0., 1., 2.],
+ [-2., -1., 0., 1., 2.],
+ [-2., -1., 0., 1., 2.],
+ [-2., -1., 0., 1., 2.]])
+ >>> im = np.outer(1j*np.linspace(2, -2, 5), np.ones((5,)))
+ >>> im
+ array([[ 0.+2.j, 0.+2.j, 0.+2.j, 0.+2.j, 0.+2.j],
+ [ 0.+1.j, 0.+1.j, 0.+1.j, 0.+1.j, 0.+1.j],
+ [ 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j],
+ [ 0.-1.j, 0.-1.j, 0.-1.j, 0.-1.j, 0.-1.j],
+ [ 0.-2.j, 0.-2.j, 0.-2.j, 0.-2.j, 0.-2.j]])
+ >>> grid = rl + im
+ >>> grid
+ array([[-2.+2.j, -1.+2.j, 0.+2.j, 1.+2.j, 2.+2.j],
+ [-2.+1.j, -1.+1.j, 0.+1.j, 1.+1.j, 2.+1.j],
+ [-2.+0.j, -1.+0.j, 0.+0.j, 1.+0.j, 2.+0.j],
+ [-2.-1.j, -1.-1.j, 0.-1.j, 1.-1.j, 2.-1.j],
+ [-2.-2.j, -1.-2.j, 0.-2.j, 1.-2.j, 2.-2.j]])
+
+ An example using a "vector" of letters:
+ >>> x = np.array(['a', 'b', 'c'], dtype=object)
>>> np.outer(x, [1, 2, 3])
array([[a, aa, aaa],
[b, bb, bbb],
@@ -806,39 +845,46 @@ except ImportError:
def tensordot(a, b, axes=2):
"""
- Returns the tensor dot product for (ndim >= 1) arrays along an axes.
+ Compute tensor dot product along specified axes for arrays >= 1-D.
- The first element of the sequence determines the axis or axes
- in `a` to sum over, and the second element in `axes` argument sequence
- determines the axis or axes in `b` to sum over.
+ Given two tensors (arrays of dimension greater than or equal to one),
+ ``a`` and ``b``, and an array_like object containing two array_like
+ objects, ``(a_axes, b_axes)``, sum the products of ``a``'s and ``b``'s
+ elements (components) over the axes specified by ``a_axes`` and
+ ``b_axes``. The third argument can be a single non-negative
+ integer_like scalar, ``N``; if it is such, then the last ``N``
+ dimensions of ``a`` and the first ``N`` dimensions of ``b`` are summed
+ over.
Parameters
----------
- a : array_like
- Input array.
- b : array_like
- Input array.
- axes : shape tuple
- Axes to be summed over.
+ a, b : array_like, len(shape) >= 1
+ Tensors to "dot".
+
+ axes : variable type
+
+ * integer_like scalar
+ Number of axes to sum over (applies to both arrays); or
+
+ * array_like, shape = (2,), both elements array_like
+ Axes to be summed over, first sequence applying to ``a``, second
+ to ``b``.
See Also
--------
- dot
+ numpy.dot
Notes
-----
- r_{xxx, yyy} = \\sum_k a_{xxx,k} b_{k,yyy}
-
- When there is more than one axis to sum over, the corresponding
- arguments to axes should be sequences of the same length with the first
- axis to sum over given first in both sequences, the second axis second,
- and so forth.
-
- If the `axes` argument is an integer, N, then the last N dimensions of `a`
- and first N dimensions of `b` are summed over.
+ When there is more than one axis to sum over - and they are not the last
+ (first) axes of ``a`` (``b``) - the argument ``axes`` should consist of
+ two sequences of the same length, with the first axis to sum over given
+ first in both sequences, the second axis second, and so forth.
Examples
--------
+ A "traditional" example:
+
>>> a = np.arange(60.).reshape(3,4,5)
>>> b = np.arange(24.).reshape(4,3,2)
>>> c = np.tensordot(a,b, axes=([1,0],[0,1]))
@@ -850,14 +896,62 @@ def tensordot(a, b, axes=2):
[ 4664., 5018.],
[ 4796., 5162.],
[ 4928., 5306.]])
-
>>> # A slower but equivalent way of computing the same...
- >>> c = np.zeros((5,2))
+ >>> d = np.zeros((5,2))
>>> for i in range(5):
... for j in range(2):
... for k in range(3):
... for n in range(4):
- ... c[i,j] += a[k,n,i] * b[n,k,j]
+ ... d[i,j] += a[k,n,i] * b[n,k,j]
+ >>> c == d
+ array([[ True, True],
+ [ True, True],
+ [ True, True],
+ [ True, True],
+ [ True, True]], dtype=bool)
+
+ An extended example taking advantage of the overloading of + and \\*:
+
+ >>> a = np.array(range(1, 9))
+ >>> a.shape = (2, 2, 2)
+ >>> A = np.array(('a', 'b', 'c', 'd'), dtype=object)
+ >>> A.shape = (2, 2)
+ >>> a; A
+ array([[[1, 2],
+ [3, 4]],
+ [[5, 6],
+ [7, 8]]])
+ array([[a, b],
+ [c, d]], dtype=object)
+
+ >>> np.tensordot(a, A) # third argument default is 2
+ array([abbcccdddd, aaaaabbbbbbcccccccdddddddd], dtype=object)
+
+ >>> np.tensordot(a, A, 1)
+ array([[[acc, bdd],
+ [aaacccc, bbbdddd]],
+ [[aaaaacccccc, bbbbbdddddd],
+ [aaaaaaacccccccc, bbbbbbbdddddddd]]], dtype=object)
+
+ >>> np.tensordot(a, A, 0) # "Left for reader" (result too long to incl.)
+
+ >>> np.tensordot(a, A, (0, 1))
+ array([[[abbbbb, cddddd],
+ [aabbbbbb, ccdddddd]],
+ [[aaabbbbbbb, cccddddddd],
+ [aaaabbbbbbbb, ccccdddddddd]]], dtype=object)
+
+ >>> np.tensordot(a, A, (2, 1))
+ array([[[abb, cdd],
+ [aaabbbb, cccdddd]],
+ [[aaaaabbbbbb, cccccdddddd],
+ [aaaaaaabbbbbbbb, cccccccdddddddd]]], dtype=object)
+
+ >>> np.tensordot(a, A, ((0, 1), (0, 1)))
+ array([abbbcccccddddddd, aabbbbccccccdddddddd], dtype=object)
+
+ >>> np.tensordot(a, A, ((2, 1), (1, 0)))
+ array([acccbbdddd, aaaaacccccccbbbbbbdddddddd], dtype=object)
"""
try:
@@ -1384,19 +1478,26 @@ def fromfunction(function, shape, **kwargs):
Parameters
----------
- fn : callable
+ function : callable
The function is called with N parameters, each of which
represents the coordinates of the array varying along a
specific axis. For example, if `shape` were ``(2, 2)``, then
the parameters would be two arrays, ``[[0, 0], [1, 1]]`` and
- ``[[0, 1], [0, 1]]``. `fn` must be capable of operating on
+ ``[[0, 1], [0, 1]]``. `function` must be capable of operating on
arrays, and should return a scalar value.
shape : (N,) tuple of ints
Shape of the output array, which also determines the shape of
- the coordinate arrays passed to `fn`.
+ the coordinate arrays passed to `function`.
dtype : data-type, optional
- Data-type of the coordinate arrays passed to `fn`. By default,
- `dtype` is float.
+ Data-type of the coordinate arrays passed to `function`.
+ By default, `dtype` is float.
+
+ Returns
+ -------
+ out : any
+ The result of the call to `function` is passed back directly.
+ Therefore the type and shape of `out` is completely determined by
+ `function`.
See Also
--------
@@ -1404,7 +1505,7 @@ def fromfunction(function, shape, **kwargs):
Notes
-----
- Keywords other than `shape` and `dtype` are passed to the function.
+ Keywords other than `shape` and `dtype` are passed to `function`.
Examples
--------
@@ -1611,8 +1712,18 @@ _cload = load
_file = file
def load(file):
- """Wrapper around cPickle.load which accepts either a file-like object or
+ """
+ Wrapper around cPickle.load which accepts either a file-like object or
a filename.
+
+ Note that the NumPy binary format is not based on pickle/cPickle anymore.
+ For details on the preferred way of loading and saving files, see `load`
+ and `save`.
+
+ See Also
+ --------
+ load, save
+
"""
if isinstance(file, type("")):
file = _file(file,"rb")
@@ -1738,6 +1849,10 @@ def allclose(a, b, rtol=1.e-5, atol=1.e-8):
absolute(`a` - `b`) <= (`atol` + `rtol` * absolute(`b`))
+ The above equation is not symmetric in `a` and `b`, so that
+ `allclose(a, b)` might be different from `allclose(b, a)` in
+ some rare cases.
+
Examples
--------
>>> np.allclose([1e10,1e-7], [1.00001e10,1e-8])
@@ -1897,7 +2012,7 @@ def seterr(all=None, divide=None, over=None, under=None, invalid=None):
See also
--------
- seterrcall : set a callback function for the 'call' mode.
+ seterrcall : Set a callback function for the 'call' mode.
geterr, geterrcall
Notes
@@ -1935,6 +2050,14 @@ def seterr(all=None, divide=None, over=None, under=None, invalid=None):
Warning: overflow encountered in short_scalars
30464
+ Calling `seterr` with no arguments resets treatment for all floating-point
+ errors to the defaults.
+
+ >>> old_settings = np.seterr()
+ >>> np.geterr()
+ {'over': 'ignore', 'divide': 'ignore', 'invalid': 'ignore',
+ 'under': 'ignore'}
+
"""
pyvals = umath.geterrobj()
@@ -2065,7 +2188,7 @@ def seterrcall(func):
Returns
-------
- h : callable or log instance
+ h : callable, log instance or None
The old error handler.
See Also
@@ -2077,13 +2200,13 @@ def seterrcall(func):
Callback upon error:
>>> def err_handler(type, flag):
- print "Floating point error (%s), with flag %s" % (type, flag)
+ print "Floating point error (%s), with flag %s" % (type, flag)
...
>>> saved_handler = np.seterrcall(err_handler)
>>> save_err = np.seterr(all='call')
- >>> np.array([1,2,3])/0.0
+ >>> np.array([1, 2, 3]) / 0.0
Floating point error (divide by zero), with flag 1
array([ Inf, Inf, Inf])
@@ -2101,7 +2224,7 @@ def seterrcall(func):
>>> saved_handler = np.seterrcall(log)
>>> save_err = np.seterr(all='log')
- >>> np.array([1,2,3])/0.0
+ >>> np.array([1, 2, 3]) / 0.0
LOG: Warning: divide by zero encountered in divide
>>> np.seterrcall(saved_handler)
@@ -2150,9 +2273,10 @@ def geterrcall():
>>> def err_handler(type, flag):
... print "Floating point error (%s), with flag %s" % (type, flag)
>>> oldhandler = np.seterrcall(err_handler)
- >>> np.array([1,2,3])/0.0
+ >>> np.array([1, 2, 3]) / 0.0
Floating point error (divide by zero), with flag 1
array([ Inf, Inf, Inf])
+
>>> cur_handler = np.geterrcall()
>>> cur_handler is err_handler
True
@@ -2165,29 +2289,64 @@ class _unspecified(object):
_Unspecified = _unspecified()
class errstate(object):
- """with errstate(**state): --> operations in following block use given state.
-
- # Set error handling to known state.
- >>> _ = np.seterr(invalid='raise', divide='raise', over='raise',
- ... under='ignore')
-
- >>> a = -np.arange(3)
- >>> with np.errstate(invalid='ignore'): # doctest: +SKIP
- ... print np.sqrt(a) # with statement requires Python 2.5
- [ 0. -1.#IND -1.#IND]
- >>> print np.sqrt(a.astype(complex))
- [ 0.+0.j 0.+1.j 0.+1.41421356j]
- >>> print np.sqrt(a)
+ """
+ errstate(**kwargs)
+
+ Context manager for floating-point error handling.
+
+ Using an instance of `errstate` as a context manager allows statements in
+ that context to execute with a known error handling behavior. Upon entering
+ the context the error handling is set with `seterr` and `seterrcall`, and
+ upon exiting it is reset to what it was before.
+
+ Parameters
+ ----------
+ kwargs : {divide, over, under, invalid}
+ Keyword arguments. The valid keywords are the possible floating-point
+ exceptions. Each keyword should have a string value that defines the
+ treatment for the particular error. Possible values are
+ {'ignore', 'warn', 'raise', 'call', 'print', 'log'}.
+
+ See Also
+ --------
+ seterr, geterr, seterrcall, geterrcall
+
+ Notes
+ -----
+ The ``with`` statement was introduced in Python 2.5, and can only be used
+ there by importing it: ``from __future__ import with_statement``. In
+ earlier Python versions the ``with`` statement is not available.
+
+ For complete documentation of the types of floating-point exceptions and
+ treatment options, see `seterr`.
+
+ Examples
+ --------
+ >>> from __future__ import with_statement # use 'with' in Python 2.5
+ >>> olderr = np.seterr(all='ignore') # Set error handling to known state.
+
+ >>> np.arange(3) / 0.
+ array([ NaN, Inf, Inf])
+ >>> with np.errstate(divide='warn'):
+ ... np.arange(3) / 0.
+ ...
+ __main__:2: RuntimeWarning: divide by zero encountered in divide
+ array([ NaN, Inf, Inf])
+
+ >>> np.sqrt(-1)
+ nan
+ >>> with np.errstate(invalid='raise'):
+ ... np.sqrt(-1)
+ ...
Traceback (most recent call last):
- ...
+ File "<stdin>", line 2, in <module>
FloatingPointError: invalid value encountered in sqrt
- >>> with np.errstate(divide='ignore'): # doctest: +SKIP
- ... print a/0
- [0 0 0]
- >>> print a/0
- Traceback (most recent call last):
- ...
- FloatingPointError: divide by zero encountered in divide
+
+ Outside the context the error handling behavior has not changed:
+
+ >>> np.geterr()
+ {'over': 'ignore', 'divide': 'ignore', 'invalid': 'ignore',
+ 'under': 'ignore'}
"""
# Note that we don't want to run the above doctests because they will fail
diff --git a/numpy/core/numerictypes.py b/numpy/core/numerictypes.py
index 30905d443..0767d32ea 100644
--- a/numpy/core/numerictypes.py
+++ b/numpy/core/numerictypes.py
@@ -444,7 +444,43 @@ genericTypeRank = ['bool', 'int8', 'uint8', 'int16', 'uint16',
'complex192', 'complex256', 'complex512', 'object']
def maximum_sctype(t):
- """returns the sctype of highest precision of the same general kind as 't'"""
+ """
+ Return the scalar type of highest precision of the same kind as the input.
+
+ Parameters
+ ----------
+ t : dtype or dtype specifier
+ The input data type. This can be a `dtype` object or an object that
+ is convertible to a `dtype`.
+
+ Returns
+ -------
+ out : dtype
+ The highest precision data type of the same kind (`dtype.kind`) as `t`.
+
+ See Also
+ --------
+ obj2sctype, mintypecode, sctype2char
+ dtype
+
+ Examples
+ --------
+ >>> np.maximum_sctype(np.int)
+ <type 'numpy.int64'>
+ >>> np.maximum_sctype(np.uint8)
+ <type 'numpy.uint64'>
+ >>> np.maximum_sctype(np.complex)
+ <type 'numpy.complex192'>
+
+ >>> np.maximum_sctype(str)
+ <type 'numpy.string_'>
+
+ >>> np.maximum_sctype('i2')
+ <type 'numpy.int64'>
+ >>> np.maximum_sctype('f4')
+ <type 'numpy.float96'>
+
+ """
g = obj2sctype(t)
if g is None:
return t
@@ -471,8 +507,34 @@ def _python_type(t):
return allTypes[_python_types.get(t, 'object_')]
def issctype(rep):
- """Determines whether the given object represents
- a numeric array type."""
+ """
+ Determines whether the given object represents a scalar data-type.
+
+ Parameters
+ ----------
+ rep : any
+ If `rep` is an instance of a scalar dtype, True is returned. If not,
+ False is returned.
+
+ Returns
+ -------
+ out : bool
+ Boolean result of check whether `rep` is a scalar dtype.
+
+ See Also
+ --------
+ issubsctype, issubdtype, obj2sctype, sctype2char
+
+ Examples
+ --------
+ >>> np.issctype(np.int32)
+ True
+ >>> np.issctype(list)
+ False
+ >>> np.issctype(1.1)
+ False
+
+ """
if not isinstance(rep, (type, dtype)):
return False
try:
@@ -509,6 +571,33 @@ def issubclass_(arg1, arg2):
return False
def issubsctype(arg1, arg2):
+ """
+ Determine if the first argument is a subclass of the second argument.
+
+ Parameters
+ ----------
+ arg1, arg2 : dtype or dtype specifier
+ Data-types.
+
+ Returns
+ -------
+ out : bool
+ The result.
+
+ See Also
+ --------
+ issctype, issubdtype,obj2sctype
+
+ Examples
+ --------
+ >>> np.issubsctype('S8', str)
+ True
+ >>> np.issubsctype(np.array([1]), np.int)
+ True
+ >>> np.issubsctype(np.array([1]), np.float)
+ False
+
+ """
return issubclass(obj2sctype(arg1), obj2sctype(arg2))
def issubdtype(arg1, arg2):
@@ -517,9 +606,7 @@ def issubdtype(arg1, arg2):
Parameters
----------
- arg1 : dtype_like
- dtype or string representing a typecode.
- arg2 : dtype_like
+ arg1, arg2 : dtype_like
dtype or string representing a typecode.
Returns
@@ -528,6 +615,7 @@ def issubdtype(arg1, arg2):
See Also
--------
+ issubsctype, issubclass_
numpy.core.numerictypes : Overview of numpy type hierarchy.
Examples
@@ -550,6 +638,13 @@ def issubdtype(arg1, arg2):
# This dictionary allows look up based on any alias for an array data-type
class _typedict(dict):
+ """
+ Base object for a dictionary for look-up with any alias for an array dtype.
+
+ Instances of `_typedict` can not be used as dictionaries directly,
+ first they have to be populated.
+
+ """
def __getitem__(self, obj):
return dict.__getitem__(self, obj2sctype(obj))
@@ -574,6 +669,47 @@ def _construct_lookups():
_construct_lookups()
def sctype2char(sctype):
+ """
+ Return the string representation of a scalar dtype.
+
+ Parameters
+ ----------
+ sctype : scalar dtype or object
+ If a scalar dtype, the corresponding string character is
+ returned. If an object, `sctype2char` tries to infer its scalar type
+ and then return the corresponding string character.
+
+ Returns
+ -------
+ typechar : str
+ The string character corresponding to the scalar type.
+
+ Raises
+ ------
+ ValueError
+ If `sctype` is an object for which the type can not be inferred.
+
+ See Also
+ --------
+ obj2sctype, issctype, issubsctype, mintypecode
+
+ Examples
+ --------
+ >>> for sctype in [np.int32, np.float, np.complex, np.string_, np.ndarray]:
+ ... print np.sctype2char(sctype)
+ l
+ d
+ D
+ S
+ O
+
+ >>> x = np.array([1., 2-1.j])
+ >>> np.sctype2char(x)
+ 'D'
+ >>> np.sctype2char(list)
+ 'O'
+
+ """
sctype = obj2sctype(sctype)
if sctype is None:
raise ValueError, "unrecognized type"
@@ -684,27 +820,53 @@ def _can_coerce_all(dtypelist, start=0):
def find_common_type(array_types, scalar_types):
"""
- Determine common type following standard coercion rules
+ Determine common type following standard coercion rules.
Parameters
----------
array_types : sequence
- A list of dtype convertible objects representing arrays
+ A list of dtypes or dtype convertible objects representing arrays.
scalar_types : sequence
- A list of dtype convertible objects representing scalars
+ A list of dtypes or dtype convertible objects representing scalars.
Returns
-------
datatype : dtype
- The common data-type which is the maximum of the array_types
- ignoring the scalar_types unless the maximum of the scalar_types
- is of a different kind.
-
- If the kinds is not understood, then None is returned.
+ The common data type, which is the maximum of `array_types` ignoring
+ `scalar_types`, unless the maximum of `scalar_types` is of a
+ different kind (`dtype.kind`). If the kind is not understood, then
+ None is returned.
See Also
--------
- dtype
+ dtype, common_type, can_cast, mintypecode
+
+ Examples
+ --------
+ >>> np.find_common_type([], [np.int64, np.float32, np.complex])
+ dtype('complex128')
+ >>> np.find_common_type([np.int64, np.float32], [])
+ dtype('float64')
+
+ The standard casting rules ensure that a scalar cannot up-cast an
+ array unless the scalar is of a fundamentally different kind of data
+ (i.e. under a different hierarchy in the data type hierarchy) then
+ the array:
+
+ >>> np.find_common_type([np.float32], [np.int64, np.float64])
+ dtype('float32')
+
+ Complex is of a different type, so it up-casts the float in the
+ `array_types` argument:
+
+ >>> np.find_common_type([np.float32], [np.complex])
+ dtype('complex128')
+
+ Type specifier strings are convertible to dtypes and can therefore
+ be used instead of dtypes:
+
+ >>> np.find_common_type(['f4', 'f4', 'i4'], ['c8'])
+ dtype('complex128')
"""
array_types = [dtype(x) for x in array_types]
diff --git a/numpy/core/records.py b/numpy/core/records.py
index 1d5b85b97..8904674b1 100644
--- a/numpy/core/records.py
+++ b/numpy/core/records.py
@@ -79,34 +79,63 @@ def find_duplicate(list):
return dup
class format_parser:
- """Class to convert formats, names, titles description to a dtype
+ """
+ Class to convert formats, names, titles description to a dtype.
After constructing the format_parser object, the dtype attribute is
- the converted data-type.
+ the converted data-type:
+ ``dtype = format_parser(formats, names, titles).dtype``
- dtype = format_parser(formats, names, titles).dtype
+ Attributes
+ ----------
+ dtype : dtype
+ The converted data-type.
Parameters
----------
- formats : string or list
- comma-separated format descriptions --- 'f8, i4, a5'
- list of format description strings --- ['f8', 'i4', 'a5']
- names : string or (list or tuple of strings)
- comma-separated field names --- 'col1, col2, col3'
- list or tuple of field names
+ formats : str or list of str
+ The format description, either specified as a string with
+ comma-separated format descriptions in the form ``'f8, i4, a5'``, or
+ a list of format description strings in the form
+ ``['f8', 'i4', 'a5']``.
+ names : str or list/tuple of str
+ The field names, either specified as a comma-separated string in the
+ form ``'col1, col2, col3'``, or as a list or tuple of strings in the
+ form ``['col1', 'col2', 'col3']``.
+ An empty list can be used, in that case default field names
+ ('f0', 'f1', ...) are used.
titles : sequence
- sequence of title strings or unicode
- aligned : bool
- align the fields by padding as the C-compiler would
- byteorder :
+ Sequence of title strings. An empty list can be used to leave titles
+ out.
+ aligned : bool, optional
+ If True, align the fields by padding as the C-compiler would.
+ Default is False.
+ byteorder : str, optional
If specified, all the fields will be changed to the
- provided byteorder. Otherwise, the default byteorder is
- used.
+ provided byte-order. Otherwise, the default byte-order is
+ used. For all available string specifiers, see `dtype.newbyteorder`.
+
+ See Also
+ --------
+ dtype, typename, sctype2char
+
+ Examples
+ --------
+ >>> np.format_parser(['f8', 'i4', 'a5'], ['col1', 'col2', 'col3'],
+ ... ['T1', 'T2', 'T3']).dtype
+ dtype([(('T1', 'col1'), '<f8'), (('T2', 'col2'), '<i4'),
+ (('T3', 'col3'), '|S5')]
+
+ `names` and/or `titles` can be empty lists. If `titles` is an empty list,
+ titles will simply not appear. If `names` is empty, default field names
+ will be used.
+
+ >>> np.format_parser(['f8', 'i4', 'a5'], ['col1', 'col2', 'col3'],
+ ... []).dtype
+ dtype([('col1', '<f8'), ('col2', '<i4'), ('col3', '|S5')])
+ >>> np.format_parser(['f8', 'i4', 'a5'], [], []).dtype
+ dtype([('f0', '<f8'), ('f1', '<i4'), ('f2', '|S5')])
- Returns
- -------
- object
- A Python object whose dtype attribute is a data-type.
"""
def __init__(self, formats, names, titles, aligned=False, byteorder=None):
self._parseFormats(formats, aligned)