summaryrefslogtreecommitdiff
path: root/numpy/core
diff options
context:
space:
mode:
Diffstat (limited to 'numpy/core')
-rw-r--r--numpy/core/arrayprint.py164
-rw-r--r--numpy/core/code_generators/docstrings.py1944
-rw-r--r--numpy/core/defmatrix.py131
-rw-r--r--numpy/core/fromnumeric.py1381
-rw-r--r--numpy/core/memmap.py133
-rw-r--r--numpy/core/numeric.py1093
-rw-r--r--numpy/core/records.py140
7 files changed, 4074 insertions, 912 deletions
diff --git a/numpy/core/arrayprint.py b/numpy/core/arrayprint.py
index 377457e23..8400802f7 100644
--- a/numpy/core/arrayprint.py
+++ b/numpy/core/arrayprint.py
@@ -34,27 +34,60 @@ _inf_str = 'Inf'
def set_printoptions(precision=None, threshold=None, edgeitems=None,
linewidth=None, suppress=None,
nanstr=None, infstr=None):
- """Set options associated with printing.
-
- :Parameters:
- precision : int
- Number of digits of precision for floating point output (default 8).
- threshold : int
- Total number of array elements which trigger summarization
- rather than full repr (default 1000).
- edgeitems : int
- Number of array items in summary at beginning and end of
- each dimension (default 3).
- linewidth : int
- The number of characters per line for the purpose of inserting
- line breaks (default 75).
- suppress : bool
- Whether or not suppress printing of small floating point values
- using scientific notation (default False).
- nanstr : string
- String representation of floating point not-a-number (default nan).
- infstr : string
- String representation of floating point infinity (default inf).
+ """
+ Set printing options.
+
+ These options determine the way floating point numbers, arrays and
+ other NumPy objects are displayed.
+
+ Parameters
+ ----------
+ precision : int
+ Number of digits of precision for floating point output (default 8).
+ threshold : int
+ Total number of array elements which trigger summarization
+ rather than full repr (default 1000).
+ edgeitems : int
+ Number of array items in summary at beginning and end of
+ each dimension (default 3).
+ linewidth : int
+ The number of characters per line for the purpose of inserting
+ line breaks (default 75).
+ suppress : bool
+ Whether or not suppress printing of small floating point values
+ using scientific notation (default False).
+ nanstr : string
+ String representation of floating point not-a-number (default nan).
+ infstr : string
+ String representation of floating point infinity (default inf).
+
+ Examples
+ --------
+ Floating point precision can be set:
+
+ >>> np.set_printoptions(precision=4)
+ >>> print np.array([1.123456789])
+ [ 1.1235]
+
+ Long arrays can be summarised:
+
+ >>> np.set_printoptions(threshold=5)
+ >>> print np.arange(10)
+ [0 1 2 ..., 7 8 9]
+
+ Small results can be suppressed:
+
+ >>> eps = np.finfo(float).eps
+ >>> x = np.arange(4.)
+
+ >>> x**2 - (x + eps)**2
+ array([ -4.9304e-32, -4.4409e-16, 0.0000e+00, 0.0000e+00])
+
+ >>> np.set_printoptions(suppress=True)
+
+ >>> x**2 - (x + eps)**2
+ array([-0., -0., 0., 0.])
+
"""
global _summaryThreshold, _summaryEdgeItems, _float_output_precision, \
@@ -75,20 +108,26 @@ def set_printoptions(precision=None, threshold=None, edgeitems=None,
_inf_str = infstr
def get_printoptions():
- """Return the current print options.
-
- :Returns:
- dictionary of current print options with keys
- - precision : int
- - threshold : int
- - edgeitems : int
- - linewidth : int
- - suppress : bool
- - nanstr : string
- - infstr : string
-
- :SeeAlso:
- - set_printoptions : parameter descriptions
+ """
+ Return the current print options.
+
+ Returns
+ -------
+ print_opts : dict
+ Dictionary of current print options with keys
+
+ - precision : int
+ - threshold : int
+ - edgeitems : int
+ - linewidth : int
+ - suppress : bool
+ - nanstr : string
+ - infstr : string
+
+ See Also
+ --------
+ set_printoptions : parameter descriptions
+
"""
d = dict(precision=_float_output_precision,
threshold=_summaryThreshold,
@@ -192,34 +231,41 @@ def _convert_arrays(obj):
def array2string(a, max_line_width = None, precision = None,
suppress_small = None, separator=' ', prefix="",
style=repr):
- """Return a string representation of an array.
-
- :Parameters:
- a : ndarray
- Input array.
- max_line_width : int
- The maximum number of columns the string should span. Newline
- characters splits the string appropriately after array elements.
- precision : int
- Floating point precision.
- suppress_small : bool
- Represent very small numbers as zero.
- separator : string
- Inserted between elements.
- prefix : string
- An array is typically printed as
-
- 'prefix(' + array2string(a) + ')'
-
- The length of the prefix string is used to align the
- output correctly.
- style : function
+ """
+ Return a string representation of an array.
+
+ Parameters
+ ----------
+ a : ndarray
+ Input array.
+ max_line_width : int, optional
+ The maximum number of columns the string should span. Newline
+ characters splits the string appropriately after array elements.
+ precision : int, optional
+ Floating point precision.
+ suppress_small : bool, optional
+ Represent very small numbers as zero.
+ separator : string, optional
+ Inserted between elements.
+ prefix : string, optional
+ An array is typically printed as::
+
+ 'prefix(' + array2string(a) + ')'
+
+ The length of the prefix string is used to align the
+ output correctly.
+ style : function, optional
+ Callable.
+
+ See Also
+ --------
+ array_str, array_repr
Examples
--------
-
>>> x = np.array([1e-16,1,2,3])
- >>> print np.core.array2string(x,precision=2,separator=',',suppress_small=True)
+ >>> print np.array2string(x, precision=2, separator=',',
+ ... suppress_small=True)
[ 0., 1., 2., 3.]
"""
diff --git a/numpy/core/code_generators/docstrings.py b/numpy/core/code_generators/docstrings.py
index 3a85221da..e6e6ab0f2 100644
--- a/numpy/core/code_generators/docstrings.py
+++ b/numpy/core/code_generators/docstrings.py
@@ -11,25 +11,181 @@ def add_newdoc(place, name, doc):
add_newdoc('numpy.core.umath', 'absolute',
"""
- Takes |x| elementwise.
+ Calculate the absolute value elementwise.
+
+ Parameters
+ ----------
+ x : array_like
+ An array-like sequence of values or a scalar.
+
+ Returns
+ -------
+ res : {ndarray, scalar}
+ An ndarray containing the absolute value of
+ each element in `x`. For complex input, ``a + ib``, the
+ absolute value is :math:`\\sqrt{ a^2 + b^2 }`.
+
+ Returns a scalar for scalar input.
+
+ Examples
+ --------
+ >>> x = np.array([-1.2, 1.2])
+ >>> np.absolute(x)
+ array([ 1.2, 1.2])
+ >>> np.absolute(1.2 + 1j)
+ 1.5620499351813308
+
+ Plot the function over ``[-10, 10]``:
+
+ >>> import matplotlib.pyplot as plt
+
+ >>> x = np.linspace(-10, 10, 101)
+ >>> plt.plot(x, np.absolute(x))
+ >>> plt.show()
+
+ Plot the function over the complex plane:
+
+ >>> xx = x + 1j * x[:, np.newaxis]
+ >>> plt.imshow(np.abs(xx), extent=[-10, 10, -10, 10])
+ >>> plt.show()
""")
add_newdoc('numpy.core.umath', 'add',
"""
- Adds the arguments elementwise.
+ Add arguments element-wise.
+
+ Parameters
+ ----------
+ x1, x2 : array_like
+ The arrays to be added.
+
+ Returns
+ -------
+ y : {ndarray, scalar}
+ The sum of `x1` and `x2`, element-wise. Returns scalar if
+ both `x1` and `x2` are scalars.
+
+ Notes
+ -----
+ Equivalent to `x1` + `x2` in terms of array broadcasting.
+
+ Examples
+ --------
+ >>> np.add(1.0, 4.0)
+ 5.0
+ >>> x1 = np.arange(9.0).reshape((3, 3))
+ >>> x2 = np.arange(3.0)
+ >>> np.add(x1, x2)
+ array([[ 0., 2., 4.],
+ [ 3., 5., 7.],
+ [ 6., 8., 10.]])
""")
add_newdoc('numpy.core.umath', 'arccos',
"""
- Inverse cosine elementwise.
+ Trigonometric inverse cosine, element-wise.
+
+ The inverse of `cos` so that, if ``y = cos(x)``, then ``x = arccos(y)``.
+
+ Parameters
+ ----------
+ x : array_like
+ `x`-coordinate on the unit circle.
+ For real arguments, the domain is [-1, 1].
+
+ Returns
+ -------
+ angle : {ndarray, scalar}
+ The angle of the ray intersecting the unit circle at the given
+ `x`-coordinate in radians [0, pi]. If `x` is a scalar then a
+ scalar is returned, otherwise an array of the same shape as `x`
+ is returned.
+
+ See Also
+ --------
+ cos, arctan, arcsin
+
+ Notes
+ -----
+ `arccos` is a multivalued function: for each `x` there are infinitely
+ many numbers `z` such that `cos(z) = x`. The convention is to return the
+ angle `z` whose real part lies in `[0, pi]`.
+
+ For real-valued input data types, `arccos` 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, `arccos` is a complex analytical function that
+ has branch cuts `[-inf, -1]` and `[1, inf]` and is continuous from above
+ on the former and from below on the latter.
+
+ The inverse `cos` is also known as `acos` or cos^-1.
+
+ References
+ ----------
+ .. [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
+
+ Examples
+ --------
+ We expect the arccos of 1 to be 0, and of -1 to be pi:
+
+ >>> np.arccos([1, -1])
+ array([ 0. , 3.14159265])
+
+ Plot arccos:
+
+ >>> import matplotlib.pyplot as plt
+ >>> x = np.linspace(-1, 1, num=100)
+ >>> plt.plot(x, np.arccos(x))
+ >>> plt.axis('tight')
+ >>> plt.show()
""")
add_newdoc('numpy.core.umath', 'arccosh',
"""
- Inverse hyperbolic cosine elementwise.
+ Inverse hyperbolic cosine, elementwise.
+
+ Parameters
+ ----------
+ x : array_like
+ Input array.
+
+ Returns
+ -------
+ out : {ndarray, scalar}
+ Array of the same shape and dtype as `x`.
+
+ Notes
+ -----
+ `arccosh` is a multivalued function: for each `x` there are infinitely
+ many numbers `z` such that `cosh(z) = x`. The convention is to return the
+ `z` whose imaginary part lies in `[-pi, pi]` and the real part in
+ ``[0, inf]``.
+
+ For real-valued input data types, `arccosh` 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, `arccosh` is a complex analytical function that
+ has a branch cut `[-inf, 1]` and is continuous from above on it.
+
+ References
+ ----------
+ .. [1] M. Abramowitz and I.A. Stegun, "Handbook of Mathematical Functions",
+ 10th printing, 1964, pp. 86. http://www.math.sfu.ca/~cbm/aands/
+ .. [2] Wikipedia, "Inverse hyperbolic function",
+ http://en.wikipedia.org/wiki/Arccosh
+
+ Examples
+ --------
+ >>> np.arccosh([np.e, 10.0])
+ array([ 1.65745445, 2.99322285])
""")
@@ -37,23 +193,234 @@ add_newdoc('numpy.core.umath', 'arcsin',
"""
Inverse sine elementwise.
+ Parameters
+ ----------
+ x : array_like
+ `y`-coordinate on the unit circle.
+
+ Returns
+ -------
+ angle : {ndarray, scalar}
+ The angle of the ray intersecting the unit circle at the given
+ `y`-coordinate in radians ``[-pi, pi]``. If `x` is a scalar then
+ a scalar is returned, otherwise an array is returned.
+
+ See Also
+ --------
+ sin, arctan, arctan2
+
+ Notes
+ -----
+ `arcsin` is a multivalued function: for each `x` there are infinitely
+ many numbers `z` such that `sin(z) = x`. The convention is to return the
+ angle `z` whose real part lies in `[-pi/2, pi/2]`.
+
+ For real-valued input data types, `arcsin` 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, `arcsin` is a complex analytical function that
+ has branch cuts `[-inf, -1]` and `[1, inf]` and is continuous from above
+ on the former and from below on the latter.
+
+ The inverse sine is also known as `asin` or ``sin^-1``.
+
+ References
+ ----------
+ .. [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
+
+ Examples
+ --------
+ >>> np.arcsin(1) # pi/2
+ 1.5707963267948966
+ >>> np.arcsin(-1) # -pi/2
+ -1.5707963267948966
+ >>> np.arcsin(0)
+ 0.0
+
""")
add_newdoc('numpy.core.umath', 'arcsinh',
"""
Inverse hyperbolic sine elementwise.
+ Parameters
+ ----------
+ x : array_like
+ Input array.
+
+ Returns
+ -------
+ out : ndarray
+ Array of of the same shape as `x`.
+
+ Notes
+ -----
+ `arcsinh` is a multivalued function: for each `x` there are infinitely
+ many numbers `z` such that `sinh(z) = x`. The convention is to return the
+ `z` whose imaginary part lies in `[-pi/2, pi/2]`.
+
+ For real-valued input data types, `arcsinh` 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, `arccos` is a complex analytical function that
+ has branch cuts `[1j, infj]` and `[-1j, -infj]` and is continuous from
+ the right on the former and from the left on the latter.
+
+ The inverse hyperbolic sine is also known as `asinh` or ``sinh^-1``.
+
+ References
+ ----------
+ .. [1] M. Abramowitz and I.A. Stegun, "Handbook of Mathematical Functions",
+ 10th printing, 1964, pp. 86. http://www.math.sfu.ca/~cbm/aands/
+ .. [2] Wikipedia, "Inverse hyperbolic function",
+ http://en.wikipedia.org/wiki/Arcsinh
+
+ Examples
+ --------
+ >>> np.arcsinh(np.array([np.e, 10.0]))
+ array([ 1.72538256, 2.99822295])
+
""")
add_newdoc('numpy.core.umath', 'arctan',
"""
- Inverse tangent elementwise.
+ Trigonometric inverse tangent, element-wise.
+
+ The inverse of tan, so that if ``y = tan(x)`` then
+ ``x = arctan(y)``.
+
+ Parameters
+ ----------
+ x : {array_like, scalar}
+ Input values. `arctan` is applied to each element of `x`.
+
+ Returns
+ -------
+ out : {ndarray, scalar}
+ Out has the same shape as `x`. Its real part is
+ in ``[-pi/2, pi/2]``. It is a scalar if `x` is a scalar.
+
+ See Also
+ --------
+ arctan2 : Calculate the arctan of y/x.
+
+ Notes
+ -----
+ `arctan` is a multivalued function: for each `x` there are infinitely
+ many numbers `z` such that `tan(z) = x`. The convention is to return the
+ angle `z` whose real part lies in `[-pi/2, pi/2]`.
+
+ For real-valued input data types, `arctan` 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, `arctan` is a complex analytical function that
+ has branch cuts `[1j, infj]` and `[-1j, -infj]` and is continuous from the
+ left on the former and from the right on the latter.
+
+ The inverse tangent is also known as `atan` or ``tan^-1``.
+
+ References
+ ----------
+ .. [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/Arctan
+
+ Examples
+ --------
+ We expect the arctan of 0 to be 0, and of 1 to be :math:`\\pi/4`:
+
+ >>> np.arctan([0, 1])
+ array([ 0. , 0.78539816])
+
+ >>> np.pi/4
+ 0.78539816339744828
+
+ Plot arctan:
+
+ >>> import matplotlib.pyplot as plt
+ >>> x = np.linspace(-10, 10)
+ >>> plt.plot(x, np.arctan(x))
+ >>> plt.axis('tight')
+ >>> plt.show()
""")
add_newdoc('numpy.core.umath', 'arctan2',
"""
- A safe and correct arctan(x1/x2)
+ Elementwise arc tangent of ``x1/x2`` choosing the quadrant correctly.
+
+ The quadrant (ie. branch) is chosen so that ``arctan2(x1, x2)``
+ is the signed angle in radians between the line segments
+ ``(0,0) - (1,0)`` and ``(0,0) - (x2,x1)``. This function is defined
+ also for `x2` = 0.
+
+ `arctan2` is not defined for complex-valued arguments.
+
+ Parameters
+ ----------
+ x1 : array-like, real-valued
+ y-coordinates.
+ x2 : array-like, real-valued
+ x-coordinates. `x2` must be broadcastable to match the shape of `x1`,
+ or vice versa.
+
+ Returns
+ -------
+ angle : array-like
+ Array of angles in radians, in the range ``[-pi, pi]``.
+
+ See Also
+ --------
+ arctan, tan
+
+ Notes
+ -----
+ `arctan2` is identical to the `atan2` function of the underlying
+ C library. The following special values are defined in the C standard [2]:
+
+ ====== ====== ================
+ `x1` `x2` `arctan2(x1,x2)`
+ ====== ====== ================
+ +/- 0 +0 +/- 0
+ +/- 0 -0 +/- pi
+ > 0 +/-inf +0 / +pi
+ < 0 +/-inf -0 / -pi
+ +/-inf +inf +/- (pi/4)
+ +/-inf -inf +/- (3*pi/4)
+ ====== ====== ================
+
+ Note that +0 and -0 are distinct floating point numbers.
+
+ References
+ ----------
+ .. [1] Wikipedia, "atan2",
+ http://en.wikipedia.org/wiki/Atan2
+ .. [2] ISO/IEC standard 9899:1999, "Programming language C", 1999.
+
+ Examples
+ --------
+ Consider four points in different quadrants:
+
+ >>> x = np.array([-1, +1, +1, -1])
+ >>> y = np.array([-1, -1, +1, +1])
+ >>> np.arctan2(y, x) * 180 / np.pi
+ array([-135., -45., 45., 135.])
+
+ Note the order of the parameters. `arctan2` is defined also when `x2` = 0
+ and at several other special points, obtaining values in
+ the range ``[-pi, pi]``:
+
+ >>> np.arctan2([1., -1.], [0., 0.])
+ array([ 1.57079633, -1.57079633])
+ >>> np.arctan2([0., 0., np.inf], [+0., -0., np.inf])
+ array([ 0. , 3.14159265, 0.78539816])
""")
@@ -61,35 +428,284 @@ add_newdoc('numpy.core.umath', 'arctanh',
"""
Inverse hyperbolic tangent elementwise.
+ Parameters
+ ----------
+ x : array_like
+ Input array.
+
+ Returns
+ -------
+ out : ndarray
+ Array of the same shape as `x`.
+
+ Notes
+ -----
+ `arctanh` is a multivalued function: for each `x` there are infinitely
+ many numbers `z` such that `tanh(z) = x`. The convention is to return the
+ `z` whose imaginary part lies in `[-pi/2, pi/2]`.
+
+ For real-valued input data types, `arctanh` 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, `arctanh` is a complex analytical function that
+ has branch cuts `[-1, -inf]` and `[1, inf]` and is continuous from
+ above on the former and from below on the latter.
+
+ The inverse hyperbolic tangent is also known as `atanh` or ``tanh^-1``.
+
+ References
+ ----------
+ .. [1] M. Abramowitz and I.A. Stegun, "Handbook of Mathematical Functions",
+ 10th printing, 1964, pp. 86. http://www.math.sfu.ca/~cbm/aands/
+ .. [2] Wikipedia, "Inverse hyperbolic function",
+ http://en.wikipedia.org/wiki/Arctanh
+
+ Examples
+ --------
+ >>> np.arctanh([0, -0.5])
+ array([ 0. , -0.54930614])
+
""")
add_newdoc('numpy.core.umath', 'bitwise_and',
"""
- Computes x1 & x2 elementwise.
+ Compute bit-wise AND of two arrays, element-wise.
+
+ When calculating the bit-wise AND between two elements, ``x`` and ``y``,
+ each element is first converted to its binary representation (which works
+ just like the decimal system, only now we're using 2 instead of 10):
+
+ .. math:: x = \\sum_{i=0}^{W-1} a_i \\cdot 2^i\\\\\n y = \\sum_{i=0}^{W-1} b_i \\cdot 2^i,
+
+ where ``W`` is the bit-width of the type (i.e., 8 for a byte or uint8),
+ and each :math:`a_i` and :math:`b_j` is either 0 or 1. For example, 13
+ is represented as ``00001101``, which translates to
+ :math:`2^4 + 2^3 + 2`.
+
+ The bit-wise operator is the result of
+
+ .. math:: z = \\sum_{i=0}^{i=W-1} (a_i \\wedge b_i) \\cdot 2^i,
+
+ where :math:`\\wedge` is the AND operator, which yields one whenever
+ both :math:`a_i` and :math:`b_i` are 1.
+
+ Parameters
+ ----------
+ x1, x2 : array_like
+ Only integer types are handled (including booleans).
+
+ Returns
+ -------
+ out : array_like
+ Result.
+
+ See Also
+ --------
+ bitwise_or, bitwise_xor
+ logical_and
+ binary_repr :
+ Return the binary representation of the input number as a string.
+
+ Examples
+ --------
+ We've seen that 13 is represented by ``00001101``. Similary, 17 is
+ represented by ``00010001``. The bit-wise AND of 13 and 17 is
+ therefore ``000000001``, or 1:
+
+ >>> np.bitwise_and(13, 17)
+ 1
+
+ >>> np.bitwise_and(14, 13)
+ 12
+ >>> np.binary_repr(12)
+ '1100'
+ >>> np.bitwise_and([14,3], 13)
+ array([12, 1])
+
+ >>> np.bitwise_and([11,7], [4,25])
+ array([0, 1])
+ >>> np.bitwise_and(np.array([2,5,255]), np.array([3,14,16]))
+ array([ 2, 4, 16])
+ >>> np.bitwise_and([True, True], [False, True])
+ array([False, True], dtype=bool)
""")
add_newdoc('numpy.core.umath', 'bitwise_or',
"""
- Computes x1 | x2 elementwise.
+ Compute bit-wise OR of two arrays, element-wise.
+
+ When calculating the bit-wise OR between two elements, ``x`` and ``y``,
+ each element is first converted to its binary representation (which works
+ just like the decimal system, only now we're using 2 instead of 10):
+
+ .. math:: x = \\sum_{i=0}^{W-1} a_i \\cdot 2^i\\\\\n y = \\sum_{i=0}^{W-1} b_i \\cdot 2^i,
+
+ where ``W`` is the bit-width of the type (i.e., 8 for a byte or uint8),
+ and each :math:`a_i` and :math:`b_j` is either 0 or 1. For example, 13
+ is represented as ``00001101``, which translates to
+ :math:`2^4 + 2^3 + 2`.
+
+ The bit-wise operator is the result of
+
+ .. math:: z = \\sum_{i=0}^{i=W-1} (a_i \\vee b_i) \\cdot 2^i,
+
+ where :math:`\\vee` is the OR operator, which yields one whenever
+ either :math:`a_i` or :math:`b_i` is 1.
+
+ Parameters
+ ----------
+ x1, x2 : array_like
+ Only integer types are handled (including booleans).
+
+ Returns
+ -------
+ out : array_like
+ Result.
+
+ See Also
+ --------
+ bitwise_and, bitwise_xor
+ logical_or
+ binary_repr :
+ Return the binary representation of the input number as a string.
+
+ Examples
+ --------
+ We've seen that 13 is represented by ``00001101``. Similary, 16 is
+ represented by ``00010000``. The bit-wise OR of 13 and 16 is
+ therefore ``000111011``, or 29:
+
+ >>> np.bitwise_or(13, 16)
+ 29
+ >>> np.binary_repr(29)
+ '11101'
+
+ >>> np.bitwise_or(32, 2)
+ 34
+ >>> np.bitwise_or([33, 4], 1)
+ array([33, 5])
+ >>> np.bitwise_or([33, 4], [1, 2])
+ array([33, 6])
+
+ >>> np.bitwise_or(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), \\\n... np.array([4, 4, 4, 2147483647L], dtype=np.int32))
+ array([ 6, 5, 255, 2147483647])
+ >>> np.bitwise_or([True, True], [False, True])
+ array([ True, True], dtype=bool)
""")
add_newdoc('numpy.core.umath', 'bitwise_xor',
"""
- Computes x1 ^ x2 elementwise.
+ Compute bit-wise XOR of two arrays, element-wise.
+
+ When calculating the bit-wise XOR between two elements, ``x`` and ``y``,
+ each element is first converted to its binary representation (which works
+ just like the decimal system, only now we're using 2 instead of 10):
+
+ .. math:: x = \\sum_{i=0}^{W-1} a_i \\cdot 2^i\\\\\n y = \\sum_{i=0}^{W-1} b_i \\cdot 2^i,
+
+ where ``W`` is the bit-width of the type (i.e., 8 for a byte or uint8),
+ and each :math:`a_i` and :math:`b_j` is either 0 or 1. For example, 13
+ is represented as ``00001101``, which translates to
+ :math:`2^4 + 2^3 + 2`.
+
+ The bit-wise operator is the result of
+
+ .. math:: z = \\sum_{i=0}^{i=W-1} (a_i \\oplus b_i) \\cdot 2^i,
+
+ where :math:`\\oplus` is the XOR operator, which yields one whenever
+ either :math:`a_i` or :math:`b_i` is 1, but not both.
+
+ Parameters
+ ----------
+ x1, x2 : array_like
+ Only integer types are handled (including booleans).
+
+ Returns
+ -------
+ out : ndarray
+ Result.
+
+ See Also
+ --------
+ bitwise_and, bitwise_or
+ logical_xor
+ binary_repr :
+ Return the binary representation of the input number as a string.
+
+ Examples
+ --------
+ We've seen that 13 is represented by ``00001101``. Similary, 17 is
+ represented by ``00010001``. The bit-wise XOR of 13 and 17 is
+ therefore ``00011100``, or 28:
+
+ >>> np.bitwise_xor(13, 17)
+ 28
+ >>> np.binary_repr(28)
+ '11100'
+
+ >>> np.bitwise_xor(31, 5)
+ 26
+ >>> np.bitwise_xor([31,3], 5)
+ array([26, 6])
+
+ >>> np.bitwise_xor([31,3], [5,6])
+ array([26, 5])
+ >>> np.bitwise_xor([True, True], [False, True])
+ array([ True, False], dtype=bool)
""")
add_newdoc('numpy.core.umath', 'ceil',
"""
- Elementwise smallest integer >= x.
+ Return the ceiling of the input, element-wise.
+
+ The ceil of the scalar `x` is the smallest integer `i`, such that
+ `i >= x`. It is often denoted as :math:`\\lceil x \\rceil`.
+
+ Parameters
+ ----------
+ x : array_like
+ Input data.
+
+ Returns
+ -------
+ y : {ndarray, scalar}
+ The ceiling of each element in `x`.
+
+ Examples
+ --------
+ >>> a = np.array([-1.7, -1.5, -0.2, 0.2, 1.5, 1.7, 2.0])
+ >>> np.ceil(a)
+ array([-1., -1., -0., 1., 2., 2., 2.])
""")
add_newdoc('numpy.core.umath', 'conjugate',
"""
- Takes the conjugate of x elementwise.
+ Return the complex conjugate, element-wise.
+
+ The complex conjugate of a complex number is obtained by changing the
+ sign of its imaginary part.
+
+ Parameters
+ ----------
+ x : array_like
+ Input value.
+
+ Returns
+ -------
+ y : {ndarray, scalar}
+ The complex conjugate of `x`, with same dtype as `y`.
+
+ Examples
+ --------
+ >>> np.conjugate(1+2j)
+ (1-2j)
""")
@@ -97,35 +713,225 @@ add_newdoc('numpy.core.umath', 'cos',
"""
Cosine elementwise.
+ Parameters
+ ----------
+ x : array_like
+ Input array in radians.
+
+ Returns
+ -------
+ out : ndarray
+ Output array of same shape as `x`.
+
+ Examples
+ --------
+ >>> np.cos(np.array([0, np.pi/2, np.pi]))
+ array([ 1.00000000e+00, 6.12303177e-17, -1.00000000e+00])
+
""")
add_newdoc('numpy.core.umath', 'cosh',
"""
- Hyperbolic cosine elementwise.
+ Hyperbolic cosine, element-wise.
+
+ Equivalent to ``1/2 * (np.exp(x) + np.exp(-x))`` and ``np.cos(1j*x)``.
+
+ Parameters
+ ----------
+ x : array_like
+ Input array.
+
+ Returns
+ -------
+ out : ndarray
+ Output array of same shape as `x`.
+
+ Examples
+ --------
+ >>> np.cosh(0)
+ 1.0
+
+ The hyperbolic cosine describes the shape of a hanging cable:
+
+ >>> import matplotlib.pyplot as plt
+ >>> x = np.linspace(-4, 4, 1000)
+ >>> plt.plot(x, np.cosh(x))
+ >>> plt.show()
""")
add_newdoc('numpy.core.umath', 'degrees',
"""
- Converts angle from radians to degrees
+ Convert angles from radians to degrees.
+
+ Parameters
+ ----------
+ x : array-like
+ Angle in radians.
+
+ Returns
+ -------
+ y : {ndarray, scalar}
+ The corresponding angle in degrees.
+
+
+ See Also
+ --------
+ radians : Convert angles from degrees to radians.
+ unwrap : Remove large jumps in angle by wrapping.
+
+ Notes
+ -----
+ degrees(x) is ``180 * x / pi``.
+
+ Examples
+ --------
+ >>> np.degrees(np.pi/2)
+ 90.0
""")
add_newdoc('numpy.core.umath', 'divide',
"""
- Divides the arguments elementwise.
+ Divide arguments element-wise.
+
+ Parameters
+ ----------
+ x1 : array_like
+ Dividend array.
+ x2 : array_like
+ Divisor array.
+
+ Returns
+ -------
+ y : {ndarray, scalar}
+ The quotient `x1/x2`, element-wise. Returns a scalar if
+ both `x1` and `x2` are scalars.
+
+ See Also
+ --------
+ seterr : Set whether to raise or warn on overflow, underflow and division
+ by zero.
+
+ Notes
+ -----
+ Equivalent to `x1` / `x2` in terms of array-broadcasting.
+
+ Behavior on division by zero can be changed using `seterr`.
+
+ When both `x1` and `x2` are of an integer type, `divide` will return
+ integers and throw away the fractional part. Moreover, division by zero
+ always yields zero in integer arithmetic.
+
+ Examples
+ --------
+ >>> np.divide(2.0, 4.0)
+ 0.5
+ >>> x1 = np.arange(9.0).reshape((3, 3))
+ >>> x2 = np.arange(3.0)
+ >>> np.divide(x1, x2)
+ array([[ NaN, 1. , 1. ],
+ [ Inf, 4. , 2.5],
+ [ Inf, 7. , 4. ]])
+
+ Note the behavior with integer types:
+
+ >>> np.divide(2, 4)
+ 0
+ >>> np.divide(2, 4.)
+ 0.5
+
+ Division by zero always yields zero in integer arithmetic, and does not
+ raise an exception or a warning:
+
+ >>> np.divide(np.array([0, 1], dtype=int), np.array([0, 0], dtype=int))
+ array([0, 0])
+
+ Division by zero can, however, be caught using `seterr`:
+
+ >>> old_err_state = np.seterr(divide='raise')
+ >>> np.divide(1, 0)
+ Traceback (most recent call last):
+ File "<stdin>", line 1, in <module>
+ FloatingPointError: divide by zero encountered in divide
+
+ >>> ignored_states = np.seterr(**old_err_state)
+ >>> np.divide(1, 0)
+ 0
""")
add_newdoc('numpy.core.umath', 'equal',
"""
- Returns elementwise x1 == x2 in a bool array
+ Returns elementwise x1 == x2 in a bool array.
+
+ Parameters
+ ----------
+ x1, x2 : array_like
+ Input arrays of the same shape.
+
+ Returns
+ -------
+ out : boolean
+ The elementwise test `x1` == `x2`.
""")
add_newdoc('numpy.core.umath', 'exp',
"""
- e**x elementwise.
+ Calculate the exponential of the elements in the input array.
+
+ Parameters
+ ----------
+ x : array_like
+ Input values.
+
+ Returns
+ -------
+ out : ndarray
+ Element-wise exponential of `x`.
+
+ Notes
+ -----
+ The irrational number ``e`` is also known as Euler's number. It is
+ approximately 2.718281, and is the base of the natural logarithm,
+ ``ln`` (this means that, if :math:`x = \\ln y = \\log_e y`,
+ then :math:`e^x = y`. For real input, ``exp(x)`` is always positive.
+
+ For complex arguments, ``x = a + ib``, we can write
+ :math:`e^x = e^a e^{ib}`. The first term, :math:`e^a`, is already
+ known (it is the real argument, described above). The second term,
+ :math:`e^{ib}`, is :math:`\\cos b + i \\sin b`, a function with magnitude
+ 1 and a periodic phase.
+
+ References
+ ----------
+ .. [1] Wikipedia, "Exponential function",
+ http://en.wikipedia.org/wiki/Exponential_function
+ .. [2] M. Abramovitz and I. A. Stegun, "Handbook of Mathematical Functions
+ with Formulas, Graphs, and Mathematical Tables," Dover, 1964, p. 69,
+ http://www.math.sfu.ca/~cbm/aands/page_69.htm
+
+ Examples
+ --------
+ Plot the magnitude and phase of ``exp(x)`` in the complex plane:
+
+ >>> import matplotlib.pyplot as plt
+
+ >>> x = np.linspace(-2*np.pi, 2*np.pi, 100)
+ >>> xx = x + 1j * x[:, np.newaxis] # a + ib over complex plane
+ >>> out = np.exp(xx)
+
+ >>> plt.subplot(121)
+ >>> plt.imshow(np.abs(out),
+ ... extent=[-2*np.pi, 2*np.pi, -2*np.pi, 2*np.pi])
+ >>> plt.title('Magnitude of exp(x)')
+
+ >>> plt.subplot(122)
+ >>> plt.imshow(np.angle(out),
+ ... extent=[-2*np.pi, 2*np.pi, -2*np.pi, 2*np.pi])
+ >>> plt.title('Phase (angle) of exp(x)')
+ >>> plt.show()
""")
@@ -137,67 +943,368 @@ add_newdoc('numpy.core.umath', 'expm1',
add_newdoc('numpy.core.umath', 'fabs',
"""
- Absolute values.
+ Compute the absolute values elementwise.
+
+ This function returns the absolute values (positive magnitude) of the data
+ in `x`. Complex values are not handled, use `absolute` to find the
+ absolute values of complex data.
+
+ Parameters
+ ----------
+ x : array_like
+ The array of numbers for which the absolute values are required. If
+ `x` is a scalar, the result `y` will also be a scalar.
+
+ Returns
+ -------
+ y : {ndarray, scalar}
+ The absolute values of `x`, the returned values are always floats.
+
+ See Also
+ --------
+ absolute : Absolute values including `complex` types.
+
+ Examples
+ --------
+ >>> np.fabs(-1)
+ 1.0
+ >>> np.fabs([-1.2, 1.2])
+ array([ 1.2, 1.2])
""")
add_newdoc('numpy.core.umath', 'floor',
"""
- Elementwise largest integer <= x
+ Return the floor of the input, element-wise.
+
+ The floor of the scalar `x` is the largest integer `i`, such that
+ `i <= x`. It is often denoted as :math:`\\lfloor x \\rfloor`.
+
+ Parameters
+ ----------
+ x : array_like
+ Input data.
+
+ Returns
+ -------
+ y : {ndarray, scalar}
+ The floor of each element in `x`.
+
+ Notes
+ -----
+ Some spreadsheet programs calculate the "floor-towards-zero", in other
+ words ``floor(-2.5) == -2``. NumPy, however, uses the a definition of
+ `floor` such that `floor(-2.5) == -3``.
+
+ Examples
+ --------
+ >>> a = np.array([-1.7, -1.5, -0.2, 0.2, 1.5, 1.7, 2.0])
+ >>> np.floor(a)
+ array([-2., -2., -1., 0., 1., 1., 2.])
""")
add_newdoc('numpy.core.umath', 'floor_divide',
"""
- Floor divides the arguments elementwise.
+ Return the largest integer smaller or equal to the division of the inputs.
+
+ Parameters
+ ----------
+ x1 : array_like
+ Numerator.
+ x2 : array_like
+ Denominator.
+
+ Returns
+ -------
+ y : ndarray
+ y = floor(`x1`/`x2`)
+
+
+ See Also
+ --------
+ divide : Standard division.
+ floor : Round a number to the nearest integer toward minus infinity.
+ ceil : Round a number to the nearest integer toward infinity.
+
+ Examples
+ --------
+ >>> np.floor_divide(7,3)
+ 2
+ >>> np.floor_divide([1., 2., 3., 4.], 2.5)
+ array([ 0., 0., 1., 1.])
""")
add_newdoc('numpy.core.umath', 'fmod',
"""
- Computes (C-like) x1 % x2 elementwise.
+ Return the remainder of division.
+
+ This is the NumPy implementation of the C modulo operator `%`.
+
+ Parameters
+ ----------
+ x1 : array_like
+ Dividend.
+ x2 : array_like
+ Divisor.
+
+ Returns
+ -------
+ y : array_like
+ The remainder of the division of `x1` by `x2`.
+
+ See Also
+ --------
+ mod : Modulo operation where the quotient is `floor(x1,x2)`.
+
+ 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.
+
+ 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)
+ array([1, 0, 1, 1, 0, 1])
""")
add_newdoc('numpy.core.umath', 'greater',
"""
- Returns elementwise x1 > x2 in a bool array.
+ Return (x1 > x2) element-wise.
+
+ Parameters
+ ----------
+ x1, x2 : array_like
+ Input arrays.
+
+ Returns
+ -------
+ Out : {ndarray, bool}
+ Output array of bools, or a single bool if `x1` and `x2` are scalars.
+
+ See Also
+ --------
+ greater_equal
+
+ Examples
+ --------
+ >>> np.greater([4,2],[2,2])
+ array([ True, False], dtype=bool)
""")
add_newdoc('numpy.core.umath', 'greater_equal',
"""
- Returns elementwise x1 >= x2 in a bool array.
+ Returns (x1 >= x2) element-wise.
+
+ Parameters
+ ----------
+ x1, x2 : array_like
+ Input arrays.
+
+ Returns
+ -------
+ Out : {ndarray, bool}
+ Output array of bools, or a single bool if `x1` and `x2` are scalars.
+
+ See Also
+ --------
+ greater
+
+ Examples
+ --------
+ >>> np.greater_equal([4,2],[2,2])
+ array([ True, True], dtype=bool)
""")
add_newdoc('numpy.core.umath', 'hypot',
"""
- sqrt(x1**2 + x2**2) elementwise
+ Given two sides of a right triangle, return its hypotenuse.
+
+ Parameters
+ ----------
+ x : array-like
+ Base of the triangle.
+ y : array-like
+ Height of the triangle.
+
+ Returns
+ -------
+ z : {ndarray, scalar}
+ Hypotenuse of the triangle: sqrt(x**2 + y**2)
+
+
+ Examples
+ --------
+ >>> np.hypot(3,4)
+ 5.0
""")
add_newdoc('numpy.core.umath', 'invert',
"""
- Computes ~x (bit inversion) elementwise.
+ Compute bit-wise inversion, or bit-wise NOT, element-wise.
+
+ When calculating the bit-wise NOT of an element ``x``, each element is
+ first converted to its binary representation (which works
+ just like the decimal system, only now we're using 2 instead of 10):
+
+ .. math:: x = \\sum_{i=0}^{W-1} a_i \\cdot 2^i
+
+ where ``W`` is the bit-width of the type (i.e., 8 for a byte or uint8),
+ and each :math:`a_i` is either 0 or 1. For example, 13 is represented
+ as ``00001101``, which translates to :math:`2^4 + 2^3 + 2`.
+
+ The bit-wise operator is the result of
+
+ .. math:: z = \\sum_{i=0}^{i=W-1} (\\lnot a_i) \\cdot 2^i,
+
+ where :math:`\\lnot` is the NOT operator, which yields 1 whenever
+ :math:`a_i` is 0 and yields 0 whenever :math:`a_i` is 1.
+
+ For signed integer inputs, the two's complement is returned.
+ In a two's-complement system negative numbers are represented by the two's
+ complement of the absolute value. This is the most common method of
+ representing signed integers on computers [1]_. A N-bit two's-complement
+ system can represent every integer in the range
+ :math:`-2^{N-1}` to :math:`+2^{N-1}-1`.
+
+ Parameters
+ ----------
+ x1 : ndarray
+ Only integer types are handled (including booleans).
+
+ Returns
+ -------
+ out : ndarray
+ Result.
+
+ See Also
+ --------
+ bitwise_and, bitwise_or, bitwise_xor
+ logical_not
+ binary_repr :
+ Return the binary representation of the input number as a string.
+
+ Notes
+ -----
+ `bitwise_not` is an alias for `invert`:
+
+ >>> np.bitwise_not is np.invert
+ True
+
+ References
+ ----------
+ .. [1] Wikipedia, "Two's complement",
+ http://en.wikipedia.org/wiki/Two's_complement
+
+ Examples
+ --------
+ We've seen that 13 is represented by ``00001101``.
+ The invert or bit-wise NOT of 13 is then:
+
+ >>> np.invert(np.array([13], dtype=uint8))
+ array([242], dtype=uint8)
+ >>> np.binary_repr(x, width=8)
+ '00001101'
+ >>> np.binary_repr(242, width=8)
+ '11110010'
+
+ The result depends on the bit-width:
+
+ >>> np.invert(np.array([13], dtype=uint16))
+ array([65522], dtype=uint16)
+ >>> np.binary_repr(x, width=16)
+ '0000000000001101'
+ >>> np.binary_repr(65522, width=16)
+ '1111111111110010'
+
+ When using signed integer types the result is the two's complement of
+ the result for the unsigned type:
+
+ >>> np.invert(np.array([13], dtype=int8))
+ array([-14], dtype=int8)
+ >>> np.binary_repr(-14, width=8)
+ '11110010'
+
+ Booleans are accepted as well:
+
+ >>> np.invert(array([True, False]))
+ array([False, True], dtype=bool)
""")
add_newdoc('numpy.core.umath', 'isfinite',
"""
- Returns True where x is finite
+ Returns True where x is finite, False otherwise.
+
+ Parameters
+ ----------
+ x : array_like
+ input values
+
+ Returns
+ -------
+ y : {ndarray, bool}
+ array of bools
+
+ Notes
+ -----
+ `Nan` is considered as non-finite.
+
+ Examples
+ --------
+ >>> np.isfinite([np.log(-1.),1.,np.log(0)])
+ array([False, True, False], dtype=bool)
""")
add_newdoc('numpy.core.umath', 'isinf',
"""
- Returns True where x is +inf or -inf
+ Returns True where x is +inf or -inf, False otherwise.
+
+ Parameters
+ ----------
+ x : array_like
+ input values
+
+ Returns
+ -------
+ y : {ndarray, bool}
+ array of bools
+
+ Examples
+ --------
+ >>> np.isinf([np.inf, -np.inf, 1.0, np.nan])
+ array([ True, True, False, False], dtype=bool)
""")
add_newdoc('numpy.core.umath', 'isnan',
"""
- Returns True where x is Not-A-Number
+ Returns True where elements are Not-A-Number, False otherwise.
+
+ Parameters
+ ----------
+ x : array_like
+ input values.
+
+ Returns
+ -------
+ y : {ndarray, bool}
+ array of bools
+
+ Examples
+ --------
+ >>> np.isnan([np.log(-1.),1.,np.log(0)])
+ array([ True, False, False], dtype=bool)
""")
@@ -209,55 +1316,325 @@ add_newdoc('numpy.core.umath', 'left_shift',
add_newdoc('numpy.core.umath', 'less',
"""
- Returns elementwise x1 < x2 in a bool array.
+ Returns (x1 < x2) element-wise.
+
+ Parameters
+ ----------
+ x1, x2 : array-like
+ Input arrays.
+
+ Returns
+ -------
+ Out : {ndarray, bool}
+ Output array of bools, or a single bool if `x1` and `x2` are scalars.
+
+ See Also
+ --------
+ less_equal
+
+ Examples
+ --------
+ >>> np.less([1,2],[2,2])
+ array([ True, False], dtype=bool)
""")
add_newdoc('numpy.core.umath', 'less_equal',
"""
- Returns elementwise x1 <= x2 in a bool array
+ Returns (x1 <= x2) element-wise.
+
+ Parameters
+ ----------
+ x1, x2 : array_like
+ Input arrays.
+
+ Returns
+ -------
+ Out : {ndarray, bool}
+ Output array of bools, or a single bool if `x1` and `x2` are scalars.
+
+ See Also
+ --------
+ less
+
+ Examples
+ --------
+ >>> np.less_equal([1,2,3],[2,2,2])
+ array([ True, True, False], dtype=bool)
""")
add_newdoc('numpy.core.umath', 'log',
"""
- Logarithm base e elementwise.
+ Natural logarithm, element-wise.
+
+ The natural logarithm `log` is the inverse of the exponential function,
+ so that `log(exp(x)) = x`. The natural logarithm is logarithm in base `e`.
+
+ Parameters
+ ----------
+ x : array_like
+ Input value.
+
+ Returns
+ -------
+ y : {ndarray, scalar}
+ The natural logarithm of `x`, element-wise.
+
+ See Also
+ --------
+ log10, log2, log1p
+
+ Notes
+ -----
+ Logarithm is a multivalued function: for each `x` there is an infinite
+ number of `z` such that `exp(z) = x`. The convention is to return the `z`
+ whose imaginary part lies in `[-pi, pi]`.
+
+ For real-valued input data types, `log` 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, `log` is a complex analytical function that
+ has a branch cut `[-inf, 0]` and is continuous from above on it. `log`
+ handles the floating-point negative zero as an infinitesimal negative
+ number, conforming to the C99 standard.
+
+ References
+ ----------
+ .. [1] M. Abramowitz and I.A. Stegun, "Handbook of Mathematical Functions",
+ 10th printing, 1964, pp. 67. http://www.math.sfu.ca/~cbm/aands/
+ .. [2] Wikipedia, "Logarithm". http://en.wikipedia.org/wiki/Logarithm
+
+ Examples
+ --------
+ >>> np.log([1, np.e, np.e**2, 0])
+ array([ 0., 1., 2., -Inf])
""")
add_newdoc('numpy.core.umath', 'log10',
"""
- Logarithm base 10 elementwise.
+ Compute the logarithm in base 10 elementwise.
+
+ Parameters
+ ----------
+ x : array_like
+ input values.
+
+ Returns
+ -------
+ y : {ndarray, scalar}
+ base-10 logarithm of `x`.
+
+
+ Notes
+ -----
+ Logarithm is a multivalued function: for each `x` there is an infinite
+ number of `z` such that `10**z = x`. The convention is to return the `z`
+ whose imaginary part lies in `[-pi, pi]`.
+
+ For real-valued input data types, `log10` 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, `log10` is a complex analytical function that
+ has a branch cut `[-inf, 0]` and is continuous from above on it. `log10`
+ handles the floating-point negative zero as an infinitesimal negative
+ number, conforming to the C99 standard.
+
+ References
+ ----------
+ .. [1] M. Abramowitz and I.A. Stegun, "Handbook of Mathematical Functions",
+ 10th printing, 1964, pp. 67. http://www.math.sfu.ca/~cbm/aands/
+ .. [2] Wikipedia, "Logarithm". http://en.wikipedia.org/wiki/Logarithm
+
+ Examples
+ --------
+ >>> np.log10([1.e-15,-3.])
+ array([-15., NaN])
""")
add_newdoc('numpy.core.umath', 'log1p',
"""
- log(1+x) to base e elementwise.
+ `log(1 + x)` in base `e`, elementwise.
+
+ Parameters
+ ----------
+ x : array_like
+ Input values.
+
+ Returns
+ -------
+ y : {ndarray, scalar}
+ Natural logarithm of `1 + x`, elementwise.
+
+ Notes
+ -----
+ For real-valued input, `log1p` is accurate also for `x` so small
+ that `1 + x == 1` in floating-point accuracy.
+
+ Logarithm is a multivalued function: for each `x` there is an infinite
+ number of `z` such that `exp(z) = 1 + x`. The convention is to return
+ the `z` whose imaginary part lies in `[-pi, pi]`.
+
+ For real-valued input data types, `log1p` 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, `log1p` is a complex analytical function that
+ has a branch cut `[-inf, -1]` and is continuous from above on it. `log1p`
+ handles the floating-point negative zero as an infinitesimal negative
+ number, conforming to the C99 standard.
+
+ References
+ ----------
+ .. [1] M. Abramowitz and I.A. Stegun, "Handbook of Mathematical Functions",
+ 10th printing, 1964, pp. 67. http://www.math.sfu.ca/~cbm/aands/
+ .. [2] Wikipedia, "Logarithm". http://en.wikipedia.org/wiki/Logarithm
+
+ Examples
+ --------
+ >>> np.log1p(1e-99)
+ 1e-99
+ >>> np.log(1 + 1e-99)
+ 0.0
""")
add_newdoc('numpy.core.umath', 'logical_and',
"""
- Returns x1 and x2 elementwise.
+ Compute the truth value of x1 AND x2 elementwise.
+
+ Parameters
+ ----------
+ x1, x2 : array_like
+ Logical AND is applied to the elements of `x1` and `x2`.
+ They have to be of the same shape.
+
+
+ Returns
+ -------
+ y : {ndarray, bool}
+ Boolean result with the same shape as `x1` and `x2` of the logical
+ AND operation on elements of `x1` and `x2`.
+
+ See Also
+ --------
+ logical_or, logical_not, logical_xor
+ bitwise_and
+
+ Examples
+ --------
+ >>> np.logical_and(True, False)
+ False
+ >>> np.logical_and([True, False], [False, False])
+ array([False, False], dtype=bool)
+
+ >>> x = np.arange(5)
+ >>> np.logical_and(x>1, x<4)
+ array([False, False, True, True, False], dtype=bool)
""")
add_newdoc('numpy.core.umath', 'logical_not',
"""
- Returns not x elementwise.
+ Compute the truth value of NOT x elementwise.
+
+ Parameters
+ ----------
+ x : array_like
+ Logical NOT is applied to the elements of `x`.
+
+ Returns
+ -------
+ y : {ndarray, bool}
+ Boolean result with the same shape as `x` of the NOT operation
+ on elements of `x`.
+
+ See Also
+ --------
+ logical_and, logical_or, logical_xor
+
+ Examples
+ --------
+ >>> np.logical_not(3)
+ False
+ >>> np.logical_not([True, False, 0, 1])
+ array([False, True, True, False], dtype=bool)
+
+ >>> x = np.arange(5)
+ >>> np.logical_not(x<3)
+ array([False, False, False, True, True], dtype=bool)
""")
add_newdoc('numpy.core.umath', 'logical_or',
"""
- Returns x1 or x2 elementwise.
+ Compute the truth value of x1 OR x2 elementwise.
+
+ Parameters
+ ----------
+ x1, x2 : array_like
+ Logical OR is applied to the elements of `x1` and `x2`.
+ They have to be of the same shape.
+
+ Returns
+ -------
+ y : {ndarray, bool}
+ Boolean result with the same shape as `x1` and `x2` of the logical
+ OR operation on elements of `x1` and `x2`.
+
+ See Also
+ --------
+ logical_and, logical_not, logical_xor
+ bitwise_or
+
+ Examples
+ --------
+ >>> np.logical_or(True, False)
+ True
+ >>> np.logical_or([True, False], [False, False])
+ array([ True, False], dtype=bool)
+
+ >>> x = np.arange(5)
+ >>> np.logical_or(x < 1, x > 3)
+ array([ True, False, False, False, True], dtype=bool)
""")
add_newdoc('numpy.core.umath', 'logical_xor',
"""
- Returns x1 xor x2 elementwise.
+ Compute the truth value of x1 XOR x2 elementwise.
+
+ Parameters
+ ----------
+ x1, x2 : array_like
+ Logical XOR is applied to the elements of `x1` and `x2`.
+ They have to be of the same shape.
+
+ Returns
+ -------
+ y : {ndarray, bool}
+ Boolean result with the same shape as `x1` and `x2` of the logical
+ XOR operation on elements of `x1` and `x2`.
+
+ See Also
+ --------
+ logical_and, logical_or, logical_not
+ bitwise_xor
+
+ Examples
+ --------
+ >>> np.logical_xor(True, False)
+ True
+ >>> np.logical_xor([True, True, False, False], [True, False, True, False])
+ array([False, True, True, False], dtype=bool)
+
+ >>> x = np.arange(5)
+ >>> np.logical_xor(x < 1, x > 3)
+ array([ True, False, False, False, True], dtype=bool)
""")
@@ -275,51 +1652,233 @@ add_newdoc('numpy.core.umath', 'minimum',
add_newdoc('numpy.core.umath', 'modf',
"""
- Breaks x into fractional (y1) and integral (y2) parts.
+ Return the fractional and integral part of a number.
+
+ The fractional and integral parts are negative if the given number is
+ negative.
- Each output has the same sign as the input.
+ Parameters
+ ----------
+ x : array_like
+ Input number.
+
+ Returns
+ -------
+ y1 : ndarray
+ Fractional part of `x`.
+ y2 : ndarray
+ Integral part of `x`.
+
+ Examples
+ --------
+ >>> np.modf(2.5)
+ (0.5, 2.0)
+ >>> np.modf(-.4)
+ (-0.40000000000000002, -0.0)
""")
add_newdoc('numpy.core.umath', 'multiply',
"""
- Multiplies the arguments elementwise.
+ Multiply arguments elementwise.
+
+ Parameters
+ ----------
+ x1, x2 : array-like
+ The arrays to be multiplied.
+
+ Returns
+ -------
+ y : {ndarray, scalar}
+ The product of `x1` and `x2`, elementwise. Returns a scalar if
+ both `x1` and `x2` are scalars.
+
+ Notes
+ -----
+ Equivalent to `x1` * `x2` in terms of array-broadcasting.
+
+ Examples
+ --------
+ >>> np.multiply(2.0, 4.0)
+ 8.0
+
+ >>> x1 = np.arange(9.0).reshape((3, 3))
+ >>> x2 = np.arange(3.0)
+ >>> np.multiply(x1, x2)
+ array([[ 0., 1., 4.],
+ [ 0., 4., 10.],
+ [ 0., 7., 16.]])
""")
add_newdoc('numpy.core.umath', 'negative',
"""
- Determines -x elementwise
+ Returns an array with the negative of each element of the original array.
+
+ Parameters
+ ----------
+ x : {array_like, scalar}
+ Input array.
+
+ Returns
+ -------
+ y : {ndarray, scalar}
+ Returned array or scalar `y=-x`.
+
+ Examples
+ --------
+ >>> np.negative([1.,-1.])
+ array([-1., 1.])
""")
add_newdoc('numpy.core.umath', 'not_equal',
"""
- Returns elementwise x1 |= x2
+ Return (x1 != x2) element-wise.
+
+ Parameters
+ ----------
+ x1, x2 : array_like
+ Input arrays.
+ out : ndarray, optional
+ A placeholder the same shape as `x1` to store the result.
+
+ Returns
+ -------
+ not_equal : ndarray bool, scalar bool
+ For each element in `x1, x2`, return True if `x1` is not equal
+ to `x2` and False otherwise.
+
+
+ See Also
+ --------
+ equal, greater, greater_equal, less, less_equal
+
+ Examples
+ --------
+ >>> np.not_equal([1.,2.], [1., 3.])
+ array([False, True], dtype=bool)
""")
add_newdoc('numpy.core.umath', 'ones_like',
"""
- Returns an array of ones of the shape and typecode of x.
+ Returns an array of zeros with the same shape and type as a given array.
+
+ Equivalent to ``a.copy().fill(1)``.
+
+ Please refer to the documentation for `zeros_like`.
+
+ See Also
+ --------
+ zeros_like
+
+ Examples
+ --------
+ >>> a = np.array([[1, 2, 3], [4, 5, 6]])
+ >>> np.ones_like(a)
+ array([[1, 1, 1],
+ [1, 1, 1]])
""")
add_newdoc('numpy.core.umath', 'power',
"""
- Computes x1**x2 elementwise.
+ Computes `x1` ** `x2` elementwise.
+
+ Raise each base in `x1` to the power of the exponents in `x2`. This
+ requires that `x1` and `x2` must be broadcastable to the same shape.
+
+ Parameters
+ ----------
+ x1 : array_like
+ The bases.
+ x2 : array_like
+ The exponents.
+
+ Returns
+ -------
+ y : ndarray
+ The bases in `x1` raised to the exponents in `x2`.
+
+ Examples
+ --------
+ Cube each element in a list.
+
+ >>> x1 = range(6)
+ >>> x1
+ [0, 1, 2, 3, 4, 5]
+ >>> np.power(x1, 3)
+ array([ 0, 1, 8, 27, 64, 125])
+
+ Raise the bases to different exponents.
+
+ >>> x2 = [1.0, 2.0, 3.0, 3.0, 2.0, 1.0]
+ >>> np.power(x1, x2)
+ array([ 0., 1., 8., 27., 16., 5.])
+
+ The effect of broadcasting.
+
+ >>> x2 = np.array([[1, 2, 3, 3, 2, 1], [1, 2, 3, 3, 2, 1]])
+ >>> x2
+ array([[1, 2, 3, 3, 2, 1],
+ [1, 2, 3, 3, 2, 1]])
+ >>> np.power(x1, x2)
+ array([[ 0, 1, 8, 27, 16, 5],
+ [ 0, 1, 8, 27, 16, 5]])
""")
add_newdoc('numpy.core.umath', 'radians',
"""
- Converts angle from degrees to radians
+ Convert angles from degrees to radians.
+
+ Parameters
+ ----------
+ x : array_like
+ Angles in degrees.
+
+ Returns
+ -------
+ y : {ndarray, scalar}
+ The corresponding angle in radians.
+
+ See Also
+ --------
+ degrees : Convert angles from radians to degrees.
+ unwrap : Remove large jumps in angle by wrapping.
+
+ Notes
+ -----
+ ``radians(x)`` is ``x * pi / 180``.
+
+ Examples
+ --------
+ >>> np.radians(180)
+ 3.1415926535897931
""")
add_newdoc('numpy.core.umath', 'reciprocal',
"""
- Compute 1/x
+ Compute 1/x.
+
+ Parameters
+ ----------
+ x : array_like
+ Input value.
+
+ Returns
+ -------
+ y : {ndarray, scalar}
+ Return value.
+
+ Examples
+ --------
+ >>> reciprocal(2.)
+ 0.5
+ >>> reciprocal([1, 2., 3.33])
+ array([ 1. , 0.5 , 0.3003003])
""")
@@ -327,6 +1886,33 @@ add_newdoc('numpy.core.umath', 'remainder',
"""
Computes x1-n*x2 where n is floor(x1 / x2)
+ Parameters
+ ----------
+ x1 : array_like
+ Dividend array.
+ x2 : array_like
+ Divisor array.
+
+ Returns
+ -------
+ y : {ndarray, scalar}
+ The quotient `x1/x2`, element-wise. Returns a scalar if
+ both `x1` and `x2` are scalars.
+
+ See Also
+ --------
+ divide
+ floor
+
+ Notes
+ -----
+ Returns 0 when `x2` is 0.
+
+ Examples
+ --------
+ >>> np.remainder([4,7],[2,3])
+ array([0, 1])
+
""")
add_newdoc('numpy.core.umath', 'right_shift',
@@ -337,55 +1923,266 @@ add_newdoc('numpy.core.umath', 'right_shift',
add_newdoc('numpy.core.umath', 'rint',
"""
- Round x elementwise to the nearest integer, round halfway cases away from zero
+ Round elements of the array to the nearest integer.
+
+ Parameters
+ ----------
+ x : array_like
+ Input array.
+
+ Returns
+ -------
+ out : ndarray
+ Output array is same shape and type as `x`.
+
+ Examples
+ --------
+ >>> a = [-4.1, -3.6, -2.5, 0.1, 2.5, 3.1, 3.9]
+ >>> np.rint(a)
+ array([-4., -4., -2., 0., 2., 3., 4.])
""")
add_newdoc('numpy.core.umath', 'sign',
"""
- Returns -1 if x < 0 and 0 if x==0 and 1 if x > 0
+ Return the sign of a number.
+
+ -1 if x < 0, 0 if x==0, 1 if x > 0.
+
+ Parameters
+ ----------
+ x : array_like
+ Input values.
+
+ Returns
+ -------
+ y : {ndarray, scalar}
+ The sign of `x`.
+
+ Examples
+ --------
+ >>> np.sign([-5., 4.5])
+ array([-1., 1.])
+ >>> np.sign(0)
+ 0
""")
add_newdoc('numpy.core.umath', 'signbit',
"""
- Returns True where signbit of x is set (x<0).
+ Returns True where `signbit` of `x` is set (`x<0`).
+
+ Parameters
+ ----------
+ x: array-like or scalar
+ the input value(s).
+ output : array-like or scalar
+ the returned boolean(s)
+
+ Examples
+ --------
+ >>> np.signbit(-1.2)
+ True
+ >>> np.signbit(np.array([1,-2.3,2.1]))
+ array([False, True, False], dtype=bool)
""")
add_newdoc('numpy.core.umath', 'sin',
"""
- Sine elementwise.
+ Trigonometric sine, element-wise.
+
+ Parameters
+ ----------
+ x : array_like
+ Angle, in radians (:math:`2 \\pi` rad equals 360 degrees).
+
+ Returns
+ -------
+ y : array_like
+ The sine of each element of x.
+
+ See Also
+ --------
+ arcsin, sinh, cos
+
+ Notes
+ -----
+ The sine is one of the fundamental functions of trigonometry
+ (the mathematical study of triangles). Consider a circle of radius
+ 1 centered on the origin. A ray comes in from the :math:`+x` axis,
+ makes an angle at the origin (measured counter-clockwise from that
+ axis), and departs from the origin. The :math:`y` coordinate of
+ the outgoing ray's intersection with the unit circle is the sine
+ of that angle. It ranges from -1 for :math:`x=3\\pi / 2` to
+ +1 for :math:`\\pi / 2.` The function has zeroes where the angle is
+ a multiple of :math:`\\pi`. Sines of angles between :math:`\\pi` and
+ :math:`2\\pi` are negative. The numerous properties of the sine and
+ related functions are included in any standard trigonometry text.
+
+ Examples
+ --------
+ Print sine of one angle:
+
+ >>> np.sin(np.pi/2.)
+ 1.0
+
+ Print sines of an array of angles given in degrees:
+
+ >>> np.sin(np.array((0., 30., 45., 60., 90.)) * np.pi / 180. )
+ array([ 0. , 0.5 , 0.70710678, 0.8660254 , 1. ])
+
+ Plot the sine function:
+
+ >>> import matplotlib.pylab as plt
+ >>> x = np.linspace(-np.pi, np.pi, 201)
+ >>> plt.plot(x, np.sin(x))
+ >>> plt.xlabel('Angle [rad]')
+ >>> plt.ylabel('sin(x)')
+ >>> plt.axis('tight')
+ >>> plt.show()
""")
add_newdoc('numpy.core.umath', 'sinh',
"""
- Hyperbolic sine elementwise.
+ Hyperbolic sine, element-wise.
+
+ Equivalent to ``1/2 * (np.exp(x) - np.exp(-x))`` or
+ ``-1j * np.sin(1j*x)``.
+
+ Parameters
+ ----------
+ x : array_like
+ Input array.
+
+ Returns
+ -------
+ out : ndarray
+ Output array of same shape as `x`.
""")
add_newdoc('numpy.core.umath', 'sqrt',
"""
- Square-root elementwise. For real x, the domain is restricted to x>=0.
+ Return the positive square-root of an array, element-wise.
+
+ Parameters
+ ----------
+ x : array_like
+ The square root of each element in this array is calculated.
+
+ Returns
+ -------
+ y : ndarray
+ The square-root of each element in `x`. If any element in `x`
+ is complex, a complex array is returned. If all of the elements
+ of `x` are real, negative elements will return numpy.nan elements.
+
+ See Also
+ --------
+ numpy.lib.scimath.sqrt
+ A version which will return complex numbers when given negative reals.
+
+ Notes
+ -----
+ `sqrt` has a branch cut ``[-inf, 0)`` and is continuous from above on it.
+
+ Examples
+ --------
+ >>> np.sqrt([1,4,9])
+ array([ 1., 2., 3.])
+
+ >>> np.sqrt([4, -1, -3+4J])
+ array([ 2.+0.j, 0.+1.j, 1.+2.j])
+
+ >>> np.sqrt([4, -1, numpy.inf])
+ array([ 2., NaN, Inf])
""")
add_newdoc('numpy.core.umath', 'square',
"""
- Compute x**2.
+ Compute `x` squared, or `x` to the power of two.
+
+ Parameters
+ ----------
+ x : array_like or scalar
+ Input data.
+
+ Returns
+ -------
+ out : ndarray or scalar
+ Element-wise `x*x`, of the same shape and dtype as `x`.
+ `out` is a scalar if `x` is a scalar.
+
+ See Also
+ --------
+ numpy.linalg.matrix_power
+ sqrt
+ power
+
+ Examples
+ --------
+ >>> np.square([-1j, 1])
+ array([-1.-0.j, 1.+0.j])
""")
add_newdoc('numpy.core.umath', 'subtract',
"""
- Subtracts the arguments elementwise.
+ Subtract arguments elementwise.
+
+ Parameters
+ ----------
+ x1, x2 : {array_like, scalar}
+ The arrays to be subtracted from each other. If type is 'array_like'
+ the `x1` and `x2` shapes must be identical.
+
+ Returns
+ -------
+ y : {ndarray, scalar}
+ The difference of `x1` and `x2`, elementwise. Returns a scalar if
+ both `x1` and `x2` are scalars.
+
+ Notes
+ -----
+ Equivalent to `x1` - `x2` in terms of array-broadcasting.
+
+ Examples
+ --------
+ >>> np.subtract(1.0, 4.0)
+ -3.0
+
+ >>> x1 = np.arange(9.0).reshape((3, 3))
+ >>> x2 = np.arange(3.0)
+ >>> np.subtract(x1, x2)
+ array([[ 0., 0., 0.],
+ [ 3., 3., 3.],
+ [ 6., 6., 6.]])
""")
add_newdoc('numpy.core.umath', 'tan',
"""
- Tangent elementwise.
+ Compute tangent elementwise.
+
+ Parameters
+ ----------
+ x : array_like
+ Angles in radians.
+
+ Returns
+ -------
+ y : ndarray or scalar
+ The corresponding tangent values.
+
+
+ Examples
+ --------
+ >>> from math import pi
+ >>> np.tan(np.array([-pi,pi/2,pi]))
+ array([ 1.22460635e-16, 1.63317787e+16, -1.22460635e-16])
""")
@@ -393,11 +2190,48 @@ add_newdoc('numpy.core.umath', 'tanh',
"""
Hyperbolic tangent elementwise.
+ Parameters
+ ----------
+ x : array_like
+ Input array.
+
+ Returns
+ -------
+ y : ndarray or scalar
+ The corresponding hyperbolic tangent values.
+
""")
add_newdoc('numpy.core.umath', 'true_divide',
"""
- True divides the arguments elementwise.
+ Returns an elementwise, true division of the inputs.
+
+ Instead of the Python traditional 'floor division', this returns a true
+ division. True division adjusts the output type to present the best
+ answer, regardless of input types.
+
+ Parameters
+ ----------
+ x1 : array_like
+ Dividend
+ x2 : array_like
+ Divisor
+
+ Returns
+ -------
+ out : {ndarray, scalar}
+ Result is scalar if both inputs are scalar, ndarray otherwise.
+
+ 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'.
+
+ In Python 3.0, '//' will be the floor division operator and '/' will be
+ the true division operator. The 'true_divide(`x1`, `x2`)' function is
+ equivalent to true division in Python.
""")
diff --git a/numpy/core/defmatrix.py b/numpy/core/defmatrix.py
index 073f63388..1707e49fd 100644
--- a/numpy/core/defmatrix.py
+++ b/numpy/core/defmatrix.py
@@ -41,14 +41,40 @@ def _convert_from_string(data):
return newdata
def asmatrix(data, dtype=None):
- """ Returns 'data' as a matrix. Unlike matrix(), no copy is performed
- if 'data' is already a matrix or array. Equivalent to:
- matrix(data, copy=False)
+ """
+ Interpret the input as a matrix.
+
+ Unlike `matrix`, `asmatrix` does not make a copy if the input is already
+ a matrix or an ndarray. Equivalent to ``matrix(data, copy=False)``.
+
+ Parameters
+ ----------
+ data : array_like
+ Input data.
+
+ Returns
+ -------
+ mat : matrix
+ `data` interpreted as a matrix.
+
+ Examples
+ --------
+ >>> x = np.array([[1, 2], [3, 4]])
+
+ >>> m = np.asmatrix(x)
+
+ >>> x[0,0] = 5
+
+ >>> m
+ matrix([[5, 2],
+ [3, 4]])
+
"""
return matrix(data, dtype=dtype, copy=False)
def matrix_power(M,n):
- """Raise a square matrix to the (integer) power n.
+ """
+ Raise a square matrix to the (integer) power n.
For positive integers n, the power is computed by repeated matrix
squarings and matrix multiplications. If n=0, the identity matrix
@@ -57,7 +83,7 @@ def matrix_power(M,n):
Parameters
----------
- M : array-like
+ M : array_like
Must be a square array (that is, of dimension two and with
equal sizes).
n : integer
@@ -87,6 +113,7 @@ def matrix_power(M,n):
>>> np.linalg.matrix_power(np.array([[0,1],[-1,0]]),10)
array([[-1, 0],
[ 0, -1]])
+
"""
if len(M.shape) != 2 or M.shape[0] != M.shape[1]:
raise ValueError("input must be a square array")
@@ -126,25 +153,29 @@ def matrix_power(M,n):
class matrix(N.ndarray):
"""
- mat = matrix(data, dtype=None, copy=True)
+ matrix(data, dtype=None, copy=True)
- Returns a matrix from an array-like object, or a string of
- data. A matrix is a specialized 2-d array that retains
- its 2-d nature through operations and where '*' means matrix
- multiplication and '**' means matrix power.
+ Returns a matrix from an array-like object, or from a string
+ of data. A matrix is a specialized 2-d array that retains
+ its 2-d nature through operations. It has certain special
+ operators, such as ``*`` (matrix multiplication) and
+ ``**`` (matrix power).
Parameters
----------
- data : array-like or string
- If data is a string, then interpret the string as a matrix
- with commas or spaces separating columns and semicolons
+ data : array_like or string
+ If data is a string, the string is interpreted as a matrix
+ with commas or spaces separating columns, and semicolons
separating rows.
- If data is array-like than convert the array to a matrix.
dtype : data-type
- Anything that can be interpreted as a NumPy datatype.
+ Data-type of the output matrix.
copy : bool
If data is already an ndarray, then this flag determines whether
- or not the data will be copied
+ the data is copied, or whether a view is constructed.
+
+ See Also
+ --------
+ array
Examples
--------
@@ -153,6 +184,10 @@ class matrix(N.ndarray):
[[1 2]
[3 4]]
+ >>> np.matrix([[1, 2], [3, 4]])
+ matrix([[1, 2],
+ [3, 4]])
+
"""
__array_priority__ = 10.0
def __new__(subtype, data, dtype=None, copy=True):
@@ -486,6 +521,26 @@ class matrix(N.ndarray):
return self.__array__().ravel()
def getT(self):
+ """
+ m.T
+
+ Returns the transpose of m.
+
+ Examples
+ --------
+ >>> m = np.matrix('[1, 2; 3, 4]')
+ >>> m
+ matrix([[1, 2],
+ [3, 4]])
+ >>> m.T
+ matrix([[1, 3],
+ [2, 4]])
+
+ See Also
+ --------
+ transpose
+
+ """
return self.transpose()
def getH(self):
@@ -527,20 +582,42 @@ def _from_string(str,gdict,ldict):
def bmat(obj, ldict=None, gdict=None):
"""
- Build a matrix object from string, nested sequence, or array.
+ Build a matrix object from a string, nested sequence, or array.
- Examples
- --------
- F = bmat('A, B; C, D')
- F = bmat([[A,B],[C,D]])
- F = bmat(r_[c_[A,B],c_[C,D]])
-
- All of these produce the same matrix::
+ Parameters
+ ----------
+ obj : string, sequence or array
+ Input data. Variables names in the current scope may
+ be referenced, even if `obj` is a string.
- [ A B ]
- [ C D ]
+ See Also
+ --------
+ matrix
- if A, B, C, and D are appropriately shaped 2-d arrays.
+ Examples
+ --------
+ >>> A = np.mat('1 1; 1 1')
+ >>> B = np.mat('2 2; 2 2')
+ >>> C = np.mat('3 4; 5 6')
+ >>> D = np.mat('7 8; 9 0')
+
+ All the following expressions construct the same block matrix:
+
+ >>> np.bmat([[A, B], [C, D]])
+ matrix([[1, 1, 2, 2],
+ [1, 1, 2, 2],
+ [3, 4, 7, 8],
+ [5, 6, 9, 0]])
+ >>> np.bmat(np.r_[np.c_[A, B], np.c_[C, D]])
+ matrix([[1, 1, 2, 2],
+ [1, 1, 2, 2],
+ [3, 4, 7, 8],
+ [5, 6, 9, 0]])
+ >>> np.bmat('A,B; C,D')
+ matrix([[1, 1, 2, 2],
+ [1, 1, 2, 2],
+ [3, 4, 7, 8],
+ [5, 6, 9, 0]])
"""
if isinstance(obj, str):
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.
diff --git a/numpy/core/memmap.py b/numpy/core/memmap.py
index 14aa409c4..3a9a345dc 100644
--- a/numpy/core/memmap.py
+++ b/numpy/core/memmap.py
@@ -16,12 +16,13 @@ mode_equivalents = {
}
class memmap(ndarray):
- """Create a memory-map to an array stored in a file on disk.
+ """
+ Create a memory-map to an array stored in a file on disk.
Memory-mapped files are used for accessing small segments of large files
- on disk, without reading the entire file into memory. Numpy's memmaps are
- array-like objects. This differs from python's mmap module which are
- file-like objects.
+ on disk, without reading the entire file into memory. Numpy's
+ memmap's are array-like objects. This differs from Python's ``mmap``
+ module, which uses file-like objects.
Parameters
----------
@@ -30,107 +31,131 @@ class memmap(ndarray):
buffer.
dtype : data-type, optional
The data-type used to interpret the file contents.
- Default is uint8
- mode : {'r', 'r+', 'w+', 'c'}, optional
- The mode to open the file.
- 'r', open existing file for read-only
- 'r+', open existing file for read-write
- 'w+', create or overwrite existing file and open for read-write
- 'c', copy-on-write, assignments effect data in memory, but changes
- are not saved to disk. File on disk is read-only.
- Default is 'r+'
+ Default is `uint8`
+ mode : {'r+', 'r', 'w+', 'c'}, optional
+ The file is opened in this mode:
+
+ +------+-------------------------------------------------------------+
+ | 'r' | Open existing file for reading only. |
+ +------+-------------------------------------------------------------+
+ | 'r+' | Open existing file for reading and writing. |
+ +------+-------------------------------------------------------------+
+ | 'w+' | Create or overwrite existing file for reading and writing. |
+ +------+-------------------------------------------------------------+
+ | 'c' | Copy-on-write: assignments affect data in memory, but |
+ | | changes are not saved to disk. The file on disk is |
+ | | read-only. |
+ +------+-------------------------------------------------------------+
+
+ Default is 'r+'.
offset : integer, optional
- Byte offset into the file to start the array data. Should be a
- multiple of the data-type of the data. Requires shape=None.
- Default is 0
+ 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.
shape : tuple, optional
- The desired shape of the array. If None, the returned array will be 1-D
- with the number of elements determined by file size and data-type.
- Default is None
+ 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.
order : {'C', 'F'}, optional
- Specify the order of the N-D array, C or Fortran ordered. This only
- has an effect if the shape is greater than 2-D.
- Default is 'C'
+ Specify the order of the ndarray memory layout: C (row-major) or
+ Fortran (column-major). This only has an effect if the shape is
+ greater than 1-D. The defaullt order is 'C'.
Methods
-------
- close : close the memmap file
- flush : flush any changes in memory to file on disk
+ close
+ Close the memmap file.
+ flush
+ Flush any changes in memory to file on disk.
When you delete a memmap object, flush is called first to write
changes to disk before removing the object.
- Returns
- -------
- memmap : array-like memmap object
- The memmap object can be used anywhere an ndarray is accepted.
- If fp is a memmap, isinstance(fp, numpy.ndarray) will return True.
+ Notes
+ -----
+ The memmap object can be used anywhere an ndarray is accepted.
+ Given a memmap ``fp``, ``isinstance(fp, numpy.ndarray)`` returns
+ ``True``.
Examples
--------
>>> data = np.arange(12, dtype='float32')
>>> data.resize((3,4))
- >>> # Using a tempfile so doctest doesn't write files to your directory.
- >>> # You would use a 'normal' filename.
+ This example uses a temporary file so that doctest doesn't write
+ files to your directory. You would use a 'normal' filename.
+
>>> from tempfile import mkdtemp
>>> import os.path as path
>>> filename = path.join(mkdtemp(), 'newfile.dat')
- >>> # Create a memmap with dtype and shape that matches our data
+ Create a memmap with dtype and shape that matches our data:
+
>>> fp = np.memmap(filename, dtype='float32', mode='w+', shape=(3,4))
>>> fp
memmap([[ 0., 0., 0., 0.],
- [ 0., 0., 0., 0.],
- [ 0., 0., 0., 0.]], dtype=float32)
+ [ 0., 0., 0., 0.],
+ [ 0., 0., 0., 0.]], dtype=float32)
+
+ Write data to memmap array:
- >>> # Write data to memmap array
>>> fp[:] = data[:]
>>> fp
memmap([[ 0., 1., 2., 3.],
- [ 4., 5., 6., 7.],
- [ 8., 9., 10., 11.]], dtype=float32)
+ [ 4., 5., 6., 7.],
+ [ 8., 9., 10., 11.]], dtype=float32)
+
+ Deletion flushes memory changes to disk before removing the object:
- >>> # Deletion flushes memory changes to disk before removing the object.
>>> del fp
- >>> # Load the memmap and verify data was stored
+
+ Load the memmap and verify data was stored:
+
>>> newfp = np.memmap(filename, dtype='float32', mode='r', shape=(3,4))
>>> newfp
memmap([[ 0., 1., 2., 3.],
- [ 4., 5., 6., 7.],
- [ 8., 9., 10., 11.]], dtype=float32)
+ [ 4., 5., 6., 7.],
+ [ 8., 9., 10., 11.]], dtype=float32)
+
+ Read-only memmap:
- >>> # read-only memmap
>>> fpr = np.memmap(filename, dtype='float32', mode='r', shape=(3,4))
>>> fpr.flags.writeable
False
- >>> # Cannot assign to read-only, obviously
+
+ Cannot assign to read-only, obviously:
+
>>> fpr[0, 3] = 56
Traceback (most recent call last):
...
RuntimeError: array is not writeable
- >>> # copy-on-write memmap
+ Copy-on-write memmap:
+
>>> fpc = np.memmap(filename, dtype='float32', mode='c', shape=(3,4))
>>> fpc.flags.writeable
True
- >>> # Can assign to copy-on-write array, but values are only written
- >>> # into the memory copy of the array, and not written to disk.
+
+ It's possible to assign to copy-on-write array, but values are only
+ written into the memory copy of the array, and not written to disk:
+
>>> fpc
memmap([[ 0., 1., 2., 3.],
- [ 4., 5., 6., 7.],
- [ 8., 9., 10., 11.]], dtype=float32)
+ [ 4., 5., 6., 7.],
+ [ 8., 9., 10., 11.]], dtype=float32)
>>> fpc[0,:] = 0
>>> fpc
memmap([[ 0., 0., 0., 0.],
- [ 4., 5., 6., 7.],
- [ 8., 9., 10., 11.]], dtype=float32)
- >>> # file on disk is unchanged
+ [ 4., 5., 6., 7.],
+ [ 8., 9., 10., 11.]], dtype=float32)
+
+ File on disk is unchanged:
+
>>> fpr
memmap([[ 0., 1., 2., 3.],
- [ 4., 5., 6., 7.],
- [ 8., 9., 10., 11.]], dtype=float32)
+ [ 4., 5., 6., 7.],
+ [ 8., 9., 10., 11.]], dtype=float32)
+
+ Offset into a memmap:
- >>> # offset into a memmap
>>> fpo = np.memmap(filename, dtype='float32', mode='r', offset=16)
>>> fpo
memmap([ 4., 5., 6., 7., 8., 9., 10., 11.], dtype=float32)
diff --git a/numpy/core/numeric.py b/numpy/core/numeric.py
index 8fe1f9220..40f14cd79 100644
--- a/numpy/core/numeric.py
+++ b/numpy/core/numeric.py
@@ -46,10 +46,41 @@ ufunc = type(sin)
# originally from Fernando Perez's IPython
def zeros_like(a):
- """Return an array of zeros of the shape and data-type of a.
+ """
+ Returns an array of zeros with the same shape and type as a given array.
+
+ Equivalent to ``a.copy().fill(0)``.
+
+ Parameters
+ ----------
+ a : array_like
+ The shape and data-type of `a` defines the parameters of
+ the returned array.
+
+ Returns
+ -------
+ out : ndarray
+ Array of zeros with same shape and type as `a`.
+
+ See Also
+ --------
+ numpy.ones_like : Return an array of ones with shape and type of input.
+ numpy.empty_like : Return an empty array with shape and type of input.
+ numpy.zeros : Return a new array setting values to zero.
+ numpy.ones : Return a new array setting values to one.
+ numpy.empty : Return a new uninitialized array.
+
+ Examples
+ --------
+ >>> x = np.arange(6)
+ >>> x = x.reshape((2, 3))
+ >>> x
+ array([[0, 1, 2],
+ [3, 4, 5]])
+ >>> np.zeros_like(x)
+ array([[0, 0, 0],
+ [0, 0, 0]])
- If you don't explicitly need the array to be zeroed, you should instead
- use empty_like(), which is a bit faster as it only allocates memory.
"""
if isinstance(a, ndarray):
res = ndarray.__new__(type(a), a.shape, a.dtype, order=a.flags.fnc)
@@ -66,10 +97,30 @@ def zeros_like(a):
return res
def empty_like(a):
- """Return an empty (uninitialized) array of the shape and data-type of a.
+ """
+ Create a new array with the same shape and type as another.
- Note that this does NOT initialize the returned array. If you require
- your array to be initialized, you should use zeros_like().
+ Parameters
+ ----------
+ a : ndarray
+ Returned array will have same shape and type as `a`.
+
+ See Also
+ --------
+ zeros_like, ones_like, zeros, ones, empty
+
+ Notes
+ -----
+ This function does *not* initialize the returned array; to do that use
+ `zeros_like` or `ones_like` instead.
+
+ Examples
+ --------
+ >>> a = np.array([[1,2,3],[4,5,6]])
+ >>> np.empty_like(a)
+ >>> np.empty_like(a)
+ array([[-1073741821, -1067702173, 65538], #random data
+ [ 25670, 23454291, 71800]])
"""
if isinstance(a, ndarray):
@@ -127,51 +178,186 @@ compare_chararrays = multiarray.compare_chararrays
putmask = multiarray.putmask
def asarray(a, dtype=None, order=None):
- """Returns a as an array.
+ """
+ Convert the input to an array.
+
+ Parameters
+ ----------
+ a : array_like
+ Input data, in any form that can be converted to an array. This
+ includes lists, lists of tuples, tuples, tuples of tuples, tuples
+ of lists and ndarrays.
+ 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'.
+
+ Returns
+ -------
+ out : ndarray
+ Array interpretation of `a`. No copy is performed if the input
+ is already an ndarray. If `a` is a subclass of ndarray, a base
+ class ndarray is returned.
+
+ See Also
+ --------
+ asanyarray : Similar function which passes through subclasses.
+ ascontiguousarray : Convert input to a contiguous array.
+ asfarray : Convert input to a floating point ndarray.
+ asfortranarray : Convert input to an ndarray with column-major
+ memory order.
+ asarray_chkfinite : Similar function which checks input for NaNs and Infs.
+ fromiter : Create an array from an iterator.
+ fromfunction : Construct an array by executing a function on grid
+ positions.
+
+ Examples
+ --------
+ Convert a list into an array:
+
+ >>> a = [1, 2]
+ >>> np.asarray(a)
+ array([1, 2])
+
+ Existing arrays are not copied:
+
+ >>> a = np.array([1, 2])
+ >>> np.asarray(a) is a
+ True
- Unlike array(), no copy is performed if a is already an array. Subclasses
- are converted to base class ndarray.
"""
return array(a, dtype, copy=False, order=order)
def asanyarray(a, dtype=None, order=None):
- """Returns a as an array, but will pass subclasses through.
+ """
+ Convert the input to a ndarray, but pass ndarray subclasses through.
+
+ Parameters
+ ----------
+ a : array_like
+ Input data, in any form that can be converted to an array. This
+ includes scalars, lists, lists of tuples, tuples, tuples of tuples,
+ tuples of lists and ndarrays.
+ 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 ('F') memory
+ representation. Defaults to 'C'.
+
+ Returns
+ -------
+ out : ndarray or an ndarray subclass
+ Array interpretation of `a`. If `a` is an ndarray or a subclass
+ of ndarray, it is returned as-is and no copy is performed.
+
+ See Also
+ --------
+ asarray : Similar function which always returns ndarrays.
+ ascontiguousarray : Convert input to a contiguous array.
+ asfarray : Convert input to a floating point ndarray.
+ asfortranarray : Convert input to an ndarray with column-major
+ memory order.
+ asarray_chkfinite : Similar function which checks input for NaNs and Infs.
+ fromiter : Create an array from an iterator.
+ fromfunction : Construct an array by executing a function on grid
+ positions.
+
+ Examples
+ --------
+ Convert a list into an array:
+
+ >>> a = [1, 2]
+ >>> np.asanyarray(a)
+ array([1, 2])
+
+ Instances of `ndarray` subclasses are passed through as-is:
+
+ >>> a = np.matrix([1, 2])
+ >>> np.asanyarray(a) is a
+ True
+
"""
return array(a, dtype, copy=False, order=order, subok=True)
def ascontiguousarray(a, dtype=None):
- """Return 'a' as an array contiguous in memory (C order).
+ """
+ Return a contiguous array in memory (C order).
+
+ Parameters
+ ----------
+ a : array_like
+ Input array.
+ dtype : string
+ Type code of returned array.
+
+ Returns
+ -------
+ out : ndarray
+ Contiguous array of same shape and content as `a` with type `dtype`.
+
"""
return array(a, dtype, copy=False, order='C', ndmin=1)
def asfortranarray(a, dtype=None):
- """Return 'a' as an array laid out in Fortran-order in memory.
+ """
+ Return an array laid out in Fortran-order in memory.
+
+ Parameters
+ ----------
+ a : array-like
+ Input array.
+ dtype : data-type, optional
+ By default, the data-type is inferred from the input data.
+
+ Returns
+ -------
+ out : ndarray
+ Array interpretation of `a` in Fortran (column-order).
+
+ See Also
+ --------
+ asarray : Similar function which always returns ndarrays.
+ ascontiguousarray : Convert input to a contiguous array.
+ asfarray : Convert input to a floating point ndarray.
+ asanyarray : Convert input to an ndarray with either row or
+ column-major memory order.
+ asarray_chkfinite : Similar function which checks input for NaNs and Infs.
+ fromiter : Create an array from an iterator.
+ fromfunction : Construct an array by executing a function on grid
+ positions.
+
"""
return array(a, dtype, copy=False, order='F', ndmin=1)
def require(a, dtype=None, requirements=None):
- """Return an ndarray of the provided type that satisfies requirements.
+ """
+ Return an ndarray of the provided type that satisfies requirements.
This function is useful to be sure that an array with the correct flags
is returned for passing to compiled code (perhaps through ctypes).
Parameters
----------
- a : array-like
+ a : array-like
The object to be converted to a type-and-requirement satisfying array
- dtype : data-type
+ dtype : data-type
The required data-type (None is the default data-type -- float64)
- requirements : list of strings
- The requirements list can be any of the
- 'ENSUREARRAY' ('E') - ensure that a base-class ndarray
- 'F_CONTIGUOUS' ('F') - ensure a Fortran-contiguous array
- 'C_CONTIGUOUS' ('C') - ensure a C-contiguous array
- 'ALIGNED' ('A') - ensure a data-type aligned array
- 'WRITEABLE' ('W') - ensure a writeable array
- 'OWNDATA' ('O') - ensure an array that owns its own data
-
- The returned array will be guaranteed to have the listed requirements
- by making a copy if needed.
+ requirements : list of strings
+ The requirements list can be any of the following
+
+ * 'ENSUREARRAY' ('E') - ensure that a base-class ndarray
+ * 'F_CONTIGUOUS' ('F') - ensure a Fortran-contiguous array
+ * 'C_CONTIGUOUS' ('C') - ensure a C-contiguous array
+ * 'ALIGNED' ('A') - ensure a data-type aligned array
+ * 'WRITEABLE' ('W') - ensure a writeable array
+ * 'OWNDATA' ('O') - ensure an array that owns its own data
+
+ Notes
+ -----
+ The returned array will be guaranteed to have the listed requirements
+ by making a copy if needed.
+
"""
if requirements is None:
requirements = []
@@ -205,7 +391,14 @@ def require(a, dtype=None, requirements=None):
return arr
def isfortran(a):
- """Returns True if 'a' is arranged in Fortran-order in memory with a.ndim > 1
+ """
+ Returns True if array is arranged in Fortran-order and dimension > 1.
+
+ Parameters
+ ----------
+ a : ndarray
+ Input array to test.
+
"""
return a.flags.fnc
@@ -223,14 +416,38 @@ def argwhere(a):
return asarray(a.nonzero()).T
def flatnonzero(a):
- """Return indicies that are not-zero in flattened version of a
+ """
+ Return indices that are non-zero in the flattened version of a.
- Equivalent to a.ravel().nonzero()[0]
+ This is equivalent to a.ravel().nonzero()[0].
- >>> np.arange(-2, 3)
+ Parameters
+ ----------
+ a : ndarray
+ Input array.
+
+ Returns
+ -------
+ res : ndarray
+ Output array, containing the indices of the elements of `a.ravel()`
+ that are non-zero.
+
+ See Also
+ --------
+ nonzero : Return the indices of the non-zero elements of the input array.
+ ravel : Return a 1-D array containing the elements of the input array.
+
+ Examples
+ --------
+ >>> x = np.arange(-2, 3)
+ >>> x
array([-2, -1, 0, 1, 2])
- >>> np.flatnonzero(np.arange(-2, 3))
+ >>> np.flatnonzero(x)
array([0, 1, 3, 4])
+
+ >>> x.ravel()[np.flatnonzero(x)]
+ array([-2, -1, 1, 2])
+
"""
return a.ravel().nonzero()[0]
@@ -244,17 +461,115 @@ def _mode_from_name(mode):
return mode
def correlate(a,v,mode='valid'):
- """Return the discrete, linear correlation of 1-D sequences a and v; mode
- can be 'valid', 'same', or 'full' to specify the size of the resulting
- sequence
+ """
+ Discrete, linear correlation of two 1-dimensional sequences.
+
+ This function is equivalent to
+
+ >>> np.convolve(a, v[::-1], mode=mode)
+
+ where ``v[::-1]`` is the reverse of `v`.
+
+ Parameters
+ ----------
+ a, v : array_like
+ Input sequences.
+ mode : {'valid', 'same', 'full'}, optional
+ Refer to the `convolve` docstring. Note that the default
+ is `valid`, unlike `convolve`, which uses `full`.
+
+ See Also
+ --------
+ convolve : Discrete, linear convolution of two
+ one-dimensional sequences.
+
"""
mode = _mode_from_name(mode)
return multiarray.correlate(a,v,mode)
def convolve(a,v,mode='full'):
- """Returns the discrete, linear convolution of 1-D sequences a and v; mode
- can be 'valid', 'same', or 'full' to specify size of the resulting sequence.
+ """
+ Returns the discrete, linear convolution of two one-dimensional sequences.
+
+ The convolution operator is often seen in signal processing, where it
+ models the effect of a linear time-invariant system on a signal [1]_. In
+ probability theory, the sum of two independent random variables is
+ distributed according to the convolution of their individual
+ distributions.
+
+ Parameters
+ ----------
+ a : (N,) array_like
+ First one-dimensional input array.
+ v : (M,) array_like
+ Second one-dimensional input array.
+ mode : {'full', 'valid', 'same'}, optional
+ 'full':
+ By default, mode is 'full'. This returns the convolution
+ at each point of overlap, with an output shape of (N+M-1,). At
+ the end-points of the convolution, the signals do not overlap
+ completely, and boundary effects may be seen.
+
+ 'same':
+ Mode `same` returns output of length ``max(M, N)``. Boundary
+ effects are still visible.
+
+ 'valid':
+ Mode `valid` returns output of length
+ ``max(M, N) - min(M, N) + 1``. The convolution product is only given
+ for points where the signals overlap completely. Values outside
+ the signal boundary have no effect.
+
+ Returns
+ -------
+ out : ndarray
+ Discrete, linear convolution of `a` and `v`.
+
+ See Also
+ --------
+ scipy.signal.fftconv : Convolve two arrays using the Fast Fourier
+ Transform.
+ scipy.linalg.toeplitz : Used to construct the convolution operator.
+
+ Notes
+ -----
+ The discrete convolution operation is defined as
+
+ .. math:: (f * g)[n] = \\sum_{m = -\\infty}^{\\infty} f[m] f[n - m]
+
+ It can be shown that a convolution :math:`x(t) * y(t)` in time/space
+ is equivalent to the multiplication :math:`X(f) Y(f)` in the Fourier
+ domain, after appropriate padding (padding is necessary to prevent
+ circular convolution). Since multiplication is more efficient (faster)
+ than convolution, the function `scipy.signal.fftconvolve` exploits the
+ FFT to calculate the convolution of large data-sets.
+
+ References
+ ----------
+ .. [1] Wikipedia, "Convolution", http://en.wikipedia.org/wiki/Convolution.
+
+ Examples
+ --------
+ Note how the convolution operator flips the second array
+ before "sliding" the two across one another:
+
+ >>> np.convolve([1, 2, 3], [0, 1, 0.5])
+ array([ 0. , 1. , 2.5, 4. , 1.5])
+
+ Only return the middle values of the convolution.
+ Contains boundary effects, where zeros are taken
+ into account:
+
+ >>> np.convolve([1,2,3],[0,1,0.5], 'same')
+ array([ 1. , 2.5, 4. ])
+
+ The two arrays are of the same length, so there
+ is only one position where they completely overlap:
+
+ >>> np.convolve([1,2,3],[0,1,0.5], 'valid')
+ array([ 2.5])
+
"""
a,v = array(a,ndmin=1),array(v,ndmin=1)
if (len(v) > len(a)):
@@ -268,21 +583,98 @@ inner = multiarray.inner
dot = multiarray.dot
def outer(a,b):
- """Returns the outer product of two vectors.
+ """
+ Returns the outer product of two vectors.
+
+ Given two vectors, ``[a0, a1, ..., aM]`` and ``[b0, b1, ..., bN]``,
+ the outer product becomes::
+
+ [[a0*b0 a0*b1 ... a0*bN ]
+ [a1*b0 .
+ [ ... .
+ [aM*b0 aM*bN ]]
+
+ 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.
+
+ Returns
+ -------
+ out : ndarray, shaped (M, N)
+ ``out[i, j] = a[i] * b[j]``
+
+ Notes
+ -----
+ The outer product of vectors is a special case of the Kronecker product.
+
+ Examples
+ --------
+ >>> x = np.array(['a', 'b', 'c'], dtype=object)
+
+ >>> np.outer(x, [1, 2, 3])
+ array([[a, aa, aaa],
+ [b, bb, bbb],
+ [c, cc, ccc]], dtype=object)
- result[i,j] = a[i]*b[j] when a and b are vectors.
- Will accept any arguments that can be made into vectors.
"""
a = asarray(a)
b = asarray(b)
return a.ravel()[:,newaxis]*b.ravel()[newaxis,:]
def vdot(a, b):
- """Returns the dot product of 2 vectors (or anything that can be made into
- a vector).
+ """
+ Return the dot product of two vectors.
+
+ The vdot(`a`, `b`) function handles complex numbers differently than
+ dot(`a`, `b`). If the first argument is complex the complex conjugate
+ of the first argument is used for the calculation of the dot product.
- Note: this is not the same as `dot`, as it takes the conjugate of its first
- argument if complex and always returns a scalar."""
+ Parameters
+ ----------
+ a : array_like
+ If `a` is complex the complex conjugate is taken before calculation
+ of the dot product.
+ b : array_like
+ Second argument to the dot product.
+
+ Returns
+ -------
+ output : scalar
+ Returns dot product of `a` and `b`. Can be an int, float, or
+ complex depending on the types of `a` and `b`.
+
+ See Also
+ --------
+ dot : Return the dot product without using the complex conjugate of the
+ first argument.
+
+ Notes
+ -----
+ The dot product is the summation of element wise multiplication.
+
+ .. math::
+ a \\cdot b = \\sum_{i=1}^n a_i^*b_i = a_1^*b_1+a_2^*b_2+\\cdots+a_n^*b_n
+
+ Examples
+ --------
+ >>> a = np.array([1+2j,3+4j])
+ >>> b = np.array([5+6j,7+8j])
+ >>> np.vdot(a, b)
+ (70-8j)
+ >>> np.vdot(b, a)
+ (70+8j)
+ >>> a = np.array([[1, 4], [5, 6]])
+ >>> b = np.array([[4, 1], [2, 2]])
+ >>> np.vdot(a, b)
+ 30
+ >>> np.vdot(b, a)
+ 30
+
+ """
return dot(asarray(a).ravel().conj(), asarray(b).ravel())
# try to import blas optimized dot if available
@@ -292,30 +684,101 @@ try:
from _dotblas import dot, vdot, inner, alterdot, restoredot
except ImportError:
def alterdot():
- "Does Nothing"
+ """
+ Change `dot`, `vdot`, and `innerproduct` to use accelerated BLAS
+ functions.
+
+ When numpy is built with an accelerated BLAS like ATLAS, the above
+ functions will be replaced to make use of the faster implementations.
+ The faster implementations only affect float32, float64, complex64, and
+ complex128 arrays. Furthermore, only matrix-matrix, matrix-vector, and
+ vector-vector products are accelerated. Products of arrays with larger
+ dimensionalities will not be accelerated since the BLAS API only
+ includes these.
+
+ Typically, the user will never have to call this function. If numpy was
+ built with an accelerated BLAS, this function will be called when numpy
+ is imported.
+
+ See Also
+ --------
+ restoredot : `restoredot` undoes the effects of `alterdot`.
+
+ """
pass
def restoredot():
- "Does Nothing"
+ """
+ Restore `dot`, `vdot`, and `innerproduct` to the default non-BLAS
+ implementations.
+
+ Typically, the user will only need to call this when troubleshooting and
+ installation problem, reproducing the conditions of a build without an
+ accelerated BLAS, or when being very careful about benchmarking linear
+ algebra operations.
+
+ See Also
+ --------
+ alterdot : `restoredot` undoes the effects of `alterdot`.
+
+ """
pass
def tensordot(a, b, axes=2):
- """tensordot returns the product for any (ndim >= 1) arrays.
+ """
+ Returns the tensor dot product for (ndim >= 1) arrays along specified axes.
+
+ 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.
+
+ Parameters
+ ----------
+ a : array_like
+ Input array.
+ b : array_like
+ Input array.
+ axes : shape tuple
+ Axes to be summed over.
- r_{xxx, yyy} = \sum_k a_{xxx,k} b_{k,yyy} where
+ See Also
+ --------
+ dot
- the axes to be summed over are given by the axes argument.
- the first element of the sequence determines the axis or axes
- in arr1 to sum over, and the second element in axes argument sequence
- determines the axis or axes in arr2 to sum over.
+ 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.
+ If the `axes` argument is an integer, N, then the last N dimensions of `a`
+ and first N dimensions of `b` are summed over.
+
+ Examples
+ --------
+ >>> 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]))
+ >>> c.shape
+ (5,2)
+ >>> c
+ array([[ 4400., 4730.],
+ [ 4532., 4874.],
+ [ 4664., 5018.],
+ [ 4796., 5162.],
+ [ 4928., 5306.]])
+
+ >>> # A slower but equivalent way of computing the same...
+ >>> c = 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]
+
"""
try:
iter(axes)
@@ -380,13 +843,53 @@ def tensordot(a, b, axes=2):
return res.reshape(olda + oldb)
def roll(a, shift, axis=None):
- """Roll the elements in the array by 'shift' positions along
- the given axis.
+ """
+ Roll array elements along a given axis.
+
+ Elements that roll beyond the last position are re-introduced at
+ the first.
- >>> np.arange(10)
- array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
- >>> np.roll(np.arange(10), 2)
+ Parameters
+ ----------
+ a : array_like
+ Input array.
+ shift : int
+ The number of places by which elements are shifted.
+ axis : int, optional
+ The axis along which elements are shifted. By default, the array
+ is flattened before shifting, after which the original
+ shape is restored.
+
+ Returns
+ -------
+ res : ndarray
+ Output array, with the same shape as `a`.
+
+ See Also
+ --------
+ rollaxis : Roll the specified axis backwards, until it lies in a
+ given position.
+
+ Examples
+ --------
+ >>> x = np.arange(10)
+ >>> np.roll(x, 2)
array([8, 9, 0, 1, 2, 3, 4, 5, 6, 7])
+
+ >>> x2 = np.reshape(x, (2,5))
+ >>> x2
+ array([[0, 1, 2, 3, 4],
+ [5, 6, 7, 8, 9]])
+ >>> np.roll(x2, 1)
+ array([[9, 0, 1, 2, 3],
+ [4, 5, 6, 7, 8]])
+ >>> np.roll(x2, 1, axis=0)
+ array([[5, 6, 7, 8, 9],
+ [0, 1, 2, 3, 4]])
+ >>> np.roll(x2, 1, axis=1)
+ array([[4, 0, 1, 2, 3],
+ [9, 5, 6, 7, 8]])
+
"""
a = asanyarray(a)
if axis is None:
@@ -404,15 +907,39 @@ def roll(a, shift, axis=None):
return res
def rollaxis(a, axis, start=0):
- """Return transposed array so that axis is rolled before start.
+ """
+ Roll the specified axis backwards, until it lies in a given position.
+ Parameters
+ ----------
+ a : ndarray
+ Input array.
+ axis : int
+ The axis to roll backwards. The positions of the other axes do not
+ change relative to one another.
+ start : int, optional
+ The axis is rolled until it lies before this position.
+
+ Returns
+ -------
+ res : ndarray
+ Output array.
+
+ See Also
+ --------
+ roll : Roll the elements of an array by a number of positions along a
+ given axis.
+
+ Examples
+ --------
>>> a = np.ones((3,4,5,6))
>>> np.rollaxis(a, 3, 1).shape
(3, 6, 4, 5)
- >>> np.rollaxis(a, 2, 0).shape
+ >>> np.rollaxis(a, 2).shape
(5, 3, 4, 6)
>>> np.rollaxis(a, 1, 4).shape
(3, 5, 6, 4)
+
"""
n = a.ndim
if axis < 0:
@@ -491,6 +1018,37 @@ if issubclass(longlong, int):
_typelessdata.append(longlong)
def array_repr(arr, max_line_width=None, precision=None, suppress_small=None):
+ """
+ Return the string representation of an array.
+
+ Parameters
+ ----------
+ arr : ndarray
+ Input array.
+ max_line_width : int
+ The maximum number of columns the string should span. Newline
+ characters splits the string appropriately after array elements.
+ precision : int
+ Floating point precision.
+ suppress_small : bool
+ Represent very small numbers as zero.
+
+ Returns
+ -------
+ string : str
+ The string representation of an array.
+
+
+ Examples
+ --------
+ >>> np.array_repr(np.array([1,2]))
+ 'array([1, 2])'
+ >>> np.array_repr(np.ma.array([0.]))
+ 'MaskedArray([ 0.])'
+ >>> np.array_repr(np.array([], np.int32))
+ 'array([], dtype=int32)'
+
+ """
if arr.size > 0 or arr.shape==(0,):
lst = array2string(arr, max_line_width, precision, suppress_small,
', ', "array(")
@@ -516,6 +1074,30 @@ def array_repr(arr, max_line_width=None, precision=None, suppress_small=None):
return cName + "(%s, %sdtype=%s)" % (lst, lf, typename)
def array_str(a, max_line_width=None, precision=None, suppress_small=None):
+ """
+ Return a string representation of an array.
+
+ Parameters
+ ----------
+ a : ndarray
+ Input array.
+ max_line_width : int, optional
+ Inserts newlines if text is longer than `max_line_width`.
+ precision : int, optional
+ If `a` is float, `precision` sets loating point precision.
+ suppress_small : boolean, optional
+ Represent very small numbers as zero.
+
+ See Also
+ --------
+ array2string, array_repr
+
+ Examples
+ --------
+ >>> np.array_str(np.arange(3))
+ >>> '[0 1 2]'
+
+ """
return array2string(a, max_line_width, precision, suppress_small, ' ', "", str)
set_string_function = multiarray.set_string_function
@@ -526,8 +1108,41 @@ little_endian = (sys.byteorder == 'little')
def indices(dimensions, dtype=int):
- """Returns an array representing a grid of indices with row-only, and
- column-only variation.
+ """
+ Return an array representing the coordinates of a grid.
+
+ Parameters
+ ----------
+ shape : (N,) tuple of ints
+
+ Returns
+ -------
+ grid : ndarray
+ The output shape is ``(N,) + shape``. I.e., if `shape` is ``(2,4,5)``,
+ the output shape is ``(3, 2, 4, 5)``. Each subarray, ``grid[i,...]``
+ contains values that vary only along the ``i-th`` axis.
+
+ Examples
+ --------
+ >>> grid = np.indices((2,3))
+
+ The row-positions are given by:
+
+ >>> grid[0]
+ array([[0, 0, 0],
+ [1, 1, 1]])
+
+ and the column-positions by
+
+ >>> grid[1]
+ array([[0, 1, 2],
+ [0, 1, 2]])
+
+
+ See Also
+ --------
+ mgrid, meshgrid, ndindex
+
"""
dimensions = tuple(dimensions)
N = len(dimensions)
@@ -543,24 +1158,76 @@ def indices(dimensions, dtype=int):
return res
def fromfunction(function, shape, **kwargs):
- """Returns an array constructed by calling a function on a tuple of number
- grids.
+ """
+ Construct an array by executing a function over each coordinate.
+
+ The resulting array therefore has a value ``fn(x, y, z)`` at
+ coordinate ``(x, y, z)``.
- The function should accept as many arguments as the length of shape and
- work on array inputs. The shape argument is a sequence of numbers
- indicating the length of the desired output for each axis.
+ Parameters
+ ----------
+ fn : 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
+ 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`.
+ dtype : data-type, optional
+ Data-type of the coordinate arrays passed to `fn`. By default,
+ `dtype` is float.
+
+ See Also
+ --------
+ indices, meshgrid
+
+ Notes
+ -----
+ Keywords other than `shape` and `dtype` are passed to the function.
+
+ Examples
+ --------
+ >>> np.fromfunction(lambda i, j: i == j, (3, 3), dtype=int)
+ array([[ True, False, False],
+ [False, True, False],
+ [False, False, True]], dtype=bool)
+
+ >>> np.fromfunction(lambda i, j: i + j, (3, 3), dtype=int)
+ array([[0, 1, 2],
+ [1, 2, 3],
+ [2, 3, 4]])
- The function can also accept keyword arguments (except dtype), which will
- be passed through fromfunction to the function itself. The dtype argument
- (default float) determines the data-type of the index grid passed to the
- function.
"""
dtype = kwargs.pop('dtype', float)
args = indices(shape, dtype=dtype)
return function(*args,**kwargs)
def isscalar(num):
- """Returns True if the type of num is a scalar type.
+ """
+ Returns True if the type of num is a scalar type.
+
+ Parameters
+ ----------
+ num : any
+ Input argument.
+
+ Returns
+ -------
+ val : bool
+ True if `num` is a scalar type, False if it is not.
+
+ Examples
+ --------
+ >>> np.isscalar(3.1)
+ True
+ >>> np.isscalar([3.1])
+ False
+ >>> np.isscalar(False)
+ True
+
"""
if isinstance(num, generic):
return True
@@ -593,14 +1260,61 @@ _lkup = {
'L':''}
def binary_repr(num, width=None):
- """Return the binary representation of the input number as a string.
-
- This is equivalent to using base_repr with base 2, but about 25x
- faster.
+ """
+ Return the binary representation of the input number as a string.
- For negative numbers, if width is not given, a - sign is added to the
+ For negative numbers, if width is not given, a minus sign is added to the
front. If width is given, the two's complement of the number is
returned, with respect to that width.
+
+ In a two's-complement system negative numbers are represented by the two's
+ complement of the absolute value. This is the most common method of
+ representing signed integers on computers [1]_. A N-bit two's-complement
+ system can represent every integer in the range
+ :math:`-2^{N-1}` to :math:`+2^{N-1}-1`.
+
+ Parameters
+ ----------
+ num : int
+ Only an integer decimal number can be used.
+ width : int, optional
+ The length of the returned string if `num` is positive, the length of
+ the two's complement if `num` is negative.
+
+ Returns
+ -------
+ bin : str
+ Binary representation of `num` or two's complement of `num`.
+
+ See Also
+ --------
+ base_repr
+
+ Notes
+ -----
+ `binary_repr` is equivalent to using `base_repr` with base 2, but about 25x
+ faster.
+
+ References
+ ----------
+ .. [1] Wikipedia, "Two's complement",
+ http://en.wikipedia.org/wiki/Two's_complement
+
+ Examples
+ --------
+ >>> np.binary_repr(3)
+ '11'
+ >>> np.binary_repr(-3)
+ '-11'
+ >>> np.binary_repr(3, width=4)
+ '0011'
+
+ The two's complement is returned when the input number is negative and
+ width is specified:
+
+ >>> np.binary_repr(-3, width=4)
+ '1101'
+
"""
sign = ''
if num < 0:
@@ -620,9 +1334,38 @@ def binary_repr(num, width=None):
return sign + bin
def base_repr (number, base=2, padding=0):
- """Return the representation of a number in the given base.
+ """
+ Return a string representation of a number in the given base system.
+
+ Parameters
+ ----------
+ number : scalar
+ The value to convert. Only positive values are handled.
+ base : int
+ Convert `number` to the `base` number system. The valid range is 2-36,
+ the default value is 2.
+ padding : int, optional
+ Number of zeros padded on the left.
+
+ Returns
+ -------
+ out : str
+ String representation of `number` in `base` system.
+
+ See Also
+ --------
+ binary_repr : Faster version of `base_repr` for base 2 that also handles
+ negative numbers.
+
+ Examples
+ --------
+ >>> np.base_repr(3, 5)
+ '3'
+ >>> np.base_repr(6, 5)
+ '11'
+ >>> np.base_repr(7, 5, padding=3)
+ '00012'
- Base can't be larger than 36.
"""
if number < 0:
raise ValueError("negative numbers not handled in base_repr")
@@ -670,8 +1413,32 @@ def _maketup(descr, val):
return tuple(res)
def ones(shape, dtype=None, order='C'):
- """Returns an array of the given dimensions which is initialized to all
- ones.
+ """
+ Return a new array of given shape and type, filled with ones.
+
+ Please refer to the documentation for `zeros`.
+
+ See Also
+ --------
+ zeros
+
+ Examples
+ --------
+ >>> np.ones(5)
+ array([ 1., 1., 1., 1., 1.])
+
+ >>> np.ones((5,), dtype=np.int)
+ array([1, 1, 1, 1, 1])
+
+ >>> np.ones((2, 1))
+ array([[ 1.],
+ [ 1.]])
+
+ >>> s = (2,2)
+ >>> np.ones(s)
+ array([[ 1., 1.],
+ [ 1., 1.]])
+
"""
a = empty(shape, dtype, order)
try:
@@ -685,10 +1452,32 @@ def ones(shape, dtype=None, order='C'):
return a
def identity(n, dtype=None):
- """Returns the identity 2-d array of shape n x n.
+ """
+ Return the identity array.
+
+ The identity array is a square array with ones on
+ the main diagonal.
+
+ Parameters
+ ----------
+ n : int
+ Number of rows (and columns) in `n` x `n` output.
+ dtype : data-type, optional
+ Data-type of the output. Defaults to ``float``.
+
+ Returns
+ -------
+ out : ndarray
+ `n` x `n` array with its main diagonal set to one,
+ and all other elements 0.
+
+ Examples
+ --------
+ >>> np.identity(3)
+ array([[ 1., 0., 0.],
+ [ 0., 1., 0.],
+ [ 0., 0., 1.]])
- identity(n)[i,j] == 1 for all i == j
- == 0 for all i != j
"""
a = array([1]+n*[0],dtype=dtype)
b = empty((n,n),dtype=dtype)
@@ -701,12 +1490,36 @@ def identity(n, dtype=None):
return b
def allclose(a, b, rtol=1.e-5, atol=1.e-8):
- """Returns True if all components of a and b are equal subject to given
- tolerances.
+ """
+ Returns True if all elements are equal subject to given tolerances.
+
+ The tolerance values are positive, typically very small numbers. The
+ relative difference (`rtol` * `b`) and the absolute difference (`atol`)
+ are added together to compare against the absolute difference between `a`
+ and `b`.
+
+ Parameters
+ ----------
+ a, b : array_like
+ Input arrays to compare.
+ rtol : Relative tolerance
+ The relative difference is equal to `rtol` * `b`.
+ atol : Absolute tolerance
+ The absolute difference is equal to `atol`.
+
+ See Also
+ --------
+ all, any, alltrue, sometrue
+
+ Examples
+ --------
+ >>> allclose(array([1e10,1e-7]), array([1.00001e10,1e-8]))
+ False
+ >>> allclose(array([1e10,1e-8]), array([1.00001e10,1e-9]))
+ True
+ >>> allclose(array([1e10,1e-8]), array([1.0001e10,1e-9]))
+ False
- The relative error rtol must be positive and << 1.0
- The absolute error atol usually comes into play for those elements of b that
- are very small or zero; it says how small a must be also.
"""
x = array(a, copy=False)
y = array(b, copy=False)
@@ -722,8 +1535,32 @@ def allclose(a, b, rtol=1.e-5, atol=1.e-8):
return all(less_equal(absolute(x-y), atol + rtol * absolute(y)))
def array_equal(a1, a2):
- """Returns True if a1 and a2 have identical shapes
- and all elements equal and False otherwise.
+ """
+ True if two arrays have the same shape and elements, False otherwise.
+
+ Parameters
+ ----------
+ a1 : array-like
+ First input array.
+ a2 : array-like
+ Second input array.
+
+ Returns
+ -------
+ b : {True, False}
+ Returns True if the arrays are equal.
+
+ Examples
+ --------
+ >>> np.array_equal([1,2],[1,2])
+ True
+ >>> np.array_equal(np.array([1,2]),np.array([1,2]))
+ True
+ >>> np.array_equal([1,2],[1,2,3])
+ False
+ >>> np.array_equal([1,2],[1,4])
+ False
+
"""
try:
a1, a2 = asarray(a1), asarray(a2)
@@ -849,15 +1686,75 @@ def getbufsize():
return umath.geterrobj()[0]
def seterrcall(func):
- """Set the callback function used when a floating-point error handler
- is set to 'call' or the object with a write method for use when
- the floating-point error handler is set to 'log'
+ """
+ Set the floating-point error callback function or log object.
+
+ There are two ways to capture floating-point error messages. The first
+ is to set the error-handler to 'call', using `seterr`. Then, set
+ the function to call using this function.
+
+ The second is to set the error-handler to `log`, using `seterr`.
+ Floating-point errors then trigger a call to the 'write' method of
+ the provided object.
+
+ Parameters
+ ----------
+ log_func_or_obj : callable f(err, flag) or object with write method
+ Function to call upon floating-point errors ('call'-mode) or
+ object whose 'write' method is used to log such message ('log'-mode).
+
+ The call function takes two arguments. The first is the
+ type of error (one of "divide", "over", "under", or "invalid"),
+ and the second is the status flag. The flag is a byte, whose
+ least-significant bits indicate the status::
+
+ [0 0 0 0 invalid over under invalid]
+
+ In other words, ``flags = divide + 2*over + 4*under + 8*invalid``.
+
+ If an object is provided, it's write method should take one argument,
+ a string.
+
+ Returns
+ -------
+ h : callable or log instance
+ The old error handler.
+
+ Examples
+ --------
+ Callback upon error:
+
+ >>> def err_handler(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
+ Floating point error (divide by zero), with flag 1
+ array([ Inf, Inf, Inf])
+
+ >>> np.seterrcall(saved_handler)
+ >>> np.seterr(**save_err)
+
+ Log error message:
+
+ >>> class Log(object):
+ def write(self, msg):
+ print "LOG: %s" % msg
+ ...
+
+ >>> log = Log()
+ >>> saved_handler = np.seterrcall(log)
+ >>> save_err = np.seterr(all='log')
+
+ >>> np.array([1,2,3])/0.0
+ LOG: Warning: divide by zero encountered in divide
- 'func' should be a function that takes two arguments. The first is
- type of error ("divide", "over", "under", or "invalid"), and the second
- is the status flag (= divide + 2*over + 4*under + 8*invalid).
+ >>> np.seterrcall(saved_handler)
+ >>> np.seterr(**save_err)
- Returns the old handler.
"""
if func is not None and not callable(func):
if not hasattr(func, 'write') or not callable(func.write):
diff --git a/numpy/core/records.py b/numpy/core/records.py
index 8d870eb22..545330a30 100644
--- a/numpy/core/records.py
+++ b/numpy/core/records.py
@@ -1,3 +1,39 @@
+"""
+Record Arrays
+=============
+Record arrays expose the fields of structured arrays as properties.
+
+Most commonly, ndarrays contain elements of a single type, e.g. floats, integers,
+bools etc. However, it is possible for elements to be combinations of these,
+such as::
+
+ >>> a = np.array([(1, 2.0), (1, 2.0)], dtype=[('x', int), ('y', float)])
+ >>> a
+ array([(1, 2.0), (1, 2.0)],
+ dtype=[('x', '<i4'), ('y', '<f8')])
+
+Here, each element consists of two fields: x (and int), and y (a float).
+This is known as a structured array. The different fields are analogous
+to columns in a spread-sheet. The different fields can be accessed as
+one would a dictionary::
+
+ >>> a['x']
+ array([1, 1])
+
+ >>> a['y']
+ array([ 2., 2.])
+
+Record arrays allow us to access fields as properties::
+
+ >>> ar = a.view(np.recarray)
+
+ >>> ar.x
+ array([1, 1])
+
+ >>> ar.y
+ array([ 2., 2.])
+
+"""
# All of the functions allow formats to be a dtype
__all__ = ['record', 'recarray', 'format_parser']
@@ -214,27 +250,107 @@ class record(nt.void):
# the fields (and any subfields)
class recarray(ndarray):
- """recarray(shape, dtype=None, buf=None, **kwds)
+ """
+ Construct an ndarray that allows field access using attributes.
- Subclass of ndarray that allows field access using attribute lookup.
+ Arrays may have a data-types containing fields, analagous
+ to columns in a spread sheet. An example is ``[(x, int), (y, float)]``,
+ where each entry in the array is a pair of ``(int, float)``. Normally,
+ these attributes are accessed using dictionary lookups such as ``arr['x']``
+ and ``arr['y']``. Record arrays allow the fields to be accessed as members
+ of the array, using ``arr.x`` and ``arr.y``.
Parameters
----------
shape : tuple
- shape of record array
- dtype : data-type or None
- The desired data-type. If this is None, then the data-type is determined
- by the *formats*, *names*, *titles*, *aligned*, and *byteorder* keywords.
- buf : [buffer] or None
- If this is None, then a new array is created of the given shape and data-type
- If this is an object exposing the buffer interface, then the array will
- use the memory from an existing buffer. In this case, the *offset* and
- *strides* keywords can also be used.
+ Shape of output array.
+ dtype : data-type, optional
+ The desired data-type. By default, the data-type is determined
+ from `formats`, `names`, `titles`, `aligned` and `byteorder`.
+ formats : list of data-types, optional
+ A list containing the data-types for the different columns, e.g.
+ ``['i4', 'f8', 'i4']``. `formats` does *not* support the new
+ convention of using types directly, i.e. ``(int, float, int)``.
+ Note that `formats` must be a list, not a tuple.
+ Given that `formats` is somewhat limited, we recommend specifying
+ `dtype` instead.
+ names : tuple of strings, optional
+ The name of each column, e.g. ``('x', 'y', 'z')``.
+ buf : buffer, optional
+ By default, a new array is created of the given shape and data-type.
+ If `buf` is specified and is an object exposing the buffer interface,
+ the array will use the memory from the existing buffer. In this case,
+ the `offset` and `strides` keywords are available.
+
+ Other Parameters
+ ----------------
+ titles : tuple of strings, optional
+ Aliases for column names. For example, if `names` were
+ ``('x', 'y', 'z')`` and `titles` is
+ ``('x_coordinate', 'y_coordinate', 'z_coordinate')``, then
+ ``arr['x']`` is equivalent to both ``arr.x`` and ``arr.x_coordinate``.
+ byteorder : {'<', '>', '='}, optional
+ Byte-order for all fields.
+ aligned : {True, False}, optional
+ Align the fields in memory as the C-compiler would.
+ strides : tuple of ints, optional
+ Buffer (`buf`) is interpreted according to these strides (strides
+ define how many bytes each array element, row, column, etc.
+ occupy in memory).
+ offset : int, optional
+ Start reading buffer (`buf`) from this offset onwards.
+
+ Returns
+ -------
+ rec : recarray
+ Empty array of the given shape and type.
See Also
--------
- format_parser : determine a data-type from formats, names, titles
+ rec.fromrecords : Construct a record array from data.
record : fundamental data-type for recarray
+ format_parser : determine a data-type from formats, names, titles
+
+ Notes
+ -----
+ This constructor can be compared to ``empty``: it creates a new record
+ array but does not fill it with data. To create a reccord array from data,
+ use one of the following methods:
+
+ 1. Create a standard ndarray and convert it to a record array,
+ using ``arr.view(np.recarray)``
+ 2. Use the `buf` keyword.
+ 3. Use `np.rec.fromrecords`.
+
+ Examples
+ --------
+ Create an array with two fields, ``x`` and ``y``:
+
+ >>> x = np.array([(1.0, 2), (3.0, 4)], dtype=[('x', float), ('y', int)])
+ >>> x
+ array([(1.0, 2), (3.0, 4)],
+ dtype=[('x', '<f8'), ('y', '<i4')])
+
+ >>> x['x']
+ array([ 1., 3.])
+
+ View the array as a record array:
+
+ >>> x = x.view(np.recarray)
+
+ >>> x.x
+ array([ 1., 3.])
+
+ >>> x.y
+ array([2, 4])
+
+ Create a new, empty record array:
+
+ >>> np.recarray((2,),
+ ... dtype=[('x', int), ('y', float), ('z', int)]) #doctest: +SKIP
+ rec.array([(-1073741821, 1.2249118382103472e-301, 24547520),
+ (3471280, 1.2134086255804012e-316, 0)],
+ dtype=[('x', '<i4'), ('y', '<f8'), ('z', '<i4')])
"""
def __new__(subtype, shape, dtype=None, buf=None, offset=0, strides=None,