This is an auto-generated version of Numpy Example List with added documentation from doc strings and arguments specification for methods and functions of Numpy 1.2.1.

Please do not edit this page directly. To update this page just follow the instructions.


...

>>> from numpy import *
>>> a = arange(12)
>>> a = a.reshape(3,2,2)
>>> print a
[[[ 0  1]
[ 2  3]]
[[ 4  5]
[ 6  7]]
[[ 8  9]
[10 11]]]
>>> a[...,0]                               # same as a[:,:,0]
array([[ 0,  2],
[ 4,  6],
[ 8, 10]])
>>> a[1:,...]                              # same as a[1:,:,:] or just a[1:]
array([[[ 4,  5],
[ 6,  7]],
[[ 8,  9],
[10, 11]]])

See also: [], newaxis

[]

>>> from numpy import *
>>> a = array([ [ 0, 1, 2, 3, 4],
...             [10,11,12,13,14],
...             [20,21,22,23,24],
...             [30,31,32,33,34] ])
>>>
>>> a[0,0]                                       # indices start by zero
0
>>> a[-1]                                        # last row
array([30, 31, 32, 33, 34])
>>> a[1:3,1:4]                                   # subarray
array([[11, 12, 13],
[21, 22, 23]])
>>>
>>> i = array([0,1,2,1])                         # array of indices for the first axis
>>> j = array([1,2,3,4])                         # array of indices for the second axis
>>> a[i,j]
array([ 1, 12, 23, 14])
>>>
>>> a[a<13]                                      # boolean indexing
array([ 0,  1,  2,  3,  4, 10, 11, 12])
>>>
>>> b1 = array( [True,False,True,False] )        # boolean row selector
>>> a[b1,:]
array([[ 0,  1,  2,  3,  4],
[20, 21, 22, 23, 24]])
>>>
>>> b2 = array( [False,True,True,False,True] )   # boolean column selector
>>> a[:,b2]
array([[ 1,  2,  4],
[11, 12, 14],
[21, 22, 24],
[31, 32, 34]])

See also: ..., newaxis, ix_, indices, nonzero, where, slice

T

ndarray.T

Same as self.transpose() except self is returned for self.ndim < 2.

Examples
--------
>>> x = np.array([[1.,2.],[3.,4.]])
>>> x.T
array([[ 1.,  3.],
       [ 2.,  4.]])

>>> from numpy import *
>>> x = array([[1.,2.],[3.,4.]])
>>> x
array([[ 1.,  2.],
[ 3.,  4.]])
>>> x.T                                           # shortcut for transpose()
array([[ 1.,  3.],
[ 2.,  4.]])

See also: transpose

abs()

numpy.abs(...)

y = absolute(x)

Calculate the absolute value element-wise.

Parameters
----------
x : array_like
    Input array.

Returns
-------
res : ndarray
    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 }`.

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()

>>> from numpy import *
>>> abs(-1)
1
>>> abs(array([-1.2, 1.2]))
array([ 1.2,  1.2])
>>> abs(1.2+1j)
1.5620499351813308

See also: absolute, angle

absolute()

numpy.absolute(...)

y = absolute(x)

Calculate the absolute value element-wise.

Parameters
----------
x : array_like
    Input array.

Returns
-------
res : ndarray
    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 }`.

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()

Synonym for abs()

See abs

accumulate

>>> from numpy import *
>>> add.accumulate(array([1.,2.,3.,4.]))                   # like reduce() but also gives intermediate results
array([  1.,   3.,   6.,  10.])
>>> array([1., 1.+2., (1.+2.)+3., ((1.+2.)+3.)+4.])        # this is what it computed
array([  1.,   3.,   6.,  10.])
>>> multiply.accumulate(array([1.,2.,3.,4.]))              # works also with other operands
array([  1.,   2.,   6.,  24.])
>>> array([1., 1.*2., (1.*2.)*3., ((1.*2.)*3.)*4.])        # this is what it computed
array([  1.,   2.,   6.,  24.])
>>> add.accumulate(array([[1,2,3],[4,5,6]]), axis = 0)     # accumulate every column separately
array([[1, 2, 3],
[5, 7, 9]])
>>> add.accumulate(array([[1,2,3],[4,5,6]]), axis = 1)     # accumulate every row separately
array([[ 1,  3,  6],
[ 4,  9, 15]])

See also: reduce, cumprod, cumsum

add()

numpy.add(...)

y = add(x1,x2)

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.]])

>>> from numpy import *
>>> add(array([-1.2, 1.2]), array([1,3]))
array([-0.2,  4.2])
>>> array([-1.2, 1.2]) + array([1,3])
array([-0.2,  4.2])

alen()

numpy.alen(a)

Return the length of the first dimension of the input array.

Parameters
----------
a : array_like
   Input array.

Returns
-------
alen : int
   Length of the first dimension of `a`.

See Also
--------
shape

Examples
--------
>>> a = np.zeros((7,4,5))
>>> a.shape[0]
7
>>> np.alen(a)
7

all()

numpy.all(a, axis=None, out=None)

Returns True if all elements evaluate to True.

Parameters
----------
a : array_like
    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, bool
    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

ndarray.all(...)

a.all(axis=None, out=None)

Returns True if all elements evaluate to True.

Refer to `numpy.all` for full documentation.

See Also
--------
numpy.all : equivalent function

>>> from numpy import *
>>> a = array([True, False, True])
>>> a.all()                              # if all elements of a are True: return True; otherwise False
False
>>> all(a)                              # this form also exists
False
>>> a = array([1,2,3])
>>> all(a > 0)                         # equivalent to (a > 0).all()
True

See also: any, alltrue, sometrue

allclose()

numpy.allclose(a, b, rtol=1.0000000000000001e-005, atol=1e-008)

Returns True if two arrays are element-wise equal within a tolerance.

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`.

Returns
-------
y : bool
    Returns True if the two arrays are equal within the given
    tolerance; False otherwise. If either array contains NaN, then
    False is returned.

See Also
--------
all, any, alltrue, sometrue

Notes
-----
If the following equation is element-wise True, then allclose returns
True.

 absolute(`a` - `b`) <= (`atol` + `rtol` * absolute(`b`))

Examples
--------
>>> np.allclose([1e10,1e-7], [1.00001e10,1e-8])
False
>>> np.allclose([1e10,1e-8], [1.00001e10,1e-9])
True
>>> np.allclose([1e10,1e-8], [1.0001e10,1e-9])
False
>>> np.allclose([1.0, np.nan], [1.0, np.nan])
False

>>> 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

alltrue()

numpy.alltrue(a, axis=None, out=None)

Check if all elements of input array are true.

See Also
--------
numpy.all : Equivalent function; see for details.

>>> from numpy import *
>>> b = array([True, False, True, True])
>>> alltrue(b)
False
>>> a = array([1, 5, 2, 7])
>>> alltrue(a >= 5)
False

See also: sometrue, all, any

alterdot()

numpy.alterdot(...)

alterdot() changes all dot functions to use blas.

amax()

numpy.amax(a, axis=None, out=None)

Return the maximum along an axis.

Parameters
----------
a : array_like
    Input data.
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 : ndarray
    A new array or a scalar with the result, or a reference to `out`
    if it was specified.

Examples
--------
>>> a = np.arange(4).reshape((2,2))
>>> a
array([[0, 1],
       [2, 3]])
>>> np.amax(a, axis=0)
array([2, 3])
>>> np.amax(a, axis=1)
array([1, 3])

amin()

numpy.amin(a, axis=None, out=None)

Return the minimum along an axis.

Parameters
----------
a : array_like
    Input data.
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 : ndarray
    A new array or a scalar with the result, or a reference to `out` if it
    was specified.

Examples
--------
>>> a = np.arange(4).reshape((2,2))
>>> a
array([[0, 1],
       [2, 3]])
>>> np.amin(a)           # Minimum of the flattened array
0
>>> np.amin(a, axis=0)         # Minima along the first axis
array([0, 1])
>>> np.amin(a, axis=1)         # Minima along the second axis
array([0, 2])

angle()

numpy.angle(z, deg=0)

Return the angle of the complex argument.

Parameters
----------
z : array_like
    A complex number or sequence of complex numbers.
deg : bool, optional
    Return angle in degrees if True, radians if False (default).

Returns
-------
angle : {ndarray, scalar}
    The counterclockwise angle from the positive real axis on
    the complex plane, with dtype as numpy.float64.

See Also
--------
arctan2

Examples
--------
>>> np.angle([1.0, 1.0j, 1+1j])               # in radians
array([ 0.        ,  1.57079633,  0.78539816])
>>> np.angle(1+1j, deg=True)                  # in degrees
45.0

>>> from numpy import *
>>> angle(1+1j)                                   # in radians
0.78539816339744828
>>> angle(1+1j,deg=True)                          # in degrees
45.0

See also: real, imag, hypot

any()

numpy.any(a, axis=None, out=None)

Test whether any elements of an array evaluate to True along an axis.

Parameters
----------
a : array_like
    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

ndarray.any(...)

a.any(axis=None, out=None)

Check if any of the elements of `a` are true.

Refer to `numpy.any` for full documentation.

See Also
--------
numpy.any : equivalent function

>>> from numpy import *
>>> a = array([True, False, True])
>>> a.any()                                 # gives True if at least 1 element of a is True, otherwise False
True
>>> any(a)                                  # this form also exists
True
>>> a = array([1,2,3])
>>> (a >= 1).any()                          # equivalent to any(a >= 1)
True

See also: all, alltrue, sometrue

append()

numpy.append(arr, values, axis=None)

Append values to the end of an array.

Parameters
----------
arr : array_like
    Values are appended to a copy of this array.
values : array_like
    These values are appended to a copy of `arr`.  It must be of the
    correct shape (the same shape as `arr`, excluding `axis`).  If `axis`
    is not specified, `values` can be any shape and will be flattened
    before use.
axis : int, optional
    The axis along which `values` are appended.  If `axis` is not given,
    both `arr` and `values` are flattened before use.

Returns
-------
out : ndarray
    A copy of `arr` with `values` appended to `axis`.  Note that `append`
    does not occur in-place: a new array is allocated and filled.

Examples
--------
>>> np.append([1, 2, 3], [[4, 5, 6], [7, 8, 9]])
array([1, 2, 3, 4, 5, 6, 7, 8, 9])

>>> np.append([[1, 2, 3], [4, 5, 6]], [[7, 8, 9]], axis=0)
array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]])

>>> from numpy import *
>>> a = array([10,20,30,40])
>>> append(a,50)
array([10, 20, 30, 40, 50])
>>> append(a,[50,60])
array([10, 20, 30, 40, 50, 60])
>>> a = array([[10,20,30],[40,50,60],[70,80,90]])
>>> append(a,[[15,15,15]],axis=0)
array([[10, 20, 30],
[40, 50, 60],
[70, 80, 90],
[15, 15, 15]])
>>> append(a,[[15],[15],[15]],axis=1)
array([[10, 20, 30, 15],
[40, 50, 60, 15],
[70, 80, 90, 15]])

See also: insert, delete, concatenate

apply_along_axis()

numpy.apply_along_axis(func1d, axis, arr, *args)

Apply function to 1-D slices along the given axis.

Execute `func1d(a[i],*args)` where `func1d` takes 1-D arrays, `a` is
the input array, and `i` is an integer that varies in order to apply the
function along the given axis for each 1-D subarray in `a`.

Parameters
----------
func1d : function
    This function should be able to take 1-D arrays. It is applied to 1-D
    slices of `a` along the specified axis.
axis : integer
    Axis along which `func1d` is applied.
a : ndarray
    Input array.
args : any
    Additional arguments to `func1d`.

Returns
-------
out : ndarray
    The output array. The shape of `out` is identical to the shape of `a`,
    except along the `axis` dimension, whose length is equal to the size
    of the return value of `func1d`.

See Also
--------
apply_over_axes : Apply a function repeatedly over multiple axes.

Examples
--------
>>> def my_func(a):
...     """Average first and last element of a 1-D array"""
...     return (a[0] + a[-1]) * 0.5
>>> b = np.array([[1,2,3], [4,5,6], [7,8,9]])
>>> np.apply_along_axis(my_func, 0, b)
array([4., 5., 6.])
>>> np.apply_along_axis(my_func, 1, b)
array([2., 5., 8.])

>>> from numpy import *
>>> def myfunc(a):                                # function works on a 1d arrays, takes the average of the 1st an last element
...   return (a[0]+a[-1])/2
...
>>> b = array([[1,2,3],[4,5,6],[7,8,9]])
>>> apply_along_axis(myfunc,0,b)                 # apply myfunc to each column (axis=0) of b
array([4, 5, 6])
>>> apply_along_axis(myfunc,1,b)                # apply myfunc to each row (axis=1) of b
array([2, 5, 8])

See also: apply_over_axes, vectorize

apply_over_axes()

numpy.apply_over_axes(func, a, axes)

Apply a function repeatedly over multiple axes.

`func` is called as `res = func(a, axis)`, where `axis` is the first
element of `axes`.  The result `res` of the function call must have
either the same dimensions as `a` or one less dimension. If `res` has one
less dimension than `a`, a dimension is inserted before `axis`.
The call to `func` is then repeated for each axis in  `axes`,
with `res` as the first argument.

Parameters
----------
func : function
    This function must take two arguments, `func(a, axis)`.
a : ndarray
    Input array.
axes : array_like
    Axes over which `func` is applied, the elements must be
    integers.

Returns
-------
val : ndarray
    The output array. The number of dimensions is the same as `a`, but
    the shape can be different. This depends on whether `func` changes
    the shape of its output with respect to its input.

See Also
--------
apply_along_axis :
    Apply a function to 1-D slices of an array along the given axis.

Examples
--------
>>> a = np.arange(24).reshape(2,3,4)
>>> a
array([[[ 0,  1,  2,  3],
        [ 4,  5,  6,  7],
        [ 8,  9, 10, 11]],
<BLANKLINE>
       [[12, 13, 14, 15],
        [16, 17, 18, 19],
        [20, 21, 22, 23]]])

Sum over axes 0 and 2. The result has same number of dimensions
as the original array:

>>> np.apply_over_axes(np.sum, a, [0,2])
array([[[ 60],
        [ 92],
        [124]]])

>>> from numpy import *
>>> a = arange(24).reshape(2,3,4)         # a has 3 axes: 0,1 and 2
>>> a
array([[[ 0,  1,  2,  3],
[ 4,  5,  6,  7],
[ 8,  9, 10, 11]],
[[12, 13, 14, 15],
[16, 17, 18, 19],
[20, 21, 22, 23]]])
>>> apply_over_axes(sum, a, [0,2])        # sum over all axes except axis=1, result has same shape as original
array([[[ 60],
[ 92],
[124]]])

See also: apply_along_axis, vectorize

arange()

numpy.arange(...)

arange([start,] stop[, step,], dtype=None)

Return evenly spaced values within a given interval.

Values are generated within the half-open interval ``[start, stop)``
(in other words, the interval including `start` but excluding `stop`).
For integer arguments the function is equivalent to the Python built-in
`range <http://docs.python.org/lib/built-in-funcs.html>`_ function,
but returns a ndarray rather than a list.

Parameters
----------
start : number, optional
    Start of interval.  The interval includes this value.  The default
    start value is 0.
stop : number
    End of interval.  The interval does not include this value.
step : number, optional
    Spacing between values.  For any output `out`, this is the distance
    between two adjacent values, ``out[i+1] - out[i]``.  The default
    step size is 1.  If `step` is specified, `start` must also be given.
dtype : dtype
    The type of the output array.  If `dtype` is not given, infer the data
    type from the other input arguments.

Returns
-------
out : ndarray
    Array of evenly spaced values.

    For floating point arguments, the length of the result is
    ``ceil((stop - start)/step)``.  Because of floating point overflow,
    this rule may result in the last element of `out` being greater
    than `stop`.

See Also
--------
linspace : Evenly spaced numbers with careful handling of endpoints.
ogrid: Arrays of evenly spaced numbers in N-dimensions
mgrid: Grid-shaped arrays of evenly spaced numbers in N-dimensions

Examples
--------
>>> np.arange(3)
array([0, 1, 2])
>>> np.arange(3.0)
array([ 0.,  1.,  2.])
>>> np.arange(3,7)
array([3, 4, 5, 6])
>>> np.arange(3,7,2)
array([3, 5])

>>> from numpy import *
>>> arange(3)
array([0, 1, 2])
>>> arange(3.0)
array([ 0.,  1.,  2.])
>>> arange(3, dtype=float)
array([ 0.,  1.,  2.])
>>> arange(3,10)                                 # start,stop
array([3, 4, 5, 6, 7, 8, 9])
>>> arange(3,10,2)                              # start,stop,step
array([3, 5, 7, 9])

See also: r_, linspace, logspace, mgrid, ogrid

arccos()

numpy.arccos(...)

y = arccos(x)

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
    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()

>>> from numpy import *
>>> arccos(array([0, 1]))
array([ 1.57079633,  0.        ])

See also: arcsin, arccosh, arctan, arctan2

arccosh()

numpy.arccosh(...)

y = arccosh(x)

Inverse hyperbolic cosine, elementwise.

Parameters
----------
x : array_like
    Input array.

Returns
-------
out : ndarray
    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])

>>> from numpy import *
>>> arccosh(array([e, 10.0]))
array([ 1.65745445,  2.99322285])

See also: arccos, arcsinh, arctanh

arcsin()

numpy.arcsin(...)

y = arcsin(x)

Inverse sine elementwise.

Parameters
----------
x : array_like
  `y`-coordinate on the unit circle.

Returns
-------
angle : ndarray
  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

>>> from numpy import *
>>> arcsin(array([0, 1]))
array([ 0.        ,  1.57079633])

See also: arccos, arctan, arcsinh

arcsinh()

numpy.arcsinh(...)

y = arcsinh(x)

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
returns ``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])

>>> from numpy import *
>>> arcsinh(array([e, 10.0]))
array([ 1.72538256,  2.99822295])

See also: arccosh, arcsin, arctanh

arctan()

numpy.arctan(...)

y = arctan(x)

Trigonometric inverse tangent, element-wise.

The inverse of tan, so that if ``y = tan(x)`` then
``x = arctan(y)``.

Parameters
----------
x : array_like
    Input values.  `arctan` is applied to each element of `x`.

Returns
-------
out : ndarray
    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()

>>> from numpy import *
>>> arctan(array([0, 1]))
array([ 0.        ,  0.78539816])

See also: arccos, arcsin, arctanh

arctan2()

numpy.arctan2(...)

y = arctan2(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 : ndarray
    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])

>>> from numpy import *
>>> arctan2(array([0, 1]), array([1, 0]))
array([ 0.        ,  1.57079633])

See also: arcsin, arccos, arctan, arctanh

arctanh()

numpy.arctanh(...)

y = arctanh(x)

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])

>>> from numpy import *
>>> arctanh(array([0, -0.5]))
array([ 0.        , -0.54930614])

See also: arcsinh, arccosh, arctan, arctan2

argmax()

numpy.argmax(a, axis=None)

Indices of the maximum values along an axis.

Parameters
----------
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 : ndarray, int
    Array of indices into the array.  It has the same shape as `a`,
    except with `axis` removed.

See Also
--------
argmin : Indices of the minimum values along an axis.
amax : The maximum value 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, axis=0)
array([1, 1, 1])
>>> np.argmax(a, axis=1)
array([2, 2])

ndarray.argmax(...)

a.argmax(axis=None, out=None)

Return indices of the maximum values along the given axis of `a`.

Parameters
----------
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
-------
index_array : ndarray
    An array of indices or single index value, or a reference to `out`
    if it was specified.

Examples
--------
>>> a = np.arange(6).reshape(2,3)
>>> a.argmax()
5
>>> a.argmax(0)
array([1, 1, 1])
>>> a.argmax(1)
array([2, 2])

>>> from numpy import *
>>> a = array([10,20,30])
>>> maxindex = a.argmax()
>>> a[maxindex]
30
>>> a = array([[10,50,30],[60,20,40]])
>>> maxindex = a.argmax()
>>> maxindex
3
>>> a.ravel()[maxindex]
60
>>> a.argmax(axis=0)                        # for each column: the row index of the maximum value
array([1, 0, 1])
>>> a.argmax(axis=1)                       # for each row: the column index of the maximum value
array([1, 0])
>>> argmax(a)                              # also exists, slower, default is axis=-1
array([1, 0])

See also: argmin, nan, min, max, maximum, minimum

argmin()

numpy.argmin(a, axis=None)

Return the indices of the minimum values along an axis.

See Also
--------
argmax : Similar function.  Please refer to `numpy.argmax` for detailed
    documentation.

ndarray.argmin(...)

a.argmin(axis=None, out=None)

Return indices of the minimum values along the given axis of `a`.

Refer to `numpy.ndarray.argmax` for detailed documentation.

>>> from numpy import *
>>> a = array([10,20,30])
>>> minindex = a.argmin()
>>> a[minindex]
10
>>> a = array([[10,50,30],[60,20,40]])
>>> minindex = a.argmin()
>>> minindex
0
>>> a.ravel()[minindex]
10
>>> a.argmin(axis=0)                           # for each column: the row index of the minimum value
array([0, 1, 0])
>>> a.argmin(axis=1)                           # for each row: the column index of the minimum value
array([0, 1])
>>> argmin(a)                                  #  also exists, slower, default is axis=-1
array([0, 1])

See also: argmax, nan, min, max, maximum, minimum

argsort()

numpy.argsort(a, axis=-1, kind='quicksort', order=None)

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.

Parameters
----------
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.
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 : ndarray, int
    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.
ndarray.sort : Inplace sort.

Notes
-----
See `sort` for notes on the different sorting algorithms.

Examples
--------
One dimensional array:

>>> 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])

ndarray.argsort(...)

a.argsort(axis=-1, kind='quicksort', order=None)

Returns the indices that would sort this array.

Refer to `numpy.argsort` for full documentation.

See Also
--------
numpy.argsort : equivalent function

argsort(axis=-1, kind="quicksort")

>>> from numpy import *
>>> a = array([2,0,8,4,1])
>>> ind = a.argsort()               # indices of sorted array using quicksort (default)
>>> ind
array([1, 4, 0, 3, 2])
>>> a[ind]                          # same effect as a.sort()
array([0, 1, 2, 4, 8])
>>> ind = a.argsort(kind='merge')   # algorithm options are 'quicksort', 'mergesort' and 'heapsort'
>>> a = array([[8,4,1],[2,0,9]])
>>> ind = a.argsort(axis=0)         # sorts on columns. NOT the same as a.sort(axis=1)
>>> ind
array([[1, 1, 0],
[0, 0, 1]])
>>> a[ind,[[0,1,2],[0,1,2]]]        # 2-D arrays need fancy indexing if you want to sort them.
array([[2, 0, 1],
[8, 4, 9]])
>>> ind = a.argsort(axis=1)         # sort along rows. Can use a.argsort(axis=-1) for last axis.
>>> ind
array([[2, 1, 0],
[1, 0, 2]])
>>> a = ones(17)
>>> a.argsort()                     # quicksort doesn't preserve original order.
array([ 0, 14, 13, 12, 11, 10,  9, 15,  8,  6,  5,  4,  3,  2,  1,  7, 16])
>>> a.argsort(kind="mergesort")     # mergesort preserves order when possible. It is a stable sort.
array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16])
>>> ind = argsort(a)                # there is a functional form

See also: lexsort, sort

argwhere()

numpy.argwhere(a)

Find the indices of array elements that are non-zero, grouped by element.

Parameters
----------
a : array_like
    Input data.

Returns
-------
index_array : ndarray
    Indices of elements that are non-zero. Indices are grouped by element.

See Also
--------
where, nonzero

Notes
-----
``np.argwhere(a)`` is the same as ``np.transpose(np.nonzero(a))``.

The output of ``argwhere`` is not suitable for indexing arrays.
For this purpose use ``where(a)`` instead.

Examples
--------
>>> x = np.arange(6).reshape(2,3)
>>> x
array([[0, 1, 2],
       [3, 4, 5]])
>>> np.argwhere(x>1)
array([[0, 2],
       [1, 0],
       [1, 1],
       [1, 2]])

around()

numpy.around(a, decimals=0, out=None)

Evenly round to the given number of decimals.

Parameters
----------
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 of the output
    values will be cast if necessary.

Returns
-------
rounded_array : ndarray
    An array of the same type as `a`, containing the rounded values.
    Unless `out` 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
--------
ndarray.round : equivalent method

Notes
-----
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
--------
>>> np.around([.5, 1.5, 2.5, 3.5, 4.5])
array([ 0.,  2.,  2.,  4.,  4.])
>>> np.around([1,2,3,11], decimals=1)
array([ 1,  2,  3, 11])
>>> np.around([1,2,3,11], decimals=-1)
array([ 0,  0,  0, 10])

array()

numpy.array(...)

array(object, dtype=None, copy=True, order=None, subok=True, ndmin=True)

Create an array.

Parameters
----------
object : array_like
    An array, any object exposing the array interface, an
    object whose __array__ method returns an array, or any
    (nested) sequence.
dtype : data-type, optional
    The desired data-type for the array.  If not given, then
    the type will be determined as the minimum type required
    to hold the objects in the sequence.  This argument can only
    be used to 'upcast' the array.  For downcasting, use the
    .astype(t) method.
copy : bool, optional
    If true (default), then the object is copied.  Otherwise, a copy
    will only be made if __array__ returns a copy, if obj is a
    nested sequence, or if a copy is needed to satisfy any of the other
    requirements (`dtype`, `order`, etc.).
order : {'C', 'F', 'A'}, optional
    Specify the order of the array.  If order is 'C' (default), then the
    array will be in C-contiguous order (last-index varies the
    fastest).  If order is 'F', then the returned array
    will be in Fortran-contiguous order (first-index varies the
    fastest).  If order is 'A', then the returned array may
    be in any order (either C-, Fortran-contiguous, or even
    discontiguous).
subok : bool, optional
    If True, then sub-classes will be passed-through, otherwise
    the returned array will be forced to be a base-class array.
ndmin : int, optional
    Specifies the minimum number of dimensions that the resulting
    array should have.  Ones will be pre-pended to the shape as
    needed to meet this requirement.

Examples
--------
>>> np.array([1, 2, 3])
array([1, 2, 3])

Upcasting:

>>> np.array([1, 2, 3.0])
array([ 1.,  2.,  3.])

More than one dimension:

>>> np.array([[1, 2], [3, 4]])
array([[1, 2],
       [3, 4]])

Minimum dimensions 2:

>>> np.array([1, 2, 3], ndmin=2)
array([[1, 2, 3]])

Type provided:

>>> np.array([1, 2, 3], dtype=complex)
array([ 1.+0.j,  2.+0.j,  3.+0.j])

Data-type consisting of more than one element:

>>> x = np.array([(1,2),(3,4)],dtype=[('a','<i4'),('b','<i4')])
>>> x['a']
array([1, 3])

Creating an array from sub-classes:

>>> np.array(np.mat('1 2; 3 4'))
array([[1, 2],
       [3, 4]])

>>> np.array(np.mat('1 2; 3 4'), subok=True)
matrix([[1, 2],
        [3, 4]])

numpy.core.records.array(obj, dtype=None, shape=None, offset=0, strides=None, formats=None, names=None, titles=None, aligned=False, byteorder=None, copy=True)

Construct a record array from a wide-variety of objects.

>>> from numpy import *
>>> array([1,2,3])                                                                         # conversion from a list to an array
array([1, 2, 3])
>>> array([1,2,3], dtype=complex)                                                          # output type is specified
array([ 1.+0.j,  2.+0.j,  3.+0.j])
>>> array(1, copy=0, subok=1, ndmin=1)                                                     # basically equivalent to atleast_1d
array([1])
>>> array(1, copy=0, subok=1, ndmin=2)                                                     # basically equivalent to atleast_2d
array([[1]])
>>> array(1, subok=1, ndmin=2)                                                             # like atleast_2d but always makes a copy
array([[1]])
>>> mydescriptor = {'names': ('gender','age','weight'), 'formats': ('S1', 'f4', 'f4')}     # one way of specifying the data type
>>> a = array([('M',64.0,75.0),('F',25.0,60.0)], dtype=mydescriptor)                       # recarray
>>> print a
[('M', 64.0, 75.0) ('F', 25.0, 60.0)]
>>> a['weight']
array([ 75.,  60.], dtype=float32)
>>> a.dtype.names                                                                          # Access to the ordered field names
('gender','age','weight')
>>> mydescriptor = [('age',int16),('Nchildren',int8),('weight',float32)]                   # another way of specifying the data type
>>> a = array([(64,2,75.0),(25,0,60.0)], dtype=mydescriptor)
>>> a['Nchildren']
array([2, 0], dtype=int8)
>>> mydescriptor = dtype([('x', 'f4'),('y', 'f4'),                                         # nested recarray
...     ('nested', [('i', 'i2'),('j','i2')])])
>>> array([(1.0, 2.0, (1,2))], dtype=mydescriptor)                                         # input one row
array([(1.0, 2.0, (1, 2))],
dtype=[('x', '<f4'), ('y', '<f4'), ('nested', [('i', '<i2'), ('j', '<i2')])])
>>> array([(1.0, 2.0, (1,2)), (2.1, 3.2, (3,2))], dtype=mydescriptor)                      # input two rows
array([(1.0, 2.0, (1, 2)), (2.0999999046325684, 3.2000000476837158, (3, 2))],
dtype=[('x', '<f4'), ('y', '<f4'), ('nested', [('i', '<i2'), ('j', '<i2')])])
>>> a=array([(1.0, 2.0, (1,2)), (2.1, 3.2, (3,2))], dtype=mydescriptor)                    # getting some columns
>>> a['x']                                                                                 # a plain column
array([ 1.       ,  2.0999999], dtype=float32)
>>> a['nested']                                                                            # a nested column
array([(1, 2), (3, 2)],
dtype=[('i', '<i2'), ('j', '<i2')])
>>> a['nested']['i']                                                                       # a plain column inside a nested column
>>> mydescriptor = dtype([('x', 'f4'),('y', 'f4'),                                         # nested recarray
...     ('nested', [('i', 'i2'),('j','i2')])])
>>> array([(1.0, 2.0, (1,2))], dtype=mydescriptor)                                         # input one row
array([(1.0, 2.0, (1, 2))],
dtype=[('x', '<f4'), ('y', '<f4'), ('nested', [('i', '<i2'), ('j', '<i2')])])
>>> array([(1.0, 2.0, (1,2)), (2.1, 3.2, (3,2))], dtype=mydescriptor)                      # input two rows
array([(1.0, 2.0, (1, 2)), (2.0999999046325684, 3.2000000476837158, (3, 2))],
dtype=[('x', '<f4'), ('y', '<f4'), ('nested', [('i', '<i2'), ('j', '<i2')])])
>>> a=array([(1.0, 2.0, (1,2)), (2.1, 3.2, (3,2))], dtype=mydescriptor)                    # getting some columns
>>> a['x']                                                                                 # a plain column
array([ 1.       ,  2.0999999], dtype=float32)
>>> a['nested']                                                                            # a nested column
array([(1, 2), (3, 2)],
dtype=[('i', '<i2'), ('j', '<i2')])
>>> a['nested']['i']                                                                       # a plain column inside a nested column
array([1, 3], dtype=int16)

See also: dtype, mat, asarray

array2string()

numpy.array2string(a, max_line_width=None, precision=None, suppress_small=None, separator=' ', prefix="", style=<built-in function repr>)

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. Default is the current printing
    precision (usually 8), which can be altered using `set_printoptions`.
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, set_printoptions

Examples
--------
>>> x = np.array([1e-16,1,2,3])
>>> print np.array2string(x, precision=2, separator=',',
...                       suppress_small=True)
[ 0., 1., 2., 3.]

array_equal()

numpy.array_equal(a1, a2)

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

array_equiv()

numpy.array_equiv(a1, a2)

Returns True if input arrays are shape consistent and all elements equal.

Parameters
----------
a1 : array_like
    Input array.
a2 : array_like
    Input array.

Returns
-------
out : bool
    True if equivalent, False otherwise.

Examples
--------
>>> np.array_equiv([1,2],[1,2])
>>> True
>>> np.array_equiv([1,2],[1,3])
>>> False
>>> np.array_equiv([1,2], [[1,2],[1,2]])
>>> True
>>> np.array_equiv([1,2], [[1,2],[1,3]])
>>> False

array_repr()

numpy.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)'

array_split()

numpy.array_split(ary, indices_or_sections, axis=0)

Split an array into multiple sub-arrays of equal or near-equal size.

Please refer to the `numpy.split` documentation.  The only difference
between these functions is that `array_split` allows `indices_or_sections`
to be an integer that does *not* equally divide the axis.

See Also
--------
numpy.split : Split array into multiple sub-arrays.

Examples
--------
>>> x = np.arange(8.0)
>>> np.array_split(x, 3)
    [array([ 0.,  1.,  2.]), array([ 3.,  4.,  5.]), array([ 6.,  7.])]

>>> from numpy import *
>>> a = array([[1,2,3,4],[5,6,7,8]])
>>> array_split(a,2,axis=0)                            # split a in 2 parts. row-wise
[array([[1, 2, 3, 4]]), array([[5, 6, 7, 8]])]
>>> array_split(a,4,axis=1)                            # split a in 4 parts, column-wise
[array([[1],
[5]]), array([[2],
[6]]), array([[3],
[7]]), array([[4],
[8]])]
>>> array_split(a,3,axis=1)                          # impossible to split in 3 equal parts -> first part(s) are bigger
[array([[1, 2],
[5, 6]]), array([[3],
[7]]), array([[4],
[8]])]
>>> array_split(a,[2,3],axis=1)                      # make a split before the 2nd and the 3rd column
[array([[1, 2],
[5, 6]]), array([[3],
[7]]), array([[4],
[8]])]

See also: dsplit, hsplit, vsplit, split, concatenate

array_str()

numpy.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]'

arrayrange

Synonym for arange()

See arange

asanyarray()

numpy.asanyarray(a, dtype=None, order=None)

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

>>> from numpy import *
>>> a = array([[1,2],[5,8]])
>>> a
array([[1, 2],
[5, 8]])
>>> m = matrix('1 2; 5 8')
>>> m
matrix([[1, 2],
[5, 8]])
>>> asanyarray(a)         # the array a is returned unmodified
array([[1, 2],
[5, 8]])
>>> asanyarray(m)         # the matrix m is returned unmodified
matrix([[1, 2],
[5, 8]])
>>> asanyarray([1,2,3])   # a new array is constructed from the list
array([1, 2, 3])

See also: asmatrix, asarray, array, mat

asarray()

numpy.asarray(a, dtype=None, order=None)

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

>>> from numpy import *
>>> m = matrix('1 2; 5 8')
>>> m
matrix([[1, 2],
[5, 8]])
>>> a = asarray(m)           # a is array type with same contents as m -- data is not copied
>>> a
array([[1, 2],
[5, 8]])
>>> m[0,0] = -99
>>> m
matrix([[-99,   2],
[  5,   8]])
>>> a                        # no copy was made, so modifying m modifies a, and vice versa
array([[-99,   2],
[  5,   8]])

See also: asmatrix, array, matrix, mat

asarray_chkfinite()

numpy.asarray_chkfinite(a)

Convert the input to an array, checking for NaNs or Infs.

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.  Success requires no NaNs or Infs.
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.

Raises
------
ValueError
    Raises ValueError if `a` contains NaN (Not a Number) or Inf (Infinity).

See Also
--------
asarray : Create and array.
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.
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.  If all elements are finite
``asarray_chkfinite`` is identical to ``asarray``.

>>> a = [1, 2]
>>> np.asarray_chkfinite(a)
array([1, 2])

Raises ValueError if array_like contains Nans or Infs.

>>> a = [1, 2, np.inf]
>>> try:
...     np.asarray_chkfinite(a)
... except ValueError:
...     print 'ValueError'
...
ValueError

ascontiguousarray()

numpy.ascontiguousarray(a, dtype=None)

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`.

asfarray()

numpy.asfarray(a, dtype=<type 'numpy.float64'>)

Return an array converted to float type.

Parameters
----------
a : array_like
    Input array.
dtype : string or dtype object, optional
    Float type code to coerce input array `a`.  If one of the 'int' dtype,
    it is replaced with float64.

Returns
-------
out : ndarray, float
    Input `a` as a float ndarray.

Examples
--------
>>> np.asfarray([2, 3])
array([ 2.,  3.])
>>> np.asfarray([2, 3], dtype='float')
array([ 2.,  3.])
>>> np.asfarray([2, 3], dtype='int8')
array([ 2.,  3.])

asfortranarray()

numpy.asfortranarray(a, dtype=None)

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.

asmatrix()

numpy.asmatrix(data, dtype=None)

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]])

>>> from numpy import *
>>> a = array([[1,2],[5,8]])
>>> a
array([[1, 2],
[5, 8]])
>>> m = asmatrix(a)        # m is matrix type with same contents as a -- data is not copied
>>> m
matrix([[1, 2],
[5, 8]])
>>> a[0,0] = -99
>>> a
array([[-99,   2],
[  5,   8]])
>>> m                      # no copy was made so modifying a modifies m, and vice versa
matrix([[-99,   2],
[  5,   8]])

See also: asarray, array, matrix, mat

asscalar()

numpy.asscalar(a)

Convert an array of size 1 to its scalar equivalent.

Parameters
----------
a : ndarray
    Input array.

Returns
-------
out : scalar
    Scalar of size 1 array.

Examples
--------
>>> np.asscalar(np.array([24]))
>>> 24

astype()

ndarray.astype(...)

a.astype(t)

Copy of the array, cast to a specified type.

Parameters
----------
t : string or dtype
    Typecode or data-type to which the array is cast.

Examples
--------
>>> x = np.array([1, 2, 2.5])
>>> x
array([ 1. ,  2. ,  2.5])

>>> x.astype(int)
array([1, 2, 2])

>>> from numpy import *
>>> x = array([1,2,3])
>>> y = x.astype(float64)                  # convert from int32 to float64
>>> type(y[0])
<type 'numpy.float64'>
>>> x.astype(None)                         # None implies converting to the default (float64)
array([1., 2., 3.])

See also: cast, dtype, ceil, floor, round_, fix

atleast_1d()

numpy.atleast_1d(*arys)

Convert inputs to arrays with at least one dimension.

Scalar inputs are converted to 1-dimensional arrays, whilst
higher-dimensional inputs are preserved.

Parameters
----------
array1, array2, ... : array_like
    One or more input arrays.

Returns
-------
ret : ndarray
    An array, or sequence of arrays, each with ``a.ndim >= 1``.
    Copies are made only if necessary.

See Also
--------
atleast_2d, atleast_3d

Examples
--------
>>> np.atleast_1d(1.0)
array([ 1.])

>>> x = np.arange(9.0).reshape(3,3)
>>> np.atleast_1d(x)
array([[ 0.,  1.,  2.],
       [ 3.,  4.,  5.],
       [ 6.,  7.,  8.]])
>>> np.atleast_1d(x) is x
True

>>> np.atleast_1d(1, [3, 4])
[array([1]), array([3, 4])]

>>> from numpy import *
>>> a = 1                                       # 0-d array
>>> b = array([2,3])                            # 1-d array
>>> c = array([[4,5],[6,7]])                    # 2-d array
>>> d = arange(8).reshape(2,2,2)                # 3-d array
>>> d
array([[[0, 1],
[2, 3]],
[[4, 5],
[6, 7]]])
>>> atleast_1d(a,b,c,d)                        # all output arrays have dim >= 1
[array([1]), array([2, 3]), array([[4, 5],
[6, 7]]), array([[[0, 1],
[2, 3]],
[[4, 5],
[6, 7]]])]

See also: atleast_2d, atleast_3d, newaxis, expand_dims

atleast_2d()

numpy.atleast_2d(*arys)

View inputs as arrays with at least two dimensions.

Parameters
----------
array1, array2, ... : array_like
    One or more array-like sequences.  Non-array inputs are converted
    to arrays.  Arrays that already have two or more dimensions are
    preserved.

Returns
-------
res, res2, ... : ndarray
    An array, or tuple of arrays, each with ``a.ndim >= 2``.
    Copies are avoided where possible, and views with two or more
    dimensions are returned.

See Also
--------
atleast_1d, atleast_3d

Examples
--------
>>> numpy.atleast_2d(3.0)
array([[ 3.]])

>>> x = numpy.arange(3.0)
>>> numpy.atleast_2d(x)
array([[ 0.,  1.,  2.]])
>>> numpy.atleast_2d(x).base is x
True

>>> np.atleast_2d(1, [1, 2], [[1, 2]])
[array([[1]]), array([[1, 2]]), array([[1, 2]])]

>>> from numpy import *
>>> a = 1                                               # 0-d array
>>> b = array([2,3])                                    # 1-d array
>>> c = array([[4,5],[6,7]])                            # 2-d array
>>> d = arange(8).reshape(2,2,2)                        # 3-d array
>>> d
array([[[0, 1],
[2, 3]],
[[4, 5],
[6, 7]]])
>>> atleast_2d(a,b,c,d)                                # all output arrays have dim >= 2
[array([[1]]), array([[2, 3]]), array([[4, 5],
[6, 7]]), array([[[0, 1],
[2, 3]],
[[4, 5],
[6, 7]]])]

See also: atleast_1d, atleast_3d, newaxis, expand_dims

atleast_3d()

numpy.atleast_3d(*arys)

View inputs as arrays with at least three dimensions.

Parameters
----------
array1, array2, ... : array_like
    One or more array-like sequences.  Non-array inputs are converted
    to arrays. Arrays that already have three or more dimensions are
    preserved.

Returns
-------
res1, res2, ... : ndarray
    An array, or tuple of arrays, each with ``a.ndim >= 3``.
    Copies are avoided where possible, and views with three or more
    dimensions are returned.  For example, a one-dimensional array of
    shape ``N`` becomes a view of shape ``(1, N, 1)``.  An ``(M, N)``
    array becomes a view of shape ``(N, M, 1)``.

See Also
--------
numpy.atleast_1d, numpy.atleast_2d

Examples
--------
>>> numpy.atleast_3d(3.0)
array([[[ 3.]]])

>>> x = numpy.arange(3.0)
>>> numpy.atleast_3d(x).shape
(1, 3, 1)

>>> x = numpy.arange(12.0).reshape(4,3)
>>> numpy.atleast_3d(x).shape
(4, 3, 1)
>>> numpy.atleast_3d(x).base is x
True

>>> for arr in np.atleast_3d(1, [1, 2], [[1, 2]]): print arr, "\n"
...
[[[1]]]

[[[1]
  [2]]]

[[[1]
  [2]]]

>>> from numpy import *
>>> a = 1                                       # 0-d array
>>> b = array([2,3])                            # 1-d array
>>> c = array([[4,5],[6,7]])                    # 2-d array
>>> d = arange(8).reshape(2,2,2)                # 3-d array
>>> d
array([[[0, 1],
[2, 3]],
[[4, 5],
[6, 7]]])
>>> atleast_3d(a,b,c,d)                       # all output arrays have dim >= 3
[array([[[1]]]), array([[[2],
[3]]]), array([[[4],
[5]],
[[6],
[7]]]), array([[[0, 1],
[2, 3]],
[[4, 5],
[6, 7]]])]

See also: atleast_1d, atleast_2d, newaxis, expand_dims

average()

numpy.average(a, axis=None, weights=None, returned=False)

Return the weighted average of array over the specified axis.

Parameters
----------
a : array_like
    Data to be averaged.
axis : int, optional
    Axis along which to average `a`. If `None`, averaging is done over the
    entire array irrespective of its shape.
weights : array_like, optional
    The importance that each datum has in the computation of the average.
    The weights array can either be 1-D (in which case its length must be
    the size of `a` along the given axis) or of the same shape as `a`.
    If `weights=None`, then all data in `a` are assumed to have a
    weight equal to one.
returned : bool, optional
    Default is `False`. If `True`, the tuple (`average`, `sum_of_weights`)
    is returned, otherwise only the average is returned.  Note that
    if `weights=None`, `sum_of_weights` is equivalent to the number of
    elements over which the average is taken.

Returns
-------
average, [sum_of_weights] : {array_type, double}
    Return the average along the specified axis. When returned is `True`,
    return a tuple with the average as the first element and the sum
    of the weights as the second element. The return type is `Float`
    if `a` is of integer type, otherwise it is of the same type as `a`.
    `sum_of_weights` is of the same type as `average`.

Raises
------
ZeroDivisionError
    When all weights along axis are zero. See `numpy.ma.average` for a
    version robust to this type of error.
TypeError
    When the length of 1D `weights` is not the same as the shape of `a`
    along axis.

See Also
--------
ma.average : average for masked arrays

Examples
--------
>>> data = range(1,5)
>>> data
[1, 2, 3, 4]
>>> np.average(data)
2.5
>>> np.average(range(1,11), weights=range(10,0,-1))
4.0

>>> from numpy import *
>>> a = array([1,2,3,4,5])
>>> w = array([0.1, 0.2, 0.5, 0.2, 0.2])             # weights, not necessarily normalized
>>> average(a)                                       # plain mean value
3.0
>>> average(a,weights=w)                            # weighted average
3.1666666666666665
>>> average(a,weights=w,returned=True)              # output = weighted average, sum of weights
(3.1666666666666665, 1.2)

See also: mean, median

bartlett()

numpy.bartlett(M)

Return the Bartlett window.

The Bartlett window is very similar to a triangular window, except
that the end points are at zero.  It is often used in signal
processing for tapering a signal, without generating too much
ripple in the frequency domain.

Parameters
----------
M : int
    Number of points in the output window. If zero or less, an
    empty array is returned.

Returns
-------
out : array
    The triangular window, normalized to one (the value one
    appears only if the number of samples is odd), with the first
    and last samples equal to zero.

See Also
--------
blackman, hamming, hanning, kaiser

Notes
-----
The Bartlett window is defined as

.. math:: w(n) = \frac{2}{M-1} \left(
          \frac{M-1}{2} - \left|n - \frac{M-1}{2}\right|
          \right)

Most references to the Bartlett window come from the signal
processing literature, where it is used as one of many windowing
functions for smoothing values.  Note that convolution with this
window produces linear interpolation.  It is also known as an
apodization (which means"removing the foot", i.e. smoothing
discontinuities at the beginning and end of the sampled signal) or
tapering function. The fourier transform of the Bartlett is the product
of two sinc functions.
Note the excellent discussion in Kanasewich.

References
----------
.. [1] M.S. Bartlett, "Periodogram Analysis and Continuous Spectra",
       Biometrika 37, 1-16, 1950.
.. [2] E.R. Kanasewich, "Time Sequence Analysis in Geophysics",
       The University of Alberta Press, 1975, pp. 109-110.
.. [3] A.V. Oppenheim and R.W. Schafer, "Discrete-Time Signal
       Processing", Prentice-Hall, 1999, pp. 468-471.
.. [4] Wikipedia, "Window function",
       http://en.wikipedia.org/wiki/Window_function
.. [5] W.H. Press,  B.P. Flannery, S.A. Teukolsky, and W.T. Vetterling,
       "Numerical Recipes", Cambridge University Press, 1986, page 429.


Examples
--------
>>> np.bartlett(12)
array([ 0.        ,  0.18181818,  0.36363636,  0.54545455,  0.72727273,
        0.90909091,  0.90909091,  0.72727273,  0.54545455,  0.36363636,
        0.18181818,  0.        ])

Plot the window and its frequency response (requires SciPy and matplotlib):

>>> from numpy import clip, log10, array, bartlett
>>> from numpy.fft import fft
>>> import matplotlib.pyplot as plt

>>> window = bartlett(51)
>>> plt.plot(window)
>>> plt.title("Bartlett window")
>>> plt.ylabel("Amplitude")
>>> plt.xlabel("Sample")
>>> plt.show()

>>> A = fft(window, 2048) / 25.5
>>> mag = abs(fftshift(A))
>>> freq = linspace(-0.5,0.5,len(A))
>>> response = 20*log10(mag)
>>> response = clip(response,-100,100)
>>> plt.plot(freq, response)
>>> plt.title("Frequency response of Bartlett window")
>>> plt.ylabel("Magnitude [dB]")
>>> plt.xlabel("Normalized frequency [cycles per sample]")
>>> plt.axis('tight'); plt.show()

base_repr()

numpy.base_repr(number, base=2, padding=0)

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'

bench()

numpy.bench(self, label='fast', verbose=1, extra_argv=None)

Run benchmarks for module using nose

Parameters
----------
label : {'fast', 'full', '', attribute identifer}
    Identifies the benchmarks to run.  This can be a string to
    pass to the nosetests executable with the '-A' option, or one of
    several special values.
    Special values are:
        'fast' - the default - which corresponds to nosetests -A option
                 of 'not slow'.
        'full' - fast (as above) and slow benchmarks as in the
                 no -A option to nosetests - same as ''
    None or '' - run all benchmarks
    attribute_identifier - string passed directly to nosetests as '-A'
verbose : integer
    verbosity value for test outputs, 1-10
extra_argv : list
    List with any extra args to pass to nosetests

beta()

numpy.random.beta(...)

beta(a, b, size=None)

The Beta distribution over ``[0, 1]``.

The Beta distribution is a special case of the Dirichlet distribution,
and is related to the Gamma distribution.  It has the probability
distribution function

.. math:: f(x; a,b) = \frac{1}{B(\alpha, \beta)} x^{\alpha - 1}
                                                 (1 - x)^{\beta - 1},

where the normalisation, B, is the beta function,

.. math:: B(\alpha, \beta) = \int_0^1 t^{\alpha - 1}
                             (1 - t)^{\beta - 1} dt.

It is often seen in Bayesian inference and order statistics.

Parameters
----------
a : float
    Alpha, non-negative.
b : float
    Beta, non-negative.
size : tuple of ints, optional
    The number of samples to draw.  The ouput is packed according to
    the size given.

Returns
-------
out : ndarray
    Array of the given shape, containing values drawn from a
    Beta distribution.

>>> from numpy import *
>>> from numpy.random import *
>>> beta(a=1,b=10,size=(2,2))                  # Beta distribution alpha=1, beta=10
array([[ 0.02571091,  0.04973536],
[ 0.04887027,  0.02382052]])

See also: seed

binary_repr()

numpy.binary_repr(num, width=None)

Return the binary representation of the input number as a string.

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'

>>> from numpy import *
>>> a = 25
>>> binary_repr(a)                              # binary representation of 25
'11001'
>>> b = float_(pi)                              # numpy float has extra functionality ...
>>> b.nbytes                                    # ... like the number of bytes it takes
8
>>> binary_repr(b.view('u8'))                   # view float number as an 8 byte integer, then get binary bitstring
'1010100010001000010110100011000'

bincount()

numpy.bincount(...)

bincount(x,weights=None)

Return the number of occurrences of each value in x.

x must be a list of non-negative integers.  The output, b[i],
represents the number of times that i is found in x.  If weights
is specified, every occurrence of i at a position p contributes
weights[p] instead of 1.

See also: histogram, digitize, unique.

>>> from numpy import *
>>> a = array([1,1,1,1,2,2,4,4,5,6,6,6])              # doesn't need to be sorted
>>> bincount(a)                                       # 0 occurs 0 times, 1 occurs 4 times, 2 occurs twice, 3 occurs 0 times, ...
array([0, 4, 2, 0, 2, 1, 3])
>>> a = array([5,4,4,2,2])
>>> w = array([0.1, 0.2, 0.1, 0.3, 0.5])
>>> bincount(a)                                      # 0 & 1 don't occur, 2 occurs twice, 3 doesn't occur, 4 occurs twice, 5 once
array([0, 0, 2, 0, 2, 1])
>>> bincount(a, weights=w)
array([ 0. ,  0. ,  0.8,  0. ,  0.3,  0.1])
>>> # 0 occurs 0 times -> result[0] = 0
>>> # 1 occurs 0 times -> result[1] = 0
>>> # 2 occurs at indices 3 & 4 -> result[2] = w[3] + w[4]
>>> # 3 occurs 0 times -> result[3] = 0
>>> # 4 occurs at indices 1 & 2 -> result[4] = w[1] + w[2]
>>> # 5 occurs at index 0  -> result[5] = w[0]

See also: histogram, digitize

binomial()

numpy.random.binomial(...)

binomial(n, p, size=None)

Draw samples from a binomial distribution.

Samples are drawn from a Binomial distribution with specified
parameters, n trials and p probability of success where
n an integer > 0 and p is in the interval [0,1]. (n may be
input as a float, but it is truncated to an integer in use)

Parameters
----------
n : float (but truncated to an integer)
        parameter, > 0.
p : float
        parameter, >= 0 and <=1.
size : {tuple, int}
    Output shape.  If the given shape is, e.g., ``(m, n, k)``, then
    ``m * n * k`` samples are drawn.

Returns
-------
samples : {ndarray, scalar}
          where the values are all integers in  [0, n].

See Also
--------
scipy.stats.distributions.binom : probability density function,
    distribution or cumulative density function, etc.

Notes
-----
The probability density for the Binomial distribution is

.. math:: P(N) = \binom{n}{N}p^N(1-p)^{n-N},

where :math:`n` is the number of trials, :math:`p` is the probability
of success, and :math:`N` is the number of successes.

When estimating the standard error of a proportion in a population by
using a random sample, the normal distribution works well unless the
product p*n <=5, where p = population proportion estimate, and n =
number of samples, in which case the binomial distribution is used
instead. For example, a sample of 15 people shows 4 who are left
handed, and 11 who are right handed. Then p = 4/15 = 27%. 0.27*15 = 4,
so the binomial distribution should be used in this case.

References
----------
.. [1] Dalgaard, Peter, "Introductory Statistics with R",
       Springer-Verlag, 2002.
.. [2] Glantz, Stanton A. "Primer of Biostatistics.", McGraw-Hill,
       Fifth Edition, 2002.
.. [3] Lentner, Marvin, "Elementary Applied Statistics", Bogden
       and Quigley, 1972.
.. [4] Weisstein, Eric W. "Binomial Distribution." From MathWorld--A
       Wolfram Web Resource.
       http://mathworld.wolfram.com/BinomialDistribution.html
.. [5] Wikipedia, "Binomial-distribution",
       http://en.wikipedia.org/wiki/Binomial_distribution

Examples
--------
Draw samples from the distribution:

>>> n, p = 10, .5 # number of trials, probability of each trial
>>> s = np.random.binomial(n, p, 1000)
# result of flipping a coin 10 times, tested 1000 times.

A real world example. A company drills 9 wild-cat oil exploration
wells, each with an estimated probability of success of 0.1. All nine
wells fail. What is the probability of that happening?

Let's do 20,000 trials of the model, and count the number that
generate zero positive results.

>>> sum(np.random.binomial(9,0.1,20000)==0)/20000.
answer = 0.38885, or 38%.

>>> from numpy import *
>>> from numpy.random import *
>>> binomial(n=100,p=0.5,size=(2,3))    # binomial distribution n trials, p= success probability
array([[38, 50, 53],
[56, 48, 54]])
>>> from pylab import *                         # histogram plot example
>>> hist(binomial(100,0.5,(1000)), 20)

See also: random_sample, uniform, standard_normal, seed

bitwise_and()

numpy.bitwise_and(...)

y = bitwise_and(x1,x2)

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\\
          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)

>>> from numpy import *
>>> bitwise_and(array([2,5,255]), array([4,4,4]))
array([0, 4, 4])
>>> bitwise_and(array([2,5,255,2147483647L],dtype=int32), array([4,4,4,2147483647L],dtype=int32))
array([         0,          4,          4, 2147483647])

See also: bitwise_or, bitwise_xor, logical_and

bitwise_not()

numpy.bitwise_not(...)

y = invert(x)

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)

bitwise_or()

numpy.bitwise_or(...)

y = bitwise_or(x1,x2)

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\\
          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),
...               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)

>>> from numpy import *
>>> bitwise_or(array([2,5,255]), array([4,4,4]))
array([  6,   5, 255])
>>> bitwise_or(array([2,5,255,2147483647L],dtype=int32), array([4,4,4,2147483647L],dtype=int32))
array([         6,          5,        255, 2147483647])

See also: bitwise_and, bitwise_xor, logical_or

bitwise_xor()

numpy.bitwise_xor(...)

y = bitwise_xor(x1,x2)

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\\
          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)

>>> from numpy import *
>>> bitwise_xor(array([2,5,255]), array([4,4,4]))
array([  6,   1, 251])
>>> bitwise_xor(array([2,5,255,2147483647L],dtype=int32), array([4,4,4,2147483647L],dtype=int32))
array([  6,   1, 251,   0])

See also: bitwise_and, bitwise_or, logical_xor

blackman()

numpy.blackman(M)

Return the Blackman window.

The Blackman window is a taper formed by using the the first
three terms of a summation of cosines. It was designed to have close
to the minimal leakage possible.
It is close to optimal, only slightly worse than a Kaiser window.

Parameters
----------
M : int
    Number of points in the output window. If zero or less, an
    empty array is returned.

Returns
-------
out : array
    The window, normalized to one (the value one
    appears only if the number of samples is odd).

See Also
--------
bartlett, hamming, hanning, kaiser

Notes
-----
The Blackman window is defined as

.. math::  w(n) = 0.42 - 0.5 \cos(2\pi n/M) + 0.08 \cos(4\pi n/M)


Most references to the Blackman window come from the signal processing
literature, where it is used as one of many windowing functions for
smoothing values.  It is also known as an apodization (which means
"removing the foot", i.e. smoothing discontinuities at the beginning
and end of the sampled signal) or tapering function. It is known as a
"near optimal" tapering function, almost as good (by some measures)
as the kaiser window.

References
----------
.. [1] Blackman, R.B. and Tukey, J.W., (1958) The measurement of power
       spectra, Dover Publications, New York.
.. [2] Wikipedia, "Window function",
       http://en.wikipedia.org/wiki/Window_function
.. [3] Oppenheim, A.V., and R.W. Schafer. Discrete-Time Signal Processing.
       Upper Saddle River, NJ: Prentice-Hall, 1999, pp. 468-471.

Examples
--------
>>> from numpy import blackman
>>> blackman(12)
array([ -1.38777878e-17,   3.26064346e-02,   1.59903635e-01,
         4.14397981e-01,   7.36045180e-01,   9.67046769e-01,
         9.67046769e-01,   7.36045180e-01,   4.14397981e-01,
         1.59903635e-01,   3.26064346e-02,  -1.38777878e-17])


Plot the window and the frequency response:

>>> from numpy import clip, log10, array, bartlett
>>> from scipy.fftpack import fft, fftshift
>>> import matplotlib.pyplot as plt

>>> window = blackman(51)
>>> plt.plot(window)
>>> plt.title("Blackman window")
>>> plt.ylabel("Amplitude")
>>> plt.xlabel("Sample")
>>> plt.show()

>>> A = fft(window, 2048) / 25.5
>>> mag = abs(fftshift(A))
>>> freq = linspace(-0.5,0.5,len(A))
>>> response = 20*log10(mag)
>>> response = clip(response,-100,100)
>>> plt.plot(freq, response)
>>> plt.title("Frequency response of Bartlett window")
>>> plt.ylabel("Magnitude [dB]")
>>> plt.xlabel("Normalized frequency [cycles per sample]")
>>> plt.axis('tight'); plt.show()

bmat()

numpy.bmat(obj, ldict=None, gdict=None)

Build a matrix object from a string, nested sequence, or array.

Parameters
----------
obj : string, sequence or array
    Input data.  Variables names in the current scope may
    be referenced, even if `obj` is a string.

Returns
-------
out : matrix
    Returns a matrix object, which is a specialized 2-D array.

See Also
--------
matrix

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]])

>>> from numpy import *
>>> a = mat('1 2; 3 4')
>>> b = mat('5 6; 7 8')
>>> bmat('a b; b a')       # all elements must be existing symbols
matrix([[1, 2, 5, 6],
[3, 4, 7, 8],
[5, 6, 1, 2],
[7, 8, 3, 4]])

See also: mat

broadcast()

numpy.broadcast(...)

>>> from numpy import *
>>> a = array([[1,2],[3,4]])
>>> b = array([5,6])
>>> c = broadcast(a,b)
>>> c.nd                                     # the number of dimensions in the broadcasted result
2
>>> c.shape                                  # the shape of the broadcasted result
(2, 2)
>>> c.size                                   # total size of the broadcasted result
4
>>> for value in c: print value
...
(1, 5)
(2, 6)
(3, 5)
(4, 6)
>>> c.reset()                                # reset the iterator to the beginning
>>> c.next()                                 # next element
(1, 5)

See also: ndenumerate, ndindex, flat

broadcast_arrays()

numpy.broadcast_arrays(*args)

Broadcast any number of arrays against each other.

Parameters
----------
`*args` : arrays
    The arrays to broadcast.

Returns
-------
broadcasted : list of arrays
    These arrays are views on the original arrays. They are typically not
    contiguous. Furthermore, more than one element of a broadcasted array
    may refer to a single memory location. If you need to write to the
    arrays, make copies first.

Examples
--------
>>> x = np.array([[1,2,3]])
>>> y = np.array([[1],[2],[3]])
>>> np.broadcast_arrays(x, y)
[array([[1, 2, 3],
       [1, 2, 3],
       [1, 2, 3]]), array([[1, 1, 1],
       [2, 2, 2],
       [3, 3, 3]])]

Here is a useful idiom for getting contiguous copies instead of
non-contiguous views.

>>> map(np.array, np.broadcast_arrays(x, y))
[array([[1, 2, 3],
       [1, 2, 3],
       [1, 2, 3]]), array([[1, 1, 1],
       [2, 2, 2],
       [3, 3, 3]])]
</