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]
array([[ 0, 2],
[ 4, 6],
[ 8, 10]])
>>> 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]
0
>>> a[-1]
array([30, 31, 32, 33, 34])
>>> a[1:3,1:4]
array([[11, 12, 13],
[21, 22, 23]])
>>>
>>> i = array([0,1,2,1])
>>> j = array([1,2,3,4])
>>> a[i,j]
array([ 1, 12, 23, 14])
>>>
>>> a[a<13]
array([ 0, 1, 2, 3, 4, 10, 11, 12])
>>>
>>> b1 = array( [True,False,True,False] )
>>> a[b1,:]
array([[ 0, 1, 2, 3, 4],
[20, 21, 22, 23, 24]])
>>>
>>> b2 = array( [False,True,True,False,True] )
>>> 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
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.]))
array([ 1., 3., 6., 10.])
>>> array([1., 1.+2., (1.+2.)+3., ((1.+2.)+3.)+4.])
array([ 1., 3., 6., 10.])
>>> multiply.accumulate(array([1.,2.,3.,4.]))
array([ 1., 2., 6., 24.])
>>> array([1., 1.*2., (1.*2.)*3., ((1.*2.)*3.)*4.])
array([ 1., 2., 6., 24.])
>>> add.accumulate(array([[1,2,3],[4,5,6]]), axis = 0)
array([[1, 2, 3],
[5, 7, 9]])
>>> add.accumulate(array([[1,2,3],[4,5,6]]), axis = 1)
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()
False
>>> all(a)
False
>>> a = array([1,2,3])
>>> all(a > 0)
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)
0.78539816339744828
>>> angle(1+1j,deg=True)
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()
True
>>> any(a)
True
>>> a = array([1,2,3])
>>> (a >= 1).any()
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):
... return (a[0]+a[-1])/2
...
>>> b = array([[1,2,3],[4,5,6],[7,8,9]])
>>> apply_along_axis(myfunc,0,b)
array([4, 5, 6])
>>> apply_along_axis(myfunc,1,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
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])
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)
array([3, 4, 5, 6, 7, 8, 9])
>>> arange(3,10,2)
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)
array([1, 0, 1])
>>> a.argmax(axis=1)
array([1, 0])
>>> argmax(a)
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)
array([0, 1, 0])
>>> a.argmin(axis=1)
array([0, 1])
>>> argmin(a)
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()
>>> ind
array([1, 4, 0, 3, 2])
>>> a[ind]
array([0, 1, 2, 4, 8])
>>> ind = a.argsort(kind='merge')
>>> a = array([[8,4,1],[2,0,9]])
>>> ind = a.argsort(axis=0)
>>> ind
array([[1, 1, 0],
[0, 0, 1]])
>>> a[ind,[[0,1,2],[0,1,2]]]
array([[2, 0, 1],
[8, 4, 9]])
>>> ind = a.argsort(axis=1)
>>> ind
array([[2, 1, 0],
[1, 0, 2]])
>>> a = ones(17)
>>> a.argsort()
array([ 0, 14, 13, 12, 11, 10, 9, 15, 8, 6, 5, 4, 3, 2, 1, 7, 16])
>>> a.argsort(kind="mergesort")
array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16])
>>> ind = argsort(a)
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])
array([1, 2, 3])
>>> array([1,2,3], dtype=complex)
array([ 1.+0.j, 2.+0.j, 3.+0.j])
>>> array(1, copy=0, subok=1, ndmin=1)
array([1])
>>> array(1, copy=0, subok=1, ndmin=2)
array([[1]])
>>> array(1, subok=1, ndmin=2)
array([[1]])
>>> mydescriptor = {'names': ('gender','age','weight'), 'formats': ('S1', 'f4', 'f4')}
>>> a = array([('M',64.0,75.0),('F',25.0,60.0)], dtype=mydescriptor)
>>> print a
[('M', 64.0, 75.0) ('F', 25.0, 60.0)]
>>> a['weight']
array([ 75., 60.], dtype=float32)
>>> a.dtype.names
('gender','age','weight')
>>> mydescriptor = [('age',int16),('Nchildren',int8),('weight',float32)]
>>> 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', [('i', 'i2'),('j','i2')])])
>>> array([(1.0, 2.0, (1,2))], dtype=mydescriptor)
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)
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)
>>> a['x']
array([ 1. , 2.0999999], dtype=float32)
>>> a['nested']
array([(1, 2), (3, 2)],
dtype=[('i', '<i2'), ('j', '<i2')])
>>> a['nested']['i']
>>> mydescriptor = dtype([('x', 'f4'),('y', 'f4'),
... ('nested', [('i', 'i2'),('j','i2')])])
>>> array([(1.0, 2.0, (1,2))], dtype=mydescriptor)
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)
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)
>>> a['x']
array([ 1. , 2.0999999], dtype=float32)
>>> a['nested']
array([(1, 2), (3, 2)],
dtype=[('i', '<i2'), ('j', '<i2')])
>>> a['nested']['i']
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)
[array([[1, 2, 3, 4]]), array([[5, 6, 7, 8]])]
>>> array_split(a,4,axis=1)
[array([[1],
[5]]), array([[2],
[6]]), array([[3],
[7]]), array([[4],
[8]])]
>>> array_split(a,3,axis=1)
[array([[1, 2],
[5, 6]]), array([[3],
[7]]), array([[4],
[8]])]
>>> array_split(a,[2,3],axis=1)
[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)
array([[1, 2],
[5, 8]])
>>> asanyarray(m)
matrix([[1, 2],
[5, 8]])
>>> asanyarray([1,2,3])
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
array([[1, 2],
[5, 8]])
>>> m[0,0] = -99
>>> m
matrix([[-99, 2],
[ 5, 8]])
>>> a
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
matrix([[1, 2],
[5, 8]])
>>> a[0,0] = -99
>>> a
array([[-99, 2],
[ 5, 8]])
>>> m
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)
>>> type(y[0])
<type 'numpy.float64'>
>>> x.astype(None)
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
>>> b = array([2,3])
>>> c = array([[4,5],[6,7]])
>>> d = arange(8).reshape(2,2,2)
>>> d
array([[[0, 1],
[2, 3]],
[[4, 5],
[6, 7]]])
>>> atleast_1d(a,b,c,d)
[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
>>> b = array([2,3])
>>> c = array([[4,5],[6,7]])
>>> d = arange(8).reshape(2,2,2)
>>> d
array([[[0, 1],
[2, 3]],
[[4, 5],
[6, 7]]])
>>> atleast_2d(a,b,c,d)
[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
>>> b = array([2,3])
>>> c = array([[4,5],[6,7]])
>>> d = arange(8).reshape(2,2,2)
>>> d
array([[[0, 1],
[2, 3]],
[[4, 5],
[6, 7]]])
>>> atleast_3d(a,b,c,d)
[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])
>>> average(a)
3.0
>>> average(a,weights=w)
3.1666666666666665
>>> average(a,weights=w,returned=True)
(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))
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)
'11001'
>>> b = float_(pi)
>>> b.nbytes
8
>>> binary_repr(b.view('u8'))
'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])
>>> bincount(a)
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)
array([0, 0, 2, 0, 2, 1])
>>> bincount(a, weights=w)
array([ 0. , 0. , 0.8, 0. , 0.3, 0.1])
>>>
>>>
>>>
>>>
>>>
>>>
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))
array([[38, 50, 53],
[56, 48, 54]])
>>> from pylab import *
>>> 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')
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
2
>>> c.shape
(2, 2)
>>> c.size
4
>>> for value in c: print value
...
(1, 5)
(2, 6)
(3, 5)
(4, 6)
>>> c.reset()
>>> c.next()
(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]])]
byte_bounds()
numpy.byte_bounds(a)
(low, high) are pointers to the end-points of an array
low is the first byte
high is just *past* the last byte
If the array is not single-segment, then it may not actually
use every byte between these bounds.
The array provided must conform to the Python-side of the array interface
bytes()
numpy.random.bytes(...)
bytes(length)
Return random bytes.
Parameters
----------
length : int
Number of random bytes.
Returns
-------
out : str
String of length `N`.
Examples
--------
>>> np.random.bytes(10)
' eh\x85\x022SZ\xbf\xa4' #random
>>> from numpy import *
>>> from numpy.random import bytes
>>> print repr(bytes(5))
'o\x07\x9f\xdf\xdf'
>>> print repr(bytes(5))
'\x98\xc9KD\xe0'
See also: shuffle, permutation, seed
byteswap()
ndarray.byteswap(...)
a.byteswap(inplace)
Swap the bytes of the array elements
Toggle between low-endian and big-endian data representation by
returning a byteswapped array, optionally swapped in-place.
Parameters
----------
inplace: bool, optional
If ``True``, swap bytes in-place, default is ``False``.
Returns
-------
out: ndarray
The byteswapped array. If `inplace` is ``True``, this is
a view to self.
Examples
--------
>>> A = np.array([1, 256, 8755], dtype=np.int16)
>>> map(hex, A)
['0x1', '0x100', '0x2233']
>>> A.byteswap(True)
array([ 256, 1, 13090], dtype=int16)
>>> map(hex, A)
['0x100', '0x1', '0x3322']
Arrays of strings are not swapped
>>> A = np.array(['ceg', 'fac'])
>>> A.byteswap()
array(['ceg', 'fac'],
dtype='|S3')
c_
numpy.c_
Translates slice objects to concatenation along the second axis.
For example:
>>> np.c_[np.array([[1,2,3]]), 0, 0, np.array([[4,5,6]])]
array([1, 2, 3, 0, 0, 4, 5, 6])
>>> from numpy import *
>>> c_[1:5]
array([1, 2, 3, 4])
>>> c_[1:5,2:6]
array([[1, 2],
[2, 3],
[3, 4],
[4, 5]])
>>> a = array([[1,2,3],[4,5,6]])
>>> c_[a,a]
array([[1, 2, 3, 1, 2, 3],
[4, 5, 6, 4, 5, 6]])
>>> c_['0',a,a]
array([[1, 2, 3],
[4, 5, 6],
[1, 2, 3],
[4, 5, 6]])
See also: r_, hstack, vstack, column_stack, concatenate, bmat, s_
cast[]()
>>> from numpy import *
>>> x = arange(3)
>>> x.dtype
dtype('int32')
>>> cast['int64'](x)
array([0, 1, 2], dtype=int64)
>>> cast['uint'](x)
array([0, 1, 2], dtype=uint32)
>>> cast[float128](x)
array([0.0, 1.0, 2.0], dtype=float128)
>>> cast.keys()
<snip>
See also: astype, typeDict
can_cast()
numpy.can_cast(...)
can_cast(from=d1, to=d2)
Returns True if cast between data types can occur without losing precision.
Parameters
----------
from: data type code
Data type code to cast from.
to: data type code
Data type code to cast to.
Returns
-------
out : bool
True if cast can occur without losing precision.
ceil()
numpy.ceil(...)
y = ceil(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.])
>>> from numpy import *
>>> a = array([-1.7, -1.5, -0.2, 0.2, 1.5, 1.7])
>>> ceil(a)
array([-1., -1., -0., 1., 2., 2.])
See also: floor, round_, fix, astype
choose()
numpy.choose(a, choices, out=None, mode='raise')
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
value in `a` is i, then the new array will have the value that
choices[i] contains in the same place.
Parameters
----------
a : int array
This array must contain integers in [0, n-1], where n is the number
of choices.
choices : sequence of arrays
Choice arrays. The index array and all of the choices should be
broadcastable to the same shape.
out : array, optional
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
Returns
-------
merged_array : array
The merged results.
See Also
--------
ndarray.choose : equivalent method
Examples
--------
>>> choices = [[0, 1, 2, 3], [10, 11, 12, 13],
... [20, 21, 22, 23], [30, 31, 32, 33]]
>>> np.choose([2, 3, 1, 0], choices)
array([20, 31, 12, 3])
>>> np.choose([2, 4, 1, 0], choices, mode='clip')
array([20, 31, 12, 3])
>>> np.choose([2, 4, 1, 0], choices, mode='wrap')
array([20, 1, 12, 3])
ndarray.choose(...)
a.choose(choices, out=None, mode='raise')
Use an index array to construct a new array from a set of choices.
Refer to `numpy.choose` for full documentation.
See Also
--------
numpy.choose : equivalent function
>>> from numpy import *
>>> choice0 =array([10,12,14,16])
>>> choice1 =array([20,22,24,26])
>>> choice2 =array([30,32,34,36])
>>> selector = array([0,0,2,1])
>>> selector.choose(choice0,choice1,choice2)
array([10, 12, 34, 26])
>>> a = arange(4)
>>> choose(a >= 2, (choice0, choice1))
array([10, 12, 24, 26])
See also: compress, take, where, select
clip()
numpy.clip(a, a_min, a_max, out=None)
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
Array containing elements to clip.
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 : 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
--------
>>> a = np.arange(10)
>>> np.clip(a, 1, 8)
array([1, 1, 2, 3, 4, 5, 6, 7, 8, 8])
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> np.clip(a, 3, 6, out=a)
array([3, 3, 3, 3, 4, 5, 6, 6, 6, 6])
>>> a
array([3, 3, 3, 3, 4, 5, 6, 6, 6, 6])
>>> a = np.arange(10)
>>> 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])
ndarray.clip(...)
a.clip(a_min, a_max, out=None)
Return an array whose values are limited to ``[a_min, a_max]``.
Refer to `numpy.clip` for full documentation.
See Also
--------
numpy.clip : equivalent function
>>> from numpy import *
>>> a = array([5,15,25,3,13])
>>> a.clip(min=10,max=20)
array([10, 15, 20, 10, 13])
>>> clip(a,10,20)
See also: where compress
column_stack()
numpy.column_stack(tup)
Stack 1-D arrays as columns into a 2-D array
Take a sequence of 1-D arrays and stack them as columns
to make a single 2-D array. 2-D arrays are stacked as-is,
just like with hstack. 1-D arrays are turned into 2-D columns
first.
Parameters
----------
tup : sequence of 1-D or 2-D arrays.
Arrays to stack. All of them must have the same first dimension.
Examples
--------
>>> a = np.array((1,2,3))
>>> b = np.array((2,3,4))
>>> np.column_stack((a,b))
array([[1, 2],
[2, 3],
[3, 4]])
>>> from numpy import *
>>> a = array([1,2])
>>> b = array([3,4])
>>> c = array([5,6])
>>> column_stack((a,b,c))
array([[1, 3, 5],
[2, 4, 6]])
See also: concatenate, dstack, hstack, vstack, c_
common_type()
numpy.common_type(*arrays)
Return the inexact scalar type which is most common in a list of arrays.
The return type will always be an inexact scalar type, even if all the
arrays are integer arrays
Parameters
----------
array1, array2, ... : ndarray
Input arrays.
Returns
-------
out : data type code
Data type code.
See Also
--------
dtype
Examples
--------
>>> np.common_type(np.arange(4), np.array([45,6]), np.array([45.0, 6.0]))
<type 'numpy.float64'>
compare_chararrays()
numpy.compare_chararrays(...)
compress()
numpy.compress(condition, a, axis=None, out=None)
Return selected slices of an array along given axis.
Parameters
----------
condition : array_like
Boolean 1-D array selecting which entries to return. If len(condition)
is less than the size of `a` along the given axis, then output is
truncated to the length of the condition array.
a : array_like
Array from which to extract a part.
axis : int, optional
Axis along which to take slices. If None (default), work on the
flattened array.
out : ndarray, optional
Output array. Its type is preserved and it must be of the right
shape to hold the output.
Returns
-------
compressed_array : ndarray
A copy of `a` without the slices along axis for which `condition`
is false.
See Also
--------
ndarray.compress: Equivalent method.
Examples
--------
>>> a = np.array([[1, 2], [3, 4]])
>>> np.compress([0, 1], a, axis=0)
array([[3, 4]])
>>> np.compress([1], a, axis=1)
array([[1],
[3]])
>>> np.compress([0,1,1], a)
array([2, 3])
ndarray.compress(...)
a.compress(condition, axis=None, out=None)
Return selected slices of this array along given axis.
Refer to `numpy.compress` for full documentation.
See Also
--------
numpy.compress : equivalent function
>>> from numpy import *
>>> a = array([10, 20, 30, 40])
>>> condition = (a > 15) & (a < 35)
>>> condition
array([False, True, True, False], dtype=bool)
>>> a.compress(condition)
array([20, 30])
>>> a[condition]
array([20, 30])
>>> compress(a >= 30, a)
array([30, 40])
>>> b = array([[10,20,30],[40,50,60]])
>>> b.compress(b.ravel() >= 22)
array([30, 40, 50, 60])
>>> x = array([3,1,2])
>>> y = array([50, 101])
>>> b.compress(x >= 2, axis=1)
array([[10, 30],
[40, 60]])
>>> b.compress(y >= 100, axis=0)
array([[40, 50, 60]])
See also: choose, take, where, trim_zeros, unique, unique1d
concatenate()
numpy.concatenate(...)
concatenate((a1, a2, ...), axis=0)
Join a sequence of arrays together.
Parameters
----------
a1, a2, ... : sequence of ndarrays
The arrays must have the same shape, except in the dimension
corresponding to `axis` (the first, by default).
axis : int, optional
The axis along which the arrays will be joined. Default is 0.
Returns
-------
res : ndarray
The concatenated array.
See Also
--------
array_split : Split an array into multiple sub-arrays of equal or
near-equal size.
split : Split array into a list of multiple sub-arrays of equal size.
hsplit : Split array into multiple sub-arrays horizontally (column wise)
vsplit : Split array into multiple sub-arrays vertically (row wise)
dsplit : Split array into multiple sub-arrays along the 3rd axis (depth).
hstack : Stack arrays in sequence horizontally (column wise)
vstack : Stack arrays in sequence vertically (row wise)
dstack : Stack arrays in sequence depth wise (along third dimension)
Examples
--------
>>> a = np.array([[1, 2], [3, 4]])
>>> b = np.array([[5, 6]])
>>> np.concatenate((a, b), axis=0)
array([[1, 2],
[3, 4],
[5, 6]])
>>> from numpy import *
>>> x = array([[1,2],[3,4]])
>>> y = array([[5,6],[7,8]])
>>> concatenate((x,y))
array([[1, 2],
[3, 4],
[5, 6],
[7, 8]])
>>> concatenate((x,y),axis=1)
array([[1, 2, 5, 6],
[3, 4, 7, 8]])
See also: append, column_stack, dstack, hstack, vstack, array_split
conj()
numpy.conj(...)
y = conjugate(x)
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
The complex conjugate of `x`, with same dtype as `y`.
Examples
--------
>>> np.conjugate(1+2j)
(1-2j)
ndarray.conj(...)
a.conj()
Return an array with all complex-valued elements conjugated.
Synonym for conjugate()
See conjugate()
conjugate()
numpy.conjugate(...)
y = conjugate(x)
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
The complex conjugate of `x`, with same dtype as `y`.
Examples
--------
>>> np.conjugate(1+2j)
(1-2j)
ndarray.conjugate(...)
a.conjugate()
Return an array with all complex-valued elements conjugated.
>>> a = array([1+2j,3-4j])
>>> a.conj()
array([ 1.-2.j, 3.+4.j])
>>> a.conjugate()
array([ 1.-2.j, 3.+4.j])
>>> conj(a)
>>> conjugate(a)
See also: vdot
convolve()
numpy.convolve(a, v, mode='full')
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])
copy()
numpy.copy(a)
Return an array copy of the given object.
Parameters
----------
a : array_like
Input data.
Returns
-------
arr : ndarray
Array interpretation of `a`.
Notes
-----
This is equivalent to
>>> np.array(a, copy=True)
Examples
--------
Create an array x, with a reference y and a copy z:
>>> x = np.array([1, 2, 3])
>>> y = x
>>> z = np.copy(x)
Note that, when we modify x, y changes, but not z:
>>> x[0] = 10
>>> x[0] == y[0]
True
>>> x[0] == z[0]
False
ndarray.copy(...)
a.copy(order='C')
Return a copy of the array.
Parameters
----------
order : {'C', 'F', 'A'}, optional
By default, the result is stored in C-contiguous (row-major) order in
memory. If `order` is `F`, the result has 'Fortran' (column-major)
order. If order is 'A' ('Any'), then the result has the same order
as the input.
Examples
--------
>>> x = np.array([[1,2,3],[4,5,6]], order='F')
>>> y = x.copy()
>>> x.fill(0)
>>> x
array([[0, 0, 0],
[0, 0, 0]])
>>> y
array([[1, 2, 3],
[4, 5, 6]])
>>> y.flags['C_CONTIGUOUS']
True
>>> from numpy import *
>>> a = array([1,2,3])
>>> a
array([1, 2, 3])
>>> b = a
>>> b[1] = 4
>>> a
array([1, 4, 3])
>>> a = array([1,2,3])
>>> b = a.copy()
>>> b[1] = 4
>>> a
array([1, 2, 3])
>>> b
array([1, 4, 3])
See also: view
corrcoef()
numpy.corrcoef(x, y=None, rowvar=1, bias=0)
Return correlation coefficients.
Please refer to the documentation for `cov` for more detail. The
relationship between the correlation coefficient matrix, P, and the
covariance matrix, C, is
.. math:: P_{ij} = \frac{ C_{ij} } { \sqrt{ C_{ii} * C_{jj} } }
The values of P are between -1 and 1.
See Also
--------
cov : Covariance matrix
>>> from numpy import *
>>> T = array([1.3, 4.5, 2.8, 3.9])
>>> P = array([2.7, 8.7, 4.7, 8.2])
>>> print corrcoef([T,P])
[[ 1. 0.98062258]
[ 0.98062258 1. ]]
>>> rho = array([8.5, 5.2, 6.9, 6.5])
>>> data = column_stack([T,P,rho])
>>> print corrcoef([T,P,rho])
[[ 1. 0.98062258 -0.97090288]
[ 0.98062258 1. -0.91538464]
[-0.97090288 -0.91538464 1. ]]
See also: cov, var
correlate()
numpy.correlate(a, v, mode='valid')
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.
cos()
numpy.cos(...)
y = cos(x)
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])
>>> cos(array([0, pi/2, pi]))
array([ 1.00000000e+00, 6.12303177e-17, -1.00000000e+00])
cosh()
numpy.cosh(...)
y = cosh(x)
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()
cov()
numpy.cov(m, y=None, rowvar=1, bias=0)
Estimate a covariance matrix, given data.
Covariance indicates the level to which two variables vary together.
If we examine N-dimensional samples, :math:`X = [x_1, x_2, ... x_N]^T`,
then the covariance matrix element :math:`C_{ij}` is the covariance of
:math:`x_i` and :math:`x_j`. The element :math:`C_{ii}` is the variance
of :math:`x_i`.
Parameters
----------
m : array_like
A 1-D or 2-D array containing multiple variables and observations.
Each row of `m` represents a variable, and each column a single
observation of all those variables. Also see `rowvar` below.
y : array_like, optional
An additional set of variables and observations. `y` has the same
form as that of `m`.
rowvar : int, optional
If `rowvar` is non-zero (default), then each row represents a
variable, with observations in the columns. Otherwise, the relationship
is transposed: each column represents a variable, while the rows
contain observations.
bias : int, optional
Default normalization is by ``(N-1)``, where ``N`` is the number of
observations given (unbiased estimate). If `bias` is 1, then
normalization is by ``N``.
Returns
-------
out : ndarray
The covariance matrix of the variables.
See Also
--------
corrcoef : Normalized covariance matrix
Examples
--------
Consider two variables, :math:`x_0` and :math:`x_1`, which
correlate perfectly, but in opposite directions:
>>> x = np.array([[0, 2], [1, 1], [2, 0]]).T
>>> x
array([[0, 1, 2],
[2, 1, 0]])
Note how :math:`x_0` increases while :math:`x_1` decreases. The covariance
matrix shows this clearly:
>>> np.cov(x)
array([[ 1., -1.],
[-1., 1.]])
Note that element :math:`C_{0,1}`, which shows the correlation between
:math:`x_0` and :math:`x_1`, is negative.
Further, note how `x` and `y` are combined:
>>> x = [-2.1, -1, 4.3]
>>> y = [3, 1.1, 0.12]
>>> X = np.vstack((x,y))
>>> print np.cov(X)
[[ 11.71 -4.286 ]
[ -4.286 2.14413333]]
>>> print np.cov(x, y)
[[ 11.71 -4.286 ]
[ -4.286 2.14413333]]
>>> print np.cov(x)
11.71
>>> from numpy import *
>>> x = array([1., 3., 8., 9.])
>>> variance = cov(x)
>>> variance = cov(x, bias=1)
>>> T = array([1.3, 4.5, 2.8, 3.9])
>>> P = array([2.7, 8.7, 4.7, 8.2])
>>> cov(T,P)
3.9541666666666657
>>> rho = array([8.5, 5.2, 6.9, 6.5])
>>> data = column_stack([T,P,rho])
>>> print cov(data)
[[ 1.97583333 3.95416667 -1.85583333]
[ 3.95416667 8.22916667 -3.57083333]
[-1.85583333 -3.57083333 1.84916667]]
See also: corrcoef, std, var
cross()
numpy.cross(a, b, axisa=-1, axisb=-1, axisc=-1, axis=None)
Return the cross product of two (arrays of) vectors.
The cross product is performed over the last axis of a and b by default,
and can handle axes with dimensions 2 and 3. For a dimension of 2,
the z-component of the equivalent three-dimensional cross product is
returned.
>>> from numpy import *
>>> x = array([1,2,3])
>>> y = array([4,5,6])
>>> cross(x,y)
array([-3, 6, -3])
See also: inner, ix_, outer
cumprod()
numpy.cumprod(a, axis=None, dtype=None, out=None)
Return the cumulative product of elements along a given axis.
Parameters
----------
a : array_like
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 of the resulting values will be cast if necessary.
Returns
-------
cumprod : ndarray
A new array holding the result is returned unless `out` is
specified, in which case a reference to out is returned.
Notes
-----
Arithmetic is modular when using integer types, and no error is
raised on overflow.
Examples
--------
>>> a = np.array([1,2,3])
>>> np.cumprod(a) # intermediate results 1, 1*2
... # 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
array([ 1., 2., 6., 24., 120., 720.])
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]])
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]])
ndarray.cumprod(...)
a.cumprod(axis=None, dtype=None, out=None)
Return the cumulative product of the elements along the given axis.
Refer to `numpy.cumprod` for full documentation.
See Also
--------
numpy.cumprod : equivalent function
>>> from numpy import *
>>> a = array([1,2,3])
>>> a.cumprod()
array([1, 2, 6])
>>> cumprod(a)
array([1, 2, 6])
>>> a = array([[1,2,3],[4,5,6]])
>>> a.cumprod(dtype=float)
array([1., 2., 6., 24., 120., 720.])
>>> a.cumprod(axis=0)
array([[ 1, 2, 3],
[ 4, 10, 18]])
>>> a.cumprod(axis=1)
array([[ 1, 2, 6],
[ 4, 20, 120]])
See also: accumulate, prod, cumsum
cumproduct()
numpy.cumproduct(a, axis=None, dtype=None, out=None)
Return the cumulative product over the given axis.
See Also
--------
cumprod : equivalent function; see for details.
cumsum()
numpy.cumsum(a, axis=None, dtype=None, out=None)
Return the cumulative sum of the elements along a given axis.
Parameters
----------
a : array_like
Input array or object that can be converted to an array.
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
precision less than that of the default platform integer. In
that case, the default platform integer is used.
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.
Returns
-------
cumsum : ndarray.
A new array holding the result is returned unless `out` is
specified, in which case a reference to `out` is returned.
Notes
-----
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)
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.])
>>> np.cumsum(a,axis=0) # sum over rows for each of the 3 columns
array([[1, 2, 3],
[5, 7, 9]])
>>> np.cumsum(a,axis=1) # sum over columns for each of the 2 rows
array([[ 1, 3, 6],
[ 4, 9, 15]])
ndarray.cumsum(...)
a.cumsum(axis=None, dtype=None, out=None)
Return the cumulative sum of the elements along the given axis.
Refer to `numpy.cumsum` for full documentation.
See Also
--------
numpy.cumsum : equivalent function
>>> from numpy import *
>>> a = array([1,2,3])
>>> a.cumsum()
array([1, 3, 6])
>>> cumsum(a)
array([1, 3, 6])
>>> a = array([[1,2,3],[4,5,6]])
>>> a.cumsum(dtype=float)
array([ 1., 3., 6., 10., 15., 21.])
>>> a.cumsum(axis=0)
array([[1, 2, 3],
[5, 7, 9]])
>>> a.cumsum(axis=1)
array([[ 1, 3, 6],
[ 4, 9, 15]])
See also: accumulate, sum, cumprod
degrees()
numpy.degrees(...)
y = degrees(x)
Convert angles from radians to degrees.
Parameters
----------
x : array_like
Angle in radians.
Returns
-------
y : ndarray
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
delete()
numpy.delete(arr, obj, axis=None)
Return a new array with sub-arrays along an axis deleted.
Parameters
----------
arr : array_like
Input array.
obj : slice, integer or an array of integers
Indicate which sub-arrays to remove.
axis : integer, optional
The axis along which to delete the subarray defined by `obj`.
If `axis` is None, `obj` is applied to the flattened array.
See Also
--------
insert : Insert values into an array.
append : Append values at the end of an array.
Examples
--------
>>> arr = np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12]])
>>> arr
array([[ 1, 2, 3, 4],
[ 5, 6, 7, 8],
[ 9, 10, 11, 12]])
>>> np.delete(arr, 1, 0)
array([[ 1, 2, 3, 4],
[ 9, 10, 11, 12]])
>>> np.delete(arr, np.s_[::2], 1)
array([[ 2, 4],
[ 6, 8],
[10, 12]])
>>> np.delete(arr, [1,3,5], None)
array([ 1, 3, 5, 7, 8, 9, 10, 11, 12])
>>> from numpy import *
>>> a = array([0, 10, 20, 30, 40])
>>> delete(a, [2,4])
array([ 0, 10, 30])
>>> a = arange(16).reshape(4,4)
>>> a
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11],
[12, 13, 14, 15]])
>>> delete(a, s_[1:3], axis=0)
array([[ 0, 1, 2, 3],
[12, 13, 14, 15]])
>>> delete(a, s_[1:3], axis=1)
array([[ 0, 3],
[ 4, 7],
[ 8, 11],
[12, 15]])
See also: append, insert
deprecate()
numpy.deprecate(func, oldname=None, newname=None)
Deprecate old functions.
Issues a DeprecationWarning, adds warning to oldname's docstring,
rebinds oldname.__name__ and returns new function object.
Example:
oldfunc = deprecate(newfunc, 'oldfunc', 'newfunc')
deprecate_with_doc()
numpy.deprecate_with_doc(somestr)
Decorator to deprecate functions and provide detailed documentation
with 'somestr' that is added to the functions docstring.
Example:
depmsg = 'function scipy.foo has been merged into numpy.foobar'
@deprecate_with_doc(depmsg)
def foo():
pass
diag()
numpy.diag(v, k=0)
Extract a diagonal or construct a diagonal array.
Parameters
----------
v : array_like
If `v` is a 2-dimensional array, return a copy of
its `k`-th diagonal. If `v` is a 1-dimensional array,
return a 2-dimensional array with `v` on the `k`-th diagonal.
k : int, optional
Diagonal in question. The defaults is 0.
Examples
--------
>>> x = np.arange(9).reshape((3,3))
>>> x
array([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]])
>>> np.diag(x)
array([0, 4, 8])
>>> np.diag(np.diag(x))
array([[0, 0, 0],
[0, 4, 0],
[0, 0, 8]])
>>> from numpy import *
>>> a = arange(12).reshape(4,3)
>>> print a
[[ 0 1 2]
[ 3 4 5]
[ 6 7 8]
[ 9 10 11]]
>>> print diag(a,k=0)
[0 4 8]
>>> print diag(a,k=1)
[1 5]
>>> print diag(array([1,4,5]),k=0)
[[1 0 0]
[0 4 0]
[0 0 5]]
>>> print diag(array([1,4,5]),k=1)
[[0 1 0 0]
[0 0 4 0]
[0 0 0 5]
[0 0 0 0]]
See also: diagonal, diagflat, trace
diagflat()
numpy.diagflat(v, k=0)
Create a 2-dimensional array with the flattened input as a diagonal.
Parameters
----------
v : array_like
Input data, which is flattened and set as the `k`-th
diagonal of the output.
k : int, optional
Diagonal to set. The default is 0.
Examples
--------
>>> np.diagflat([[1,2],[3,4]])
array([[1, 0, 0, 0],
[0, 2, 0, 0],
[0, 0, 3, 0],
[0, 0, 0, 4]])
>>> np.diagflat([1,2], 1)
array([[0, 1, 0],
[0, 0, 2],
[0, 0, 0]])
>>> from numpy import *
>>> x = array([[5,6],[7,8]])
>>> diagflat(x)
array([[5, 0, 0, 0],
[0, 6, 0, 0],
[0, 0, 7, 0],
[0, 0, 0, 8]])
See also: diag, diagonal, flatten
diagonal()
numpy.diagonal(a, offset=0, axis1=0, axis2=1)
Return specified diagonals.
If `a` is 2-D, returns the diagonal of `a` 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 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 (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 : 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.
diagflat : Create diagonal arrays.
trace : Sum along diagonals.
Examples
--------
>>> a = np.arange(4).reshape(2,2)
>>> a
array([[0, 1],
[2, 3]])
>>> a.diagonal()
array([0, 3])
>>> a.diagonal(1)
array([1])
>>> a = np.arange(8).reshape(2,2,2)
>>> a
array([[[0, 1],
[2, 3]],
<BLANKLINE>
[[4, 5],
[6, 7]]])
>>> a.diagonal(0,-2,-1)
array([[0, 3],
[4, 7]])
ndarray.diagonal(...)
a.diagonal(offset=0, axis1=0, axis2=1)
Return specified diagonals.
Refer to `numpy.diagonal` for full documentation.
See Also
--------
numpy.diagonal : equivalent function
>>> from numpy import *
>>> a = arange(12).reshape(3,4)
>>> print a
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
>>> a.diagonal()
array([ 0, 5, 10])
>>> a.diagonal(offset=1)
array([ 1, 6, 11])
>>> diagonal(a)
array([ 0, 5, 10])
See also: diag, diagflat, trace
diff()
numpy.diff(a, n=1, axis=-1)
Calculate the nth order discrete difference along given axis.
Parameters
----------
a : array_like
Input array
n : int, optional
The number of times values are differenced.
axis : int, optional
The axis along which the difference is taken.
Returns
-------
out : ndarray
The `n` order differences. The shape of the output is the same as `a`
except along `axis` where the dimension is `n` less.
Examples
--------
>>> x = np.array([0,1,3,9,5,10])
>>> np.diff(x)
array([ 1, 2, 6, -4, 5])
>>> np.diff(x,n=2)
array([ 1, 4, -10, 9])
>>> x = np.array([[1,3,6,10],[0,5,6,8]])
>>> np.diff(x)
array([[2, 3, 4],
[5, 1, 2]])
>>> np.diff(x,axis=0)
array([[-1, 2, 0, -2]])
>>> from numpy import *
>>> x = array([0,1,3,9,5,10])
>>> diff(x)
array([ 1, 2, 6, -4, 5])
>>> diff(x,n=2)
array([ 1, 4, -10, 9])
>>> x = array([[1,3,6,10],[0,5,6,8]])
>>> diff(x)
array([[2, 3, 4],
[5, 1, 2]])
>>> diff(x,axis=0)
array([[-1, 2, 0, -2]])
digitize()
numpy.digitize(...)
digitize(x,bins)
Return the index of the bin to which each value of x belongs.
Each index i returned is such that bins[i-1] <= x < bins[i] if
bins is monotonically increasing, or bins [i-1] > x >= bins[i] if
bins is monotonically decreasing.
Beyond the bounds of the bins 0 or len(bins) is returned as appropriate.
>>> from numpy import *
>>> x = array([0.2, 6.4, 3.0, 1.6])
>>> bins = array([0.0, 1.0, 2.5, 4.0, 10.0])
>>> d = digitize(x,bins)
>>> d
array([1, 4, 3, 2])
>>> for n in range(len(x)):
... print bins[d[n]-1], "<=", x[n], "<", bins[d[n]]
...
0.0 <= 0.2 < 1.0
4.0 <= 6.4 < 10.0
2.5 <= 3.0 < 4.0
1.0 <= 1.6 < 2.5
See also: bincount, histogram
disp()
numpy.disp(mesg, device=None, linefeed=True)
Display a message on a device
Parameters
----------
mesg : string
Message to display.
device : device object with 'write' method
Device to write message. If None, defaults to ``sys.stdout`` which is
very similar to ``print``.
linefeed : bool, optional
Option whether to print a line feed or not. Defaults to True.
divide()
numpy.divide(...)
y = divide(x1,x2)
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
dot()
numpy.dot(...)
dot(a,b)
Returns the dot product of a and b for arrays of floating point types.
Like the generic numpy equivalent the product sum is over
the last dimension of a and the second-to-last dimension of b.
NB: The first argument is not conjugated.
>>> from numpy import *
>>> x = array([[1,2,3],[4,5,6]])
>>> x.shape
(2, 3)
>>> y = array([[1,2],[3,4],[5,6]])
>>> y.shape
(3, 2)
>>> dot(x,y)
array([[22, 28],
[49, 64]])
>>>
>>> import numpy
>>> if id(dot) == id(numpy.core.multiarray.dot):
... print "Not using blas/lapack!"
See also: vdot, inner, multiply
dsplit()
numpy.dsplit(ary, indices_or_sections)
Split array into multiple sub-arrays along the 3rd axis (depth).
Parameters
----------
ary : ndarray
An array, with at least 3 dimensions, to be divided into sub-arrays
depth-wise, or along the third axis.
indices_or_sections: integer or 1D array
If `indices_or_sections` is an integer, N, the array will be divided
into N equal arrays along `axis`. If an equal split is not possible,
a ValueError is raised.
if `indices_or_sections` is a 1D array of sorted integers representing
indices along `axis`, the array will be divided such that each index
marks the start of each sub-array. If an index exceeds the dimension of
the array along `axis`, and empty sub-array is returned for that index.
axis : integer, optional
the axis along which to split. Default is 0.
Returns
-------
sub-arrays : list
A list of sub-arrays.
See Also
--------
array_split : Split an array into a list of multiple sub-arrays
of near-equal size.
split : Split array into a list of multiple sub-arrays of equal size.
hsplit : Split array into a list of multiple sub-arrays horizontally
vsplit : Split array into a list of multiple sub-arrays vertically
concatenate : Join arrays together.
hstack : Stack arrays in sequence horizontally (column wise)
vstack : Stack arrays in sequence vertically (row wise)
dstack : Stack arrays in sequence depth wise (along third dimension)
Notes
-----
`dsplit` requires that sub-arrays are of equal shape, whereas
`array_split` allows for sub-arrays to have nearly-equal shape.
Equivalent to `split` with `axis` = 2.
Examples
--------
>>> x = np.arange(16.0).reshape(2, 2, 4)
>>> np.dsplit(x, 2)
<BLANKLINE>
[array([[[ 0., 1.],
[ 4., 5.]],
<BLANKLINE>
[[ 8., 9.],
[ 12., 13.]]]),
array([[[ 2., 3.],
[ 6., 7.]],
<BLANKLINE>
[[ 10., 11.],
[ 14., 15.]]])]
<BLANKLINE>
>>> x = np.arange(16.0).reshape(2, 2, 4)
>>> np.dsplit(x, array([3, 6]))
<BLANKLINE>
[array([[[ 0., 1., 2.],
[ 4., 5., 6.]],
<BLANKLINE>
[[ 8., 9., 10.],
[ 12., 13., 14.]]]),
array([[[ 3.],
[ 7.]],
<BLANKLINE>
[[ 11.],
[ 15.]]]),
array([], dtype=float64)]
>>> from numpy import *
>>> a = array([[1,2],[3,4]])
>>> b = dstack((a,a,a,a))
>>> b.shape
(2, 2, 4)
>>> c = dsplit(b,2)
>>> print c[0].shape, c[1].shape
(2, 2, 2) (2, 2, 2)
>>> d = dsplit(b,[1,2])
>>> print d[0].shape, d[1].shape, d[2].shape
(2, 2, 1) (2, 2, 1) (2, 2, 2)
See also: split, array_split, hsplit, vsplit, dstack
dstack()
numpy.dstack(tup)
Stack arrays in sequence depth wise (along third axis)
Takes a sequence of arrays and stack them along the third axis
to make a single array. Rebuilds arrays divided by ``dsplit``.
This is a simple way to stack 2D arrays (images) into a single
3D array for processing.
Parameters
----------
tup : sequence of arrays
Arrays to stack. All of them must have the same shape along all
but the third axis.
Returns
-------
stacked : ndarray
The array formed by stacking the given arrays.
See Also
--------
vstack : Stack along first axis.
hstack : Stack along second axis.
concatenate : Join arrays.
dsplit : Split array along third axis.
Notes
-----
Equivalent to ``np.concatenate(tup, axis=2)``
Examples
--------
>>> a = np.array((1,2,3))
>>> b = np.array((2,3,4))
>>> np.dstack((a,b))
array([[[1, 2],
[2, 3],
[3, 4]]])
>>> a = np.array([[1],[2],[3]])
>>> b = np.array([[2],[3],[4]])
>>> np.dstack((a,b))
array([[[1, 2]],
<BLANKLINE>
[[2, 3]],
<BLANKLINE>
[[3, 4]]])
>>> from numpy import *
>>> a = array([[1,2],[3,4]])
>>> b = array([[5,6],[7,8]])
>>> dstack((a,b))
array([[[1, 5],
[2, 6]],
[[3, 7],
[4, 8]]])
See also: column_stack, concatenate, hstack, vstack, dsplit
dtype() or .dtype
numpy.dtype(...)
Create a data type.
A numpy array is homogeneous, and contains elements described by a
dtype. A dtype can be constructed from different combinations of
fundamental numeric types, as illustrated below.
Examples
--------
Using array-scalar type:
>>> np.dtype(np.int16)
dtype('int16')
Record, one field name 'f1', containing int16:
>>> np.dtype([('f1', np.int16)])
dtype([('f1', '<i2')])
Record, one field named 'f1', in itself containing a record with one field:
>>> np.dtype([('f1', [('f1', np.int16)])])
dtype([('f1', [('f1', '<i2')])])
Record, two fields: the first field contains an unsigned int, the
second an int32:
>>> np.dtype([('f1', np.uint), ('f2', np.int32)])
dtype([('f1', '<u4'), ('f2', '<i4')])
Using array-protocol type strings:
>>> np.dtype([('a','f8'),('b','S10')])
dtype([('a', '<f8'), ('b', '|S10')])
Using comma-separated field formats. The shape is (2,3):
>>> np.dtype("i4, (2,3)f8")
dtype([('f0', '<i4'), ('f1', '<f8', (2, 3))])
Using tuples. ``int`` is a fixed type, 3 the field's shape. ``void``
is a flexible type, here of size 10:
>>> np.dtype([('hello',(np.int,3)),('world',np.void,10)])
dtype([('hello', '<i4', 3), ('world', '|V10')])
Subdivide ``int16`` into 2 ``int8``'s, called x and y. 0 and 1 are
the offsets in bytes:
>>> np.dtype((np.int16, {'x':(np.int8,0), 'y':(np.int8,1)}))
dtype(('<i2', [('x', '|i1'), ('y', '|i1')]))
Using dictionaries. Two fields named 'gender' and 'age':
>>> np.dtype({'names':['gender','age'], 'formats':['S1',np.uint8]})
dtype([('gender', '|S1'), ('age', '|u1')])
Offsets in bytes, here 0 and 25:
>>> np.dtype({'surname':('S25',0),'age':(np.uint8,25)})
dtype([('surname', '|S25'), ('age', '|u1')])
ndarray.dtype
Data-type for the array.
>>> from numpy import *
>>> dtype('int16')
dtype('int16')
>>> dtype([('f1', 'int16')])
dtype([('f1', '<i2')])
>>> dtype([('f1', [('f1', 'int16')])])
dtype([('f1', [('f1', '<i2')])])
>>> dtype([('f1', 'uint'), ('f2', 'int32')])
dtype([('f1', '<u4'), ('f2', '<i4')])
>>> dtype([('a','f8'),('b','S10')])
dtype([('a', '<f8'), ('b', '|S10')])
>>> dtype("i4, (2,3)f8")
dtype([('f0', '<i4'), ('f1', '<f8', (2, 3))])
>>> dtype([('hello',('int',3)),('world','void',10)])
dtype([('hello', '<i4', 3), ('world', '|V10')])
>>> dtype(('int16', {'x':('int8',0), 'y':('int8',1)}))
dtype(('<i2', [('x', '|i1'), ('y', '|i1')]))
>>> dtype({'names':['gender','age'], 'formats':['S1',uint8]})
dtype([('gender', '|S1'), ('age', '|u1')])
>>> dtype({'surname':('S25',0),'age':(uint8,25)})
dtype([('surname', '|S25'), ('age', '|u1')])
>>>
>>> a = dtype('int32')
>>> a
dtype('int32')
>>> a.type
<type 'numpy.int32'>
>>> a.kind
'i'
>>> a.char
'l'
>>> a.num
7
>>> a.str
'<i4'
>>> a.name
'int32'
>>> a.byteorder
'='
>>> a.itemsize
4
>>> a = dtype({'surname':('S25',0),'age':(uint8,25)})
>>> a.fields.keys()
['age', 'surname']
>>> a.fields.values()
[(dtype('uint8'), 25), (dtype('|S25'), 0)]
>>> a = dtype([('x', 'f4'),('y', 'f4'),
... ('nested', [('i', 'i2'),('j','i2')])])
>>> a.fields['nested']
(dtype([('i', '<i2'), ('j', '<i2')]), 8)
>>> a.fields['nested'][0].fields['i']
(dtype('int16'), 0)
>>> a.fields['nested'][0].fields['i'][0].type
<type 'numpy.int16'>
See also: array, typeDict, astype
dump()
ndarray.dump(...)
a.dump(file)
Dump a pickle of the array to the specified file.
The array can be read back with pickle.load or numpy.load.
Parameters
----------
file : str
A string naming the dump file.
dumps()
ndarray.dumps(...)
a.dumps()
Returns the pickle of the array as a string.
pickle.loads or numpy.loads will convert the string back to an array.
ediff1d()
numpy.ediff1d(ary, to_end=None, to_begin=None)
The differences between consecutive elements of an array.
Parameters
----------
ary : array
This array will be flattened before the difference is taken.
to_end : number, optional
If provided, this number will be tacked onto the end of the returned
differences.
to_begin : number, optional
If provided, this number will be taked onto the beginning of the
returned differences.
Returns
-------
ed : array
The differences. Loosely, this will be (ary[1:] - ary[:-1]).
empty()
numpy.empty(...)
empty(shape, dtype=float, order='C')
Return a new array of given shape and type, without initialising entries.
Parameters
----------
shape : {tuple of int, int}
Shape of the empty array
dtype : data-type, optional
Desired output data-type.
order : {'C', 'F'}, optional
Whether to store multi-dimensional data in C (row-major) or
Fortran (column-major) order in memory.
See Also
--------
empty_like, zeros
Notes
-----
`empty`, unlike `zeros`, does not set the array values to zero,
and may therefore be marginally faster. On the other hand, it requires
the user to manually set all the values in the array, and should be
used with caution.
Examples
--------
>>> np.empty([2, 2])
array([[ -9.74499359e+001, 6.69583040e-309], #random data
[ 2.13182611e-314, 3.06959433e-309]])
>>> np.empty([2, 2], dtype=int)
array([[-1073741821, -1067949133], #random data
[ 496041986, 19249760]])
>>> from numpy import *
>>> empty(3)
array([ 6.08581638e+000, 3.45845952e-323, 4.94065646e-324])
>>> empty((2,3),int)
array([[1075337192, 1075337192, 135609024],
[1084062604, 1197436517, 1129066306]])
See also: ones, zeros, eye, identity
empty_like()
numpy.empty_like(a)
Create a new array with the same shape and type as another.
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]])
>>> from numpy import *
>>> a = array([[1,2,3],[4,5,6]])
>>> empty_like(a)
array([[ 0, 25362433, 6571520],
[ 21248, 136447968, 4]])
See also: ones_like, zeros_like
equal()
numpy.equal(...)
y = equal(x1,x2)
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`.
exp()
numpy.exp(...)
y = exp(x)
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()
expand_dims()
numpy.expand_dims(a, axis)
Expand the shape of an array.
Insert a new axis, corresponding to a given position in the array shape.
Parameters
----------
a : array_like
Input array.
axis : int
Position (amongst axes) where new axis is to be inserted.
Returns
-------
res : ndarray
Output array. The number of dimensions is one greater than that of
the input array.
See Also
--------
doc.indexing, atleast_1d, atleast_2d, atleast_3d
Examples
--------
>>> x = np.array([1,2])
>>> x.shape
(2,)
The following is equivalent to ``x[np.newaxis,:]`` or ``x[np.newaxis]``:
>>> y = np.expand_dims(x, axis=0)
>>> y
array([[1, 2]])
>>> y.shape
(1, 2)
>>> y = np.expand_dims(x, axis=1) # Equivalent to x[:,newaxis]
>>> y
array([[1],
[2]])
>>> y.shape
(2, 1)
Note that some examples may use ``None`` instead of ``np.newaxis``. These
are the same objects:
>>> np.newaxis is None
True
>>> from numpy import *
>>> x = array([1,2])
>>> expand_dims(x,axis=0)
array([[1, 2]])
>>> expand_dims(x,axis=1)
array([[1],
[2]])
See also: newaxis, atleast_1d, atleast_2d, atleast_3d
expm1()
numpy.expm1(...)
y = expm1(x)
Return the exponential of the elements in the array minus one.
Parameters
----------
x : array_like
Input values.
Returns
-------
out : ndarray
Element-wise exponential minus one: ``out=exp(x)-1``.
See Also
--------
log1p : ``log(1+x)``, the inverse of expm1.
Notes
-----
This function provides greater precision than using ``exp(x)-1``
for small values of `x`.
Examples
--------
Since the series expansion of ``e**x = 1 + x + x**2/2! + x**3/3! + ...``,
for very small `x` we expect that ``e**x -1 ~ x + x**2/2``:
>>> np.expm1(1e-10)
1.00000000005e-10
>>> np.exp(1e-10) - 1
1.000000082740371e-10
numpy.extract(condition, arr)
Return the elements of an array that satisfy some condition.
This is equivalent to ``np.compress(ravel(condition), ravel(arr))``. If
`condition` is boolean ``np.extract`` is equivalent to ``arr[condition]``.
Parameters
----------
condition : array_like
An array whose nonzero or True entries indicate the elements of `arr`
to extract.
arr : array_like
Input array of the same size as `condition`.
See Also
--------
take, put, putmask
Examples
--------
>>> arr = np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12]])
>>> arr
array([[ 1, 2, 3, 4],
[ 5, 6, 7, 8],
[ 9, 10, 11, 12]])
>>> condition = np.mod(arr, 3)==0
>>> condition
array([[False, False, True, False],
[False, True, False, False],
[ True, False, False, True]], dtype=bool)
>>> np.extract(condition, arr)
array([ 3, 6, 9, 12])
If `condition` is boolean:
>>> arr[condition]
array([ 3, 6, 9, 12])
eye()
numpy.eye(N, M=None, k=0, dtype=<type 'float'>)
Return a 2-D array with ones on the diagonal and zeros elsewhere.
Parameters
----------
N : int
Number of rows in the output.
M : int, optional
Number of columns in the output. If None, defaults to `N`.
k : int, optional
Index of the diagonal: 0 refers to the main diagonal, a positive value
refers to an upper diagonal, and a negative value to a lower diagonal.
dtype : dtype, optional
Data-type of the returned array.
Returns
-------
I : ndarray (N,M)
An array where all elements are equal to zero, except for the `k`-th
diagonal, whose values are equal to one.
See Also
--------
diag : Return a diagonal 2-D array using a 1-D array specified by the user.
Examples
--------
>>> np.eye(2, dtype=int)
array([[1, 0],
[0, 1]])
>>> np.eye(3, k=1)
array([[ 0., 1., 0.],
[ 0., 0., 1.],
[ 0., 0., 0.]])
>>> from numpy import *
>>> eye(3,4,0,dtype=float)
array([[ 1., 0., 0., 0.],
[ 0., 1., 0., 0.],
[ 0., 0., 1., 0.]])
>>> eye(3,4,1,dtype=float)
array([[ 0., 1., 0., 0.],
[ 0., 0., 1., 0.],
[ 0., 0., 0., 1.]])
See also: ones, zeros, empty, identity
fabs()
numpy.fabs(...)
y = fabs(x)
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])
fastCopyAndTranspose()
numpy.fastCopyAndTranspose(...)
_fastCopyAndTranspose(a)
fft
numpy.fft
Core FFT routines
==================
Standard FFTs
fft
ifft
fft2
ifft2
fftn
ifftn
Real FFTs
rfft
irfft
rfft2
irfft2
rfftn
irfftn
Hermite FFTs
hfft
ihfft
>>> from numpy import *
>>> from numpy.fft import *
>>> signal = array([-2., 8., -6., 4., 1., 0., 3., 5.])
>>> fourier = fft(signal)
>>> fourier
array([ 13. +0.j , 3.36396103 +4.05025253j,
2. +1.j , -9.36396103-13.94974747j,
-21. +0.j , -9.36396103+13.94974747j,
2. -1.j , 3.36396103 -4.05025253j])
>>>
>>> N = len(signal)
>>> fourier = empty(N,complex)
>>> for k in range(N):
... fourier[k] = sum(signal * exp(-1j*2*pi*k*arange(N)/N))
...
>>> timestep = 0.1
>>> fftfreq(N, d=timestep)
array([ 0. , 1.25, 2.5 , 3.75, -5. , -3.75, -2.5 , -1.25])
See also: ifft, fftfreq, fftshift
fftfreq
>>> from numpy import *
>>> from numpy.fft import *
>>> signal = array([-2., 8., -6., 4., 1., 0., 3., 5.])
>>> fourier = fft(signal)
>>> N = len(signal)
>>> timestep = 0.1
>>> freq = fftfreq(N, d=timestep)
>>> freq
array([ 0. , 1.25, 2.5 , 3.75, -5. , -3.75, -2.5 , -1.25])
>>>
>>> fftshift(freq)
array([-5. , -3.75, -2.5 , -1.25, 0. , 1.25, 2.5 , 3.75])
See also: fft, ifft, fftshift
fftshift
>>> from numpy import *
>>> from numpy.fft import *
>>> signal = array([-2., 8., -6., 4., 1., 0., 3., 5.])
>>> fourier = fft(signal)
>>> N = len(signal)
>>> timestep = 0.1
>>> freq = fftfreq(N, d=timestep)
>>> freq
array([ 0. , 1.25, 2.5 , 3.75, -5. , -3.75, -2.5 , -1.25])
>>>
>>> freq = fftshift(freq)
>>> freq
array([-5. , -3.75, -2.5 , -1.25, 0. , 1.25, 2.5 , 3.75])
>>> fourier = fftshift(fourier)
>>>
>>> freq = ifftshift(freq)
>>> fourier = ifftshift(fourier)
See also: fft, ifft, fftfreq
fill()
ndarray.fill(...)
a.fill(value)
Fill the array with a scalar value.
Parameters
----------
a : ndarray
Input array
value : scalar
All elements of `a` will be assigned this value.
Examples
--------
>>> a = np.array([1, 2])
>>> a.fill(0)
>>> a
array([0, 0])
>>> a = np.empty(2)
>>> a.fill(1)
>>> a
array([ 1., 1.])
>>> from numpy import *
>>> a = arange(4, dtype=int)
>>> a
array([0, 1, 2, 3])
>>> a.fill(7)
>>> a
array([7, 7, 7, 7])
>>> a.fill(6.5)
>>> a
array([6, 6, 6, 6])
See also: empty, zeros, ones, repeat
find_common_type()
numpy.find_common_type(array_types, scalar_types)
Determine common type following standard coercion rules
Parameters
----------
array_types : sequence
A list of dtype convertible objects representing arrays
scalar_types : sequence
A list of dtype convertible objects representing scalars
Returns
-------
datatype : dtype
The common data-type which is the maximum of the array_types
ignoring the scalar_types unless the maximum of the scalar_types
is of a different kind.
If the kinds is not understood, then None is returned.
See Also
--------
dtype
finfo()
numpy.finfo(...)
finfo(dtype)
Machine limits for floating point types.
Attributes
----------
eps : floating point number of the appropriate type
The smallest representable number such that ``1.0 + eps != 1.0``.
epsneg : floating point number of the appropriate type
The smallest representable number such that ``1.0 - epsneg != 1.0``.
iexp : int
The number of bits in the exponent portion of the floating point
representation.
machar : MachAr
The object which calculated these parameters and holds more detailed
information.
machep : int
The exponent that yields ``eps``.
max : floating point number of the appropriate type
The largest representable number.
maxexp : int
The smallest positive power of the base (2) that causes overflow.
min : floating point number of the appropriate type
The smallest representable number, typically ``-max``.
minexp : int
The most negative power of the base (2) consistent with there being
no leading 0s in the mantissa.
negep : int
The exponent that yields ``epsneg``.
nexp : int
The number of bits in the exponent including its sign and bias.
nmant : int
The number of bits in the mantissa.
precision : int
The approximate number of decimal digits to which this kind of float
is precise.
resolution : floating point number of the appropriate type
The approximate decimal resolution of this type, i.e.
``10**-precision``.
tiny : floating point number of the appropriate type
The smallest-magnitude usable number.
Parameters
----------
dtype : floating point type, dtype, or instance
The kind of floating point data type to get information about.
See Also
--------
numpy.lib.machar.MachAr :
The implementation of the tests that produce this information.
iinfo :
The equivalent for integer data types.
Notes
-----
For developers of numpy: do not instantiate this at the module level. The
initial calculation of these parameters is expensive and negatively impacts
import times. These objects are cached, so calling ``finfo()`` repeatedly
inside your functions is not a problem.
>>> from numpy import *
>>> f = finfo(float)
>>> f.nmant, f.nexp
(52, 11)
>>> f.machep
-52
>>> f.eps
array(2.2204460492503131e-16)
>>> f.precision
15
>>> f.resolution
array(1.0000000000000001e-15)
>>> f.negep
-53
>>> f.epsneg
array(1.1102230246251565e-16)
>>> f.minexp
-1022
>>> f.tiny
array(2.2250738585072014e-308)
>>> f.maxexp
1024
>>> f.min, f.max
(-1.7976931348623157e+308, array(1.7976931348623157e+308))
fix()
numpy.fix(x, y=None)
Round to nearest integer towards zero.
Round an array of floats element-wise to nearest integer towards zero.
The rounded values are returned as floats.
Parameters
----------
x : array_like
An array of floats to be rounded
y : ndarray, optional
Output array
Returns
-------
out : ndarray of floats
The array of rounded numbers
See Also
--------
floor : Round downwards
around : Round to given number of decimals
Examples
--------
>>> np.fix(3.14)
3.0
>>> np.fix(3)
3.0
>>> np.fix([2.1, 2.9, -2.1, -2.9])
array([ 2., 2., -2., -2.])
>>> from numpy import *
>>> a = array([-1.7, -1.5, -0.2, 0.2, 1.5, 1.7])
>>> fix(a)
array([-1., -1., 0., 0., 1., 1.])
See also: round_, ceil, floor, astype
flat
ndarray.flat
A 1-d flat iterator.
Examples
--------
>>> x = np.arange(3*4*5)
>>> x.shape = (3,4,5)
>>> x.flat[19]
19
>>> x.T.flat[19]
31
>>> from numpy import *
>>> a = array([[10,30],[40,60]])
>>> iter = a.flat
>>> iter.next()
10
>>> iter.next()
30
>>> iter.next()
40
See also: broadcast, flatten
flatnonzero()
numpy.flatnonzero(a)
Return indices that are non-zero in the flattened version of a.
This is equivalent to a.ravel().nonzero()[0].
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(x)
array([0, 1, 3, 4])
>>> x.ravel()[np.flatnonzero(x)]
array([-2, -1, 1, 2])
flatten()
ndarray.flatten(...)
a.flatten(order='C')
Collapse an array into one dimension.
Parameters
----------
order : {'C', 'F'}, optional
Whether to flatten in C (row-major) or Fortran (column-major) order.
The default is 'C'.
Returns
-------
y : ndarray
A copy of the input array, flattened to one dimension.
Examples
--------
>>> a = np.array([[1,2], [3,4]])
>>> a.flatten()
array([1, 2, 3, 4])
>>> a.flatten('F')
array([1, 3, 2, 4])
>>> from numpy import *
>>> a = array([[[1,2]],[[3,4]]])
>>> print a
[[[1 2]]
[[3 4]]]
>>> b = a.flatten()
>>> print b
[1 2 3 4]
See also: ravel, flat
fliplr()
numpy.fliplr(m)
Left-right flip.
Flip the entries in each row in the left/right direction.
Columns are preserved, but appear in a different order than before.
Parameters
----------
m : array_like
Input array.
Returns
-------
f : ndarray
A view of `m` with the columns reversed. Since a view
is returned, this operation is :math:`\mathcal O(1)`.
See Also
--------
flipud : Flip array in the up/down direction.
rot90 : Rotate array counterclockwise.
Notes
-----
Equivalent to A[::-1,...]. Does not require the array to be
two-dimensional.
Examples
--------
>>> A = np.diag([1.,2.,3.])
>>> A
array([[ 1., 0., 0.],
[ 0., 2., 0.],
[ 0., 0., 3.]])
>>> np.fliplr(A)
array([[ 0., 0., 1.],
[ 0., 2., 0.],
[ 3., 0., 0.]])
>>> A = np.random.randn(2,3,5)
>>> np.all(numpy.fliplr(A)==A[:,::-1,...])
True
>>> from numpy import *
>>> a = arange(12).reshape(4,3)
>>> a
array([[ 0, 1, 2],
[ 3, 4, 5],
[ 6, 7, 8],
[ 9, 10, 11]])
>>> fliplr(a)
array([[ 2, 1, 0],
[ 5, 4, 3],
[ 8, 7, 6],
[11, 10, 9]])
See also: flipud, rot90
flipud()
numpy.flipud(m)
Up-down flip.
Flip the entries in each column in the up/down direction.
Rows are preserved, but appear in a different order than before.
Parameters
----------
m : array_like
Input array.
Returns
-------
out : array_like
A view of `m` with the rows reversed. Since a view is
returned, this operation is :math:`\mathcal O(1)`.
Notes
-----
Equivalent to ``A[::-1,...]``.
Does not require the array to be two-dimensional.
Examples
--------
>>> A = np.diag([1.0, 2, 3])
>>> A
array([[ 1., 0., 0.],
[ 0., 2., 0.],
[ 0., 0., 3.]])
>>> np.flipud(A)
array([[ 0., 0., 3.],
[ 0., 2., 0.],
[ 1., 0., 0.]])
>>> A = np.random.randn(2,3,5)
>>> np.all(np.flipud(A)==A[::-1,...])
True
>>> np.flipud([1,2])
array([2, 1])
>>> from numpy import *
>>> a = arange(12).reshape(4,3)
>>> a
array([[ 0, 1, 2],
[ 3, 4, 5],
[ 6, 7, 8],
[ 9, 10, 11]])
>>> flipud(a)
array([[ 9, 10, 11],
[ 6, 7, 8],
[ 3, 4, 5],
[ 0, 1, 2]])
See also: fliplr, rot90
floor()
numpy.floor(...)
y = floor(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.])
>>> from numpy import *
>>> a = array([-1.7, -1.5, -0.2, 0.2, 1.5, 1.7])
>>> floor(a)
array([-2., -2., -1., 0., 1., 1.])
See also: ceil, round_, fix, astype
floor_divide()
numpy.floor_divide(...)
y = floor_divide(x1,x2)
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.])
fmod()
numpy.fmod(...)
y = fmod(x1,x2)
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])
frexp()
numpy.frexp(...)
y1,y2 = frexp(x)
Split the number, x, into a normalized fraction (y1) and exponent (y2)
fromarrays()
numpy.core.records.fromarrays(arrayList, dtype=None, shape=None, formats=None, names=None, titles=None, aligned=False, byteorder=None)
create a record array from a (flat) list of arrays
>>> x1=np.array([1,2,3,4])
>>> x2=np.array(['a','dd','xyz','12'])
>>> x3=np.array([1.1,2,3,4])
>>> r = np.core.records.fromarrays([x1,x2,x3],names='a,b,c')
>>> print r[1]
(2, 'dd', 2.0)
>>> x1[1]=34
>>> r.a
array([1, 2, 3, 4])
>>> from numpy import *
>>> x = array(['Smith','Johnson','McDonald'])
>>> y = array(['F','F','M'], dtype='S1')
>>> z = array([20,25,23])
>>> data = rec.fromarrays([x,y,z], names='surname, gender, age')
>>> data[0]
('Smith', 'F', 20)
>>> data.age
array([20, 25, 23])
See also: view
frombuffer()
numpy.frombuffer(...)
frombuffer(buffer, dtype=float, count=-1, offset=0)
Interpret a buffer as a 1-dimensional array.
Parameters
----------
buffer
An object that exposes the buffer interface.
dtype : data-type, optional
Data type of the returned array.
count : int, optional
Number of items to read. ``-1`` means all data in the buffer.
offset : int, optional
Start reading the buffer from this offset.
Notes
-----
If the buffer has data that is not in machine byte-order, this
should be specified as part of the data-type, e.g.::
>>> dt = np.dtype(int)
>>> dt = dt.newbyteorder('>')
>>> np.frombuffer(buf, dtype=dt)
The data of the resulting array will not be byteswapped,
but will be interpreted correctly.
Examples
--------
>>> s = 'hello world'
>>> np.frombuffer(s, dtype='S1', count=5, offset=6)
array(['w', 'o', 'r', 'l', 'd'],
dtype='|S1')
>>> from numpy import *
>>> buffer = "\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\x00@\x00\x00\x00\x00\x00\x00\x08\
... @\x00\x00\x00\x00\x00\x00\x10@\x00\x00\x00\x00\x00\x00\x14@\x00\x00\x00\x00\x00\x00\x18@"
>>> a = frombuffer(buffer, complex128)
>>> a
array([ 1.+2.j, 3.+4.j, 5.+6.j])
See also: fromfunction, fromfile
fromfile()
numpy.fromfile(...)
fromfile(file, dtype=float, count=-1, sep='')
Construct an array from data in a text or binary file.
A highly efficient way of reading binary data with a known data-type,
as well as parsing simply formatted text files. Data written using the
`tofile` method can be read using this function.
Parameters
----------
file : file or string
Open file object or filename.
dtype : data-type
Data type of the returned array.
For binary files, it is used to determine the size and byte-order
of the items in the file.
count : int
Number of items to read. ``-1`` means all items (i.e., the complete
file).
sep : string
Separator between items if file is a text file.
Empty ("") separator means the file should be treated as binary.
Spaces (" ") in the separator match zero or more whitespace characters.
A separator consisting only of spaces must match at least one
whitespace.
See also
--------
load, save
ndarray.tofile
loadtxt : More flexible way of loading data from a text file.
Notes
-----
Do not rely on the combination of `tofile` and `fromfile` for
data storage, as the binary files generated are are not platform
independent. In particular, no byte-order or data-type information is
saved. Data can be stored in the platform independent ``.npy`` format
using `save` and `load` instead.
Examples
--------
Construct an ndarray:
>>> dt = np.dtype([('time', [('min', int), ('sec', int)]),
... ('temp', float)])
>>> x = np.zeros((1,), dtype=dt)
>>> x['time']['min'] = 10; x['temp'] = 98.25
>>> x
array([((10, 0), 98.25)],
dtype=[('time', [('min', '<i4'), ('sec', '<i4')]), ('temp', '<f8')])
Save the raw data to disk:
>>> import os
>>> fname = os.tmpnam()
>>> x.tofile(fname)
Read the raw data from disk:
>>> np.fromfile(fname, dtype=dt)
array([((10, 0), 98.25)],
dtype=[('time', [('min', '<i4'), ('sec', '<i4')]), ('temp', '<f8')])
The recommended way to store and load data:
>>> np.save(fname, x)
>>> np.load(fname + '.npy')
array([((10, 0), 98.25)],
dtype=[('time', [('min', '<i4'), ('sec', '<i4')]), ('temp', '<f8')])
numpy.core.records.fromfile(fd, dtype=None, shape=None, offset=0, formats=None, names=None, titles=None, aligned=False, byteorder=None)
Create an array from binary file data
If file is a string then that file is opened, else it is assumed
to be a file object.
>>> from tempfile import TemporaryFile
>>> a = np.empty(10,dtype='f8,i4,a5')
>>> a[5] = (0.5,10,'abcde')
>>>
>>> fd=TemporaryFile()
>>> a = a.newbyteorder('<')
>>> a.tofile(fd)
>>>
>>> fd.seek(0)
>>> r=np.core.records.fromfile(fd, formats='f8,i4,a5', shape=10,
... byteorder='<')
>>> print r[5]
(0.5, 10, 'abcde')
>>> r.shape
(10,)
>>> from numpy import *
>>> y = array([2.,4.,6.,8.])
>>> y.tofile("myfile.dat")
>>> y.tofile("myfile.txt", sep='\n', format = "%e")
>>> fromfile('myfile.dat', dtype=float)
array([ 2., 4., 6., 8.])
>>> fromfile('myfile.txt', dtype=float, sep='\n')
array([ 2., 4., 6., 8.])
See also: loadtxt, fromfunction, tofile, frombuffer, savetxt
fromfunction()
numpy.fromfunction(function, shape, **kwargs)
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)``.
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]])
>>> from numpy import *
>>> def f(i,j):
... return i**2 + j**2
...
>>> fromfunction(f, (3,3))
array([[0, 1, 4],
[1, 2, 5],
[4, 5, 8]])
See also: fromfile, frombuffer
fromiter()
numpy.fromiter(...)
fromiter(iterable, dtype, count=-1)
Create a new 1-dimensional array from an iterable object.
Parameters
----------
iterable : iterable object
An iterable object providing data for the array.
dtype : data-type
The data type of the returned array.
count : int, optional
The number of items to read from iterable. The default is -1,
which means all data is read.
Returns
-------
out : ndarray
The output array.
Notes
-----
Specify ``count`` to improve performance. It allows
``fromiter`` to pre-allocate the output array, instead of
resizing it on demand.
Examples
--------
>>> iterable = (x*x for x in range(5))
>>> np.fromiter(iterable, np.float)
array([ 0., 1., 4., 9., 16.])
>>> from numpy import *
>>> import itertools
>>> mydata = [[55.5, 40],[60.5, 70]]
>>> mydescriptor = {'names': ('weight','age'), 'formats': (float32, int32)}
>>> myiterator = itertools.imap(tuple,mydata)
>>> a = fromiter(myiterator, dtype = mydescriptor)
>>> a
array([(55.5, 40), (60.5, 70)],
dtype=[('weight', '<f4'), ('age', '<i4')])
See also: fromarrays, frombuffer, fromfile, fromfunction
frompyfunc()
numpy.frompyfunc(...)
frompyfunc(func, nin, nout) take an arbitrary python function that takes nin objects as input and returns nout objects and return a universal function (ufunc). This ufunc always returns PyObject arrays
fromregex()
numpy.fromregex(file, regexp, dtype)
Construct an array from a text file, using regular-expressions parsing.
Array is constructed from all matches of the regular expression
in the file. Groups in the regular expression are converted to fields.
Parameters
----------
file : str or file
File name or file object to read.
regexp : str or regexp
Regular expression used to parse the file.
Groups in the regular expression correspond to fields in the dtype.
dtype : dtype or dtype list
Dtype for the structured array
Examples
--------
>>> f = open('test.dat', 'w')
>>> f.write("1312 foo\n1534 bar\n444 qux")
>>> f.close()
>>> np.fromregex('test.dat', r"(\d+)\s+(...)",
... [('num', np.int64), ('key', 'S3')])
array([(1312L, 'foo'), (1534L, 'bar'), (444L, 'qux')],
dtype=[('num', '<i8'), ('key', '|S3')])
fromstring()
numpy.fromstring(...)
fromstring(string, dtype=float, count=-1, sep='')
Return a new 1d array initialized from raw binary or text data in
string.
Parameters
----------
string : str
A string containing the data.
dtype : dtype, optional
The data type of the array. For binary input data, the data must be
in exactly this format.
count : int, optional
Read this number of `dtype` elements from the data. If this is
negative, then the size will be determined from the length of the
data.
sep : str, optional
If provided and not empty, then the data will be interpreted as
ASCII text with decimal numbers. This argument is interpreted as the
string separating numbers in the data. Extra whitespace between
elements is also ignored.
Returns
-------
arr : array
The constructed array.
Raises
------
ValueError
If the string is not the correct size to satisfy the requested
`dtype` and `count`.
Examples
--------
>>> np.fromstring('\x01\x02', dtype=np.uint8)
array([1, 2], dtype=uint8)
>>> np.fromstring('1 2', dtype=int, sep=' ')
array([1, 2])
>>> np.fromstring('1, 2', dtype=int, sep=',')
array([1, 2])
>>> np.fromstring('\x01\x02\x03\x04\x05', dtype=np.uint8, count=3)
array([1, 2, 3], dtype=uint8)
Invalid inputs:
>>> np.fromstring('\x01\x02\x03\x04\x05', dtype=np.int32)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: string size must be a multiple of element size
>>> np.fromstring('\x01\x02', dtype=np.uint8, count=3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: string is smaller than requested size
fv()
numpy.fv(rate, nper, pmt, pv, when='end')
Compute the future value.
Parameters
----------
rate : scalar or array_like of shape(M, )
Rate of interest as decimal (not per cent) per period
nper : scalar or array_like of shape(M, )
Number of compounding periods
pmt : scalar or array_like of shape(M, )
Payment
pv : scalar or array_like of shape(M, )
Present value
when : {{'begin', 1}, {'end', 0}}, {string, int}, optional
When payments are due ('begin' (1) or 'end' (0)).
Defaults to {'end', 0}.
Returns
-------
out : ndarray
Future values. If all input is scalar, returns a scalar float. If
any input is array_like, returns future values for each input element.
If multiple inputs are array_like, they all must have the same shape.
Notes
-----
The future value is computed by solving the equation::
fv +
pv*(1+rate)**nper +
pmt*(1 + rate*when)/rate*((1 + rate)**nper - 1) == 0
or, when ``rate == 0``::
fv + pv + pmt * nper == 0
Examples
--------
What is the future value after 10 years of saving $100 now, with
an additional monthly savings of $100. Assume the interest rate is
5% (annually) compounded monthly?
>>> np.fv(0.05/12, 10*12, -100, -100)
15692.928894335748
By convention, the negative sign represents cash flow out (i.e. money not
available today). Thus, saving $100 a month at 5% annual interest leads
to $15,692.93 available to spend in 10 years.
If any input is array_like, returns an array of equal shape. Let's
compare different interest rates from the example above.
>>> a = np.array((0.05, 0.06, 0.07))/12
>>> np.fv(a, 10*12, -100, -100)
array([ 15692.92889434, 16569.87435405, 17509.44688102])
generic()
numpy.generic(...)
>>> from numpy import *
>>> numpyscalar = string_('7')
>>> numpyscalar
'7'
>>> type(numpyscalar)
<type 'numpy.string_'>
>>> buildinscalar = '7'
>>> type(buildinscalar)
<type 'str'>
>>> isinstance(numpyscalar, generic)
True
>>> isinstance(buildinscalar, generic)
False
get_array_wrap()
numpy.get_array_wrap(*args)
Find the wrapper for the array with the highest priority.
In case of ties, leftmost wins. If no wrapper is found, return None
get_include()
numpy.get_include()
Return the directory that contains the numpy \*.h header files.
Extension modules that need to compile against numpy should use this
function to locate the appropriate include directory.
Notes
-----
When using ``distutils``, for example in ``setup.py``.
::
import numpy as np
...
Extension('extension_name', ...
include_dirs=[np.get_include()])
...
get_numarray_include()
numpy.get_numarray_include(type=None)
Return the directory that contains the numarray \*.h header files.
Extension modules that need to compile against numarray should use this
function to locate the appropriate include directory.
Notes
-----
When using ``distutils``, for example in ``setup.py``.
::
import numpy as np
...
Extension('extension_name', ...
include_dirs=[np.get_numarray_include()])
...
get_numpy_include()
numpy.get_numpy_include(*args, **kwds)
get_numpy_include is DEPRECATED!! -- use get_include instead
Return the directory that contains the numpy \*.h header files.
Extension modules that need to compile against numpy should use this
function to locate the appropriate include directory.
Notes
-----
When using ``distutils``, for example in ``setup.py``.
::
import numpy as np
...
Extension('extension_name', ...
include_dirs=[np.get_include()])
...
get_printoptions()
numpy.get_printoptions()
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
getbuffer()
numpy.getbuffer(...)
getbuffer(obj [,offset[, size]])
Create a buffer object from the given object referencing a slice of
length size starting at offset. Default is the entire buffer. A
read-write buffer is attempted followed by a read-only buffer.
getbufsize()
numpy.getbufsize()
Return the size of the buffer used in ufuncs.
geterr()
numpy.geterr()
Get the current way of handling floating-point errors.
Returns a dictionary with entries "divide", "over", "under", and
"invalid", whose values are from the strings
"ignore", "print", "log", "warn", "raise", and "call".
geterrcall()
numpy.geterrcall()
Return the current callback function used on floating-point errors.
geterrobj()
numpy.geterrobj(...)
geterrobj()
Used internally by `geterr`.
Returns
-------
errobj : list
Internal numpy buffer size, error mask, error callback function.
getfield()
ndarray.getfield(...)
a.getfield(dtype, offset)
Returns a field of the given array as a certain type. A field is a view of
the array data with each itemsize determined by the given type and the
offset into the current array.
gradient()
numpy.gradient(f, *varargs)
Return the gradient of an N-dimensional array.
The gradient is computed using central differences in the interior
and first differences at the boundaries. The returned gradient hence has
the same shape as the input array.
Parameters
----------
f : array_like
An N-dimensional array containing samples of a scalar function.
`*varargs` : scalars
0, 1, or N scalars specifying the sample distances in each direction,
that is: `dx`, `dy`, `dz`, ... The default distance is 1.
Returns
-------
g : ndarray
N arrays of the same shape as `f` giving the derivative of `f` with
respect to each dimension.
Examples
--------
>>> np.gradient(np.array([[1,1],[3,4]]))
[array([[ 2., 3.],
[ 2., 3.]]),
array([[ 0., 0.],
[ 1., 1.]])]
greater()
numpy.greater(...)
y = greater(x1,x2)
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)
If the inputs are ndarrays, then np.greater is equivalent to '>'.
>>> a = np.array([4,2])
>>> b = np.array([2,2])
>>> a > b
array([ True, False], dtype=bool)
greater_equal()
numpy.greater_equal(...)
y = greater_equal(x1,x2)
Element-wise True if first array is greater or equal than second array.
Parameters
----------
x1, x2 : array_like
Input arrays.
Returns
-------
out : ndarray, bool
Output array.
See Also
--------
greater, less, less_equal, equal
Examples
--------
>>> np.greater_equal([4,2],[2,2])
array([ True, True], dtype=bool)
gumbel()
numpy.random.gumbel(...)
gumbel(loc=0.0, scale=1.0, size=None)
Gumbel distribution.
Draw samples from a Gumbel distribution with specified location (or mean)
and scale (or standard deviation).
The Gumbel (or Smallest Extreme Value (SEV) or the Smallest Extreme Value
Type I) distribution is one of a class of Generalized Extreme Value (GEV)
distributions used in modeling extreme value problems. The Gumbel is a
special case of the Extreme Value Type I distribution for maximums from
distributions with "exponential-like" tails, it may be derived by
considering a Gaussian process of measurements, and generating the pdf for
the maximum values from that set of measurements (see examples).
Parameters
----------
loc : float
The location of the mode of the distribution.
scale : float
The scale parameter of the distribution.
size : tuple of ints
Output shape. If the given shape is, e.g., ``(m, n, k)``, then
``m * n * k`` samples are drawn.
See Also
--------
scipy.stats.gumbel : probability density function,
distribution or cumulative density function, etc.
weibull, scipy.stats.genextreme
Notes
-----
The probability density for the Gumbel distribution is
.. math:: p(x) = \frac{e^{-(x - \mu)/ \beta}}{\beta} e^{ -e^{-(x - \mu)/
\beta}},
where :math:`\mu` is the mode, a location parameter, and :math:`\beta`
is the scale parameter.
The Gumbel (named for German mathematician Emil Julius Gumbel) was used
very early in the hydrology literature, for modeling the occurrence of
flood events. It is also used for modeling maximum wind speed and rainfall
rates. It is a "fat-tailed" distribution - the probability of an event in
the tail of the distribution is larger than if one used a Gaussian, hence
the surprisingly frequent occurrence of 100-year floods. Floods were
initially modeled as a Gaussian process, which underestimated the frequency
of extreme events.
It is one of a class of extreme value distributions, the Generalized
Extreme Value (GEV) distributions, which also includes the Weibull and
Frechet.
The function has a mean of :math:`\mu + 0.57721\beta` and a variance of
:math:`\frac{\pi^2}{6}\beta^2`.
References
----------
.. [1] Gumbel, E.J. (1958). Statistics of Extremes. Columbia University
Press.
.. [2] Reiss, R.-D. and Thomas M. (2001), Statistical Analysis of Extreme
Values, from Insurance, Finance, Hydrology and Other Fields,
Birkhauser Verlag, Basel: Boston : Berlin.
.. [3] Wikipedia, "Gumbel distribution",
http://en.wikipedia.org/wiki/Gumbel_distribution
Examples
--------
Draw samples from the distribution:
>>> mu, beta = 0, 0.1 # location and scale
>>> s = np.random.gumbel(mu, beta, 1000)
Display the histogram of the samples, along with
the probability density function:
>>> import matplotlib.pyplot as plt
>>> count, bins, ignored = plt.hist(s, 30, normed=True)
>>> plt.plot(bins, (1/beta)*np.exp(-(bins - mu)/beta)
... * np.exp( -np.exp( -(bins - mu) /beta) ),
... linewidth=2, color='r')
>>> plt.show()
Show how an extreme value distribution can arise from a Gaussian process
and compare to a Gaussian:
>>> means = []
>>> maxima = []
>>> for i in range(0,1000) :
... a = np.random.normal(mu, beta, 1000)
... means.append(a.mean())
... maxima.append(a.max())
>>> count, bins, ignored = plt.hist(maxima, 30, normed=True)
>>> beta = np.std(maxima)*np.pi/np.sqrt(6)
>>> mu = np.mean(maxima) - 0.57721*beta
>>> plt.plot(bins, (1/beta)*np.exp(-(bins - mu)/beta)
... * np.exp(-np.exp(-(bins - mu)/beta)),
... linewidth=2, color='r')
>>> plt.plot(bins, 1/(beta * np.sqrt(2 * np.pi))
... * np.exp(-(bins - mu)**2 / (2 * beta**2)),
... linewidth=2, color='g')
>>> plt.show()
>>> from numpy import *
>>> from numpy.random import *
>>> gumbel(loc=0.0,scale=1.0,size=(2,3))
array([[-1.25923601, 1.68758144, 1.76620507],
[ 1.96820048, -0.21219499, 1.83579566]])
>>> from pylab import *
>>> hist(gumbel(0,1,(1000)), 50)
See also: random_sample, uniform, poisson, seed
hamming()
numpy.hamming(M)
Return the Hamming window.
The Hamming window is a taper formed by using a weighted cosine.
Parameters
----------
M : int
Number of points in the output window. If zero or less, an
empty array is returned.
Returns
-------
out : ndarray
The window, normalized to one (the value one
appears only if the number of samples is odd).
See Also
--------
bartlett, blackman, hanning, kaiser
Notes
-----
The Hamming window is defined as
.. math:: w(n) = 0.54 + 0.46cos\left(\frac{2\pi{n}}{M-1}\right)
\qquad 0 \leq n \leq M-1
The Hamming was named for R. W. Hamming, an associate of J. W. Tukey and
is described in Blackman and Tukey. It was recommended for smoothing the
truncated autocovariance function in the time domain.
Most references to the Hamming 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.
References
----------
.. [1] Blackman, R.B. and Tukey, J.W., (1958) The measurement of power
spectra, Dover Publications, New York.
.. [2] E.R. Kanasewich, "Time Sequence Analysis in Geophysics", The
University of Alberta Press, 1975, pp. 109-110.
.. [3] Wikipedia, "Window function",
http://en.wikipedia.org/wiki/Window_function
.. [4] W.H. Press, B.P. Flannery, S.A. Teukolsky, and W.T. Vetterling,
"Numerical Recipes", Cambridge University Press, 1986, page 425.
Examples
--------
>>> from numpy import hamming
>>> hamming(12)
array([ 0.08 , 0.15302337, 0.34890909, 0.60546483, 0.84123594,
0.98136677, 0.98136677, 0.84123594, 0.60546483, 0.34890909,
0.15302337, 0.08 ])
Plot the window and the frequency response:
>>> from numpy import clip, log10, array, hamming
>>> from scipy.fftpack import fft, fftshift
>>> import matplotlib.pyplot as plt
>>> window = hamming(51)
>>> plt.plot(window)
>>> plt.title("Hamming 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 Hamming window")
>>> plt.ylabel("Magnitude [dB]")
>>> plt.xlabel("Normalized frequency [cycles per sample]")
>>> plt.axis('tight'); plt.show()
hanning()
numpy.hanning(M)
Return the Hanning window.
The Hanning window is a taper formed by using a weighted cosine.
Parameters
----------
M : int
Number of points in the output window. If zero or less, an
empty array is returned.
Returns
-------
out : ndarray, shape(M,)
The window, normalized to one (the value one
appears only if `M` is odd).
See Also
--------
bartlett, blackman, hamming, kaiser
Notes
-----
The Hanning window is defined as
.. math:: w(n) = 0.5 - 0.5cos\left(\frac{2\pi{n}}{M-1}\right)
\qquad 0 \leq n \leq M-1
The Hanning was named for Julius van Hann, an Austrian meterologist. It is
also known as the Cosine Bell. Some authors prefer that it be called a
Hann window, to help avoid confusion with the very similar Hamming window.
Most references to the Hanning 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.
References
----------
.. [1] Blackman, R.B. and Tukey, J.W., (1958) The measurement of power
spectra, Dover Publications, New York.
.. [2] E.R. Kanasewich, "Time Sequence Analysis in Geophysics",
The University of Alberta Press, 1975, pp. 106-108.
.. [3] Wikipedia, "Window function",
http://en.wikipedia.org/wiki/Window_function
.. [4] W.H. Press, B.P. Flannery, S.A. Teukolsky, and W.T. Vetterling,
"Numerical Recipes", Cambridge University Press, 1986, page 425.
Examples
--------
>>> from numpy import hanning
>>> hanning(12)
array([ 0. , 0.07937323, 0.29229249, 0.57115742, 0.82743037,
0.97974649, 0.97974649, 0.82743037, 0.57115742, 0.29229249,
0.07937323, 0. ])
Plot the window and its frequency response:
>>> from numpy.fft import fft, fftshift
>>> import matplotlib.pyplot as plt
>>> window = np.hanning(51)
>>> plt.subplot(121)
>>> plt.plot(window)
>>> plt.title("Hann window")
>>> plt.ylabel("Amplitude")
>>> plt.xlabel("Sample")
>>> A = fft(window, 2048) / 25.5
>>> mag = abs(fftshift(A))
>>> freq = np.linspace(-0.5,0.5,len(A))
>>> response = 20*np.log10(mag)
>>> response = np.clip(response,-100,100)
>>> plt.subplot(122)
>>> plt.plot(freq, response)
>>> plt.title("Frequency response of the Hann window")
>>> plt.ylabel("Magnitude [dB]")
>>> plt.xlabel("Normalized frequency [cycles per sample]")
>>> plt.axis('tight'); plt.show()
histogram()
numpy.histogram(a, bins=10, range=None, normed=False, weights=None, new=None)
Compute the histogram of a set of data.
Parameters
----------
a : array_like
Input data.
bins : int or sequence of scalars, optional
If `bins` is an int, it defines the number of equal-width
bins in the given range (10, by default). If `bins` is a sequence,
it defines the bin edges, including the rightmost edge, allowing
for non-uniform bin widths.
range : (float, float), optional
The lower and upper range of the bins. If not provided, range
is simply ``(a.min(), a.max())``. Values outside the range are
ignored. Note that with `new` set to False, values below
the range are ignored, while those above the range are tallied
in the rightmost bin.
normed : bool, optional
If False, the result will contain the number of samples
in each bin. If True, the result is the value of the
probability *density* function at the bin, normalized such that
the *integral* over the range is 1. Note that the sum of the
histogram values will often not be equal to 1; it is not a
probability *mass* function.
weights : array_like, optional
An array of weights, of the same shape as `a`. Each value in `a`
only contributes its associated weight towards the bin count
(instead of 1). If `normed` is True, the weights are normalized,
so that the integral of the density over the range remains 1.
The `weights` keyword is only available with `new` set to True.
new : {None, True, False}, optional
Whether to use the new semantics for histogram:
* None : the new behaviour is used, and a warning is printed,
* True : the new behaviour is used and no warning is printed,
* False : the old behaviour is used and a message is printed
warning about future deprecation.
Returns
-------
hist : array
The values of the histogram. See `normed` and `weights` for a
description of the possible semantics.
bin_edges : array of dtype float
Return the bin edges ``(length(hist)+1)``.
With ``new=False``, return the left bin edges (``length(hist)``).
See Also
--------
histogramdd
Notes
-----
All but the last (righthand-most) bin is half-open. In other words, if
`bins` is::
[1, 2, 3, 4]
then the first bin is ``[1, 2)`` (including 1, but excluding 2) and the
second ``[2, 3)``. The last bin, however, is ``[3, 4]``, which *includes*
4.
Examples
--------
>>> np.histogram([1,2,1], bins=[0,1,2,3], new=True)
(array([0, 2, 1]), array([0, 1, 2, 3]))
>>> from numpy import *
>>> x = array([0.2, 6.4, 3.0, 1.6, 0.9, 2.3, 1.6, 5.7, 8.5, 4.0, 12.8])
>>> bins = array([0.0, 1.0, 2.5, 4.0, 10.0])
>>> N,bins = histogram(x,bins)
>>> N,bins
(array([2, 3, 1, 4, 1]), array([ 0. , 1. , 2.5, 4. , 10. ]))
>>> for n in range(len(bins)):
... if n < len(bins)-1:
... print "# ", N[n], "numbers fall into bin [", bins[n], ",", bins[n+1], "["
... else:
... print "# ", N[n], "numbers fall outside the bin range"
...
>>> N,bins = histogram(x,5,range=(0.0, 10.0))
>>> N,bins
(array([4, 2, 2, 1, 2]), array([ 0., 2., 4., 6., 8.]))
>>> N,bins = histogram(x,5,range=(0.0, 10.0), normed=True)
>>> N,bins
(array([ 0.18181818, 0.09090909, 0.09090909, 0.04545455, 0.09090909]), array([ 0., 2., 4., 6., 8.]))
See also: bincount, digitize
histogram2d()
numpy.histogram2d(x, y, bins=10, range=None, normed=False, weights=None)
Compute the bidimensional histogram of two data samples.
Parameters
----------
x : array_like, shape(N,)
A sequence of values to be histogrammed along the first dimension.
y : array_like, shape(M,)
A sequence of values to be histogrammed along the second dimension.
bins : int or [int, int] or array-like or [array, array], optional
The bin specification:
* the number of bins for the two dimensions (nx=ny=bins),
* the number of bins in each dimension (nx, ny = bins),
* the bin edges for the two dimensions (x_edges=y_edges=bins),
* the bin edges in each dimension (x_edges, y_edges = bins).
range : array_like, shape(2,2), optional
The leftmost and rightmost edges of the bins along each dimension
(if not specified explicitly in the `bins` parameters):
[[xmin, xmax], [ymin, ymax]]. All values outside of this range will be
considered outliers and not tallied in the histogram.
normed : boolean, optional
If False, returns the number of samples in each bin. If True, returns
the bin density, ie, the bin count divided by the bin area.
weights : array-like, shape(N,), optional
An array of values `w_i` weighing each sample `(x_i, y_i)`. Weights are
normalized to 1 if normed is True. If normed is False, the values of the
returned histogram are equal to the sum of the weights belonging to the
samples falling into each bin.
Returns
-------
H : ndarray, shape(nx, ny)
The bidimensional histogram of samples x and y. Values in x are
histogrammed along the first dimension and values in y are histogrammed
along the second dimension.
xedges : ndarray, shape(nx,)
The bin edges along the first dimension.
yedges : ndarray, shape(ny,)
The bin edges along the second dimension.
See Also
--------
histogram: 1D histogram
histogramdd: Multidimensional histogram
Notes
-----
When normed is True, then the returned histogram is the sample density,
defined such that:
.. math::
\sum_{i=0}^{nx-1} \sum_{j=0}^{ny-1} H_{i,j} \Delta x_i \Delta y_j = 1
where :math:`H` is the histogram array and :math:`\Delta x_i \Delta y_i`
the area of bin :math:`{i,j}`.
Please note that the histogram does not follow the cartesian convention
where `x` values are on the abcissa and `y` values on the ordinate axis.
Rather, `x` is histogrammed along the first dimension of the array
(vertical), and `y` along the second dimension of the array (horizontal).
This ensures compatibility with `histogrammdd`.
Examples
--------
>>> x,y = np.random.randn(2,100)
>>> H, xedges, yedges = np.histogram2d(x, y, bins = (5, 8))
>>> H.shape, xedges.shape, yedges.shape
((5,8), (6,), (9,))
histogramdd()
numpy.histogramdd(sample, bins=10, range=None, normed=False, weights=None)
Compute the multidimensional histogram of some data.
Parameters
----------
sample : array_like
Data to histogram passed as a sequence of D arrays of length N, or
as an (N,D) array.
bins : sequence or int, optional
The bin specification:
* A sequence of arrays describing the bin edges along each dimension.
* The number of bins for each dimension (nx, ny, ... =bins)
* The number of bins for all dimensions (nx=ny=...=bins).
range : sequence, optional
A sequence of lower and upper bin edges to be used if the edges are
not given explicitely in `bins`. Defaults to the minimum and maximum
values along each dimension.
normed : boolean, optional
If False, returns the number of samples in each bin. If True, returns
the bin density, ie, the bin count divided by the bin hypervolume.
weights : array_like (N,), optional
An array of values `w_i` weighing each sample `(x_i, y_i, z_i, ...)`.
Weights are normalized to 1 if normed is True. If normed is False, the
values of the returned histogram are equal to the sum of the weights
belonging to the samples falling into each bin.
Returns
-------
H : ndarray
The multidimensional histogram of sample x. See normed and weights for
the different possible semantics.
edges : list
A list of D arrays describing the bin edges for each dimension.
See Also
--------
histogram: 1D histogram
histogram2d: 2D histogram
Examples
--------
>>> r = np.random.randn(100,3)
>>> H, edges = np.histogramdd(r, bins = (5, 8, 4))
>>> H.shape, edges[0].size, edges[1].size, edges[2].size
((5,8,4), 6, 9, 5)
hsplit()
numpy.hsplit(ary, indices_or_sections)
Split array into multiple sub-arrays horizontally.
Please refer to the `numpy.split` documentation. `hsplit` is
equivalent to `numpy.split` with ``axis = 1``.
See Also
--------
split : Split array into multiple sub-arrays.
Examples
--------
>>> x = np.arange(16.0).reshape(4, 4)
>>> np.hsplit(x, 2)
<BLANKLINE>
[array([[ 0., 1.],
[ 4., 5.],
[ 8., 9.],
[ 12., 13.]]),
array([[ 2., 3.],
[ 6., 7.],
[ 10., 11.],
[ 14., 15.]])]
>>> np.hsplit(x, array([3, 6]))
<BLANKLINE>
[array([[ 0., 1., 2.],
[ 4., 5., 6.],
[ 8., 9., 10.],
[ 12., 13., 14.]]),
array([[ 3.],
[ 7.],
[ 11.],
[ 15.]]),
array([], dtype=float64)]
>>> from numpy import *
>>> a = array([[1,2,3,4],[5,6,7,8]])
>>> hsplit(a,2)
[array([[1, 2],
[5, 6]]), array([[3, 4],
[7, 8]])]
>>> hsplit(a,[1,2])
[array([[1],
[5]]), array([[2],
[6]]), array([[3, 4],
[7, 8]])]
See also: split, array_split, dsplit, vsplit, hstack
hstack()
numpy.hstack(tup)
Stack arrays in sequence horizontally (column wise)
Take a sequence of arrays and stack them horizontally to make
a single array. Rebuild arrays divided by ``hsplit``.
Parameters
----------
tup : sequence of ndarrays
All arrays must have the same shape along all but the second axis.
Returns
-------
stacked : ndarray
The array formed by stacking the given arrays.
See Also
--------
vstack : Stack along first axis.
dstack : Stack along third axis.
concatenate : Join arrays.
hsplit : Split array along second axis.
Notes
-----
Equivalent to ``np.concatenate(tup, axis=1)``
Examples
--------
>>> a = np.array((1,2,3))
>>> b = np.array((2,3,4))
>>> np.hstack((a,b))
array([1, 2, 3, 2, 3, 4])
>>> a = np.array([[1],[2],[3]])
>>> b = np.array([[2],[3],[4]])
>>> np.hstack((a,b))
array([[1, 2],
[2, 3],
[3, 4]])
>>> from numpy import *
>>> a =array([[1],[2]])
>>> b = array([[3,4],[5,6]])
>>> hstack((a,b,a))
array([[1, 3, 4, 1],
[2, 5, 6, 2]])
See also: column_stack, concatenate, dstack, vstack, hsplit
hypot()
numpy.hypot(...)
y = hypot(x1,x2)
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
Hypotenuse of the triangle: sqrt(x**2 + y**2)
Examples
--------
>>> np.hypot(3,4)
5.0
>>> from numpy import *
>>> hypot(3.,4.)
5.0
>>> z = array([2+3j, 3+4j])
>>> hypot(z.real, z.imag)
array([ 3.60555128, 5. ])
See also: angle, abs
i0()
numpy.i0(x)
Modified Bessel function of the first kind, order 0.
Usually denoted :math:`I_0`.
Parameters
----------
x : array_like, dtype float or complex
Argument of the Bessel function.
Returns
-------
out : ndarray, shape z.shape, dtype z.dtype
The modified Bessel function evaluated at the elements of `x`.
See Also
--------
scipy.special.iv, scipy.special.ive
References
----------
.. [1] M. Abramowitz and I.A. Stegun, "Handbook of Mathematical Functions",
10th printing, 1964, pp. 374. http://www.math.sfu.ca/~cbm/aands/
.. [2] Wikipedia, "Bessel function",
http://en.wikipedia.org/wiki/Bessel_function
Examples
--------
>>> np.i0([0.])
array(1.0)
>>> np.i0([0., 1. + 2j])
array([ 1.00000000+0.j , 0.18785373+0.64616944j])
identity()
numpy.identity(n, dtype=None)
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.]])
>>> from numpy import *
>>> identity(3,float)
array([[ 1., 0., 0.],
[ 0., 1., 0.],
[ 0., 0., 1.]])
See also: empty, eye, ones, zeros
ifft
>>> from numpy import *
>>> from numpy.fft import *
>>> signal = array([-2., 8., -6., 4., 1., 0., 3., 5.])
>>> fourier = fft(signal)
>>> ifft(fourier)
array([-2. +0.00000000e+00j, 8. +1.51410866e-15j, -6. +3.77475828e-15j,
4. +2.06737026e-16j, 1. +0.00000000e+00j, 0. -1.92758271e-15j,
3. -3.77475828e-15j, 5. +2.06737026e-16j])
>>>
>>> allclose(signal.astype(complex), ifft(fft(signal)))
True
>>>
>>> N = len(fourier)
>>> signal = empty(N,complex)
>>> for k in range(N):
... signal[k] = sum(fourier * exp(+1j*2*pi*k*arange(N)/N)) / N
See also: fft, fftfreq, fftshift
imag() or .imag
numpy.imag(val)
Return the imaginary part of array.
Parameters
----------
val : array_like
Input array.
Returns
-------
out : ndarray, real or int
Real part of each element, same shape as `val`.
ndarray.imag
The imaginary part of the array.
Examples
--------
>>> x = np.sqrt([1+0j, 0+1j])
>>> x.imag
array([ 0. , 0.70710678])
>>> x.imag.dtype
dtype('float64')
>>> from numpy import *
>>> a = array([1+2j,3+4j,5+6j])
>>> a.imag
array([ 2., 4., 6.])
>>> a.imag = 9
>>> a
array([ 1.+9.j, 3.+9.j, 5.+9.j])
>>> a.imag = array([9,8,7])
>>> a
array([ 1.+9.j, 3.+8.j, 5.+7.j])
See also: real, angle
index_exp
numpy.index_exp
A nicer way to build up index tuples for arrays.
For any index combination, including slicing and axis insertion,
'a[indices]' is the same as 'a[index_exp[indices]]' for any
array 'a'. However, 'index_exp[indices]' can be used anywhere
in Python code and returns a tuple of slice objects that can be
used in the construction of complex index expressions.
>>> from numpy import *
>>> myslice = index_exp[2:4,...,4,::-1]
>>> print myslice
(slice(2, 4, None), Ellipsis, 4, slice(None, None, -1))
See also: slice, s_
indices()
numpy.indices(dimensions, dtype=<type 'int'>)
Return an array representing the indices of a grid.
Compute an array where the subarrays contain index values 0,1,...
varying only along the corresponding axis.
Parameters
----------
dimensions : sequence of ints
The shape of the grid.
dtype : optional
Data_type of the result.
Returns
-------
grid : ndarray
The array of grid indices,
``grid.shape = (len(dimensions),) + tuple(dimensions)``.
See Also
--------
mgrid, meshgrid
Notes
-----
The output shape is obtained by prepending the number of dimensions
in front of the tuple of dimensions, i.e. if `dimensions` is a tuple
``(r0, ..., rN-1)`` of length ``N``, the output shape is
``(N,r0,...,rN-1)``.
The subarrays ``grid[k]`` contains the N-D array of indices along the
``k-th`` axis. Explicitly::
grid[k,i0,i1,...,iN-1] = ik
Examples
--------
>>> grid = np.indices((2,3))
>>> grid.shape
(2,2,3)
>>> grid[0] # row indices
array([[0, 0, 0],
[1, 1, 1]])
>>> grid[1] # column indices
array([[0, 1, 2],
[0, 1, 2]])
>>> from numpy import *
>>> indices((2,3))
array([[[0, 0, 0],
[1, 1, 1]],
[[0, 1, 2],
[0, 1, 2]]])
>>> a = array([ [ 0, 1, 2, 3, 4],
... [10,11,12,13,14],
... [20,21,22,23,24],
... [30,31,32,33,34] ])
>>> i,j = indices((2,3))
>>> a[i,j]
array([[ 0, 1, 2],
[10, 11, 12]])
See also: mgrid, [], ix_, slice
inf
numpy.inf
float(x) -> floating point number
Convert a string or number to a floating point number, if possible.
>>> from numpy import *
>>> exp(array([1000.]))
array([ inf])
>>> x = array([2,-inf,1,inf])
>>> isfinite(x)
array([True, False, True, False], dtype=bool)
>>> isinf(x)
array([False, True, False, True], dtype=bool)
>>> isposinf(x)
array([False, False, False, True], dtype=bool)
>>> isneginf(x)
array([False, True, False, False], dtype=bool)
>>> nan_to_num(x)
array([ 2.00000000e+000, -1.79769313e+308, 1.00000000e+000,
1.79769313e+308])
See also: nan, finfo
info() or .info
numpy.info(object=None, maxwidth=76, output=<open file '<stdout>', mode 'w' at 0x00AFF068>, toplevel='numpy')
Get help information for a function, class, or module.
Parameters
----------
object : optional
Input object to get information about.
maxwidth : int, optional
Printing width.
output : file like object open for writing, optional
Write into file like object.
toplevel : string, optional
Start search at this level.
Examples
--------
>>> np.info(np.polyval) # doctest: +SKIP
polyval(p, x)
Evaluate the polymnomial p at x.
...
inner()
numpy.inner(...)
innerproduct(a,b)
Returns the inner product of a and b for arrays of floating point types.
Like the generic NumPy equivalent the product sum is over
the last dimension of a and b.
NB: The first argument is not conjugated.
>>> from numpy import *
>>> x = array([1,2,3])
>>> y = array([10,20,30])
>>> inner(x,y)
140
See also: cross, outer, dot
insert()
numpy.insert(arr, obj, values, axis=None)
Insert values along the given axis before the given indices.
Parameters
----------
arr : array_like
Input array.
obj : {integer, slice, integer array_like}
Insert `values` before `obj` indices.
values :
Values to insert into `arr`.
axis : int, optional
Axis along which to insert `values`. If `axis` is None then ravel
`arr` first.
Examples
--------
>>> a = np.array([[1,2,3],
... [4,5,6],
... [7,8,9]])
>>> np.insert(a, [1,2], [[4],[5]], axis=0)
array([[1, 2, 3],
[4, 4, 4],
[4, 5, 6],
[5, 5, 5],
[7, 8, 9]])
>>> from numpy import *
>>> a = array([10,20,30,40])
>>> insert(a,[1,3],50)
array([10, 50, 20, 30, 50, 40])
>>> insert(a,[1,3],[50,60])
array([10, 50, 20, 30, 60, 40])
>>> a = array([[10,20,30],[40,50,60],[70,80,90]])
>>> insert(a, [1,2], 100, axis=0)
array([[ 10, 20, 30],
[100, 100, 100],
[ 40, 50, 60],
[100, 100, 100],
[ 70, 80, 90]])
>>> insert(a, [0,1], [[100],[200]], axis=0)
array([[100, 100, 100],
[ 10, 20, 30],
[200, 200, 200],
[ 40, 50, 60],
[ 70, 80, 90]])
>>> insert(a, [0,1], [100,200], axis=1)
array([[100, 10, 200, 20, 30],
[100, 40, 200, 50, 60],
[100, 70, 200, 80, 90]])
See also: delete, append
int_asbuffer()
numpy.int_asbuffer(...)
interp()
numpy.interp(x, xp, fp, left=None, right=None)
One-dimensional linear interpolation.
Returns the one-dimensional piecewise linear interpolant to a function
with given values at discrete data-points.
Parameters
----------
x : array_like
The x-coordinates of the interpolated values.
xp : 1-D sequence of floats
The x-coordinates of the data points, must be increasing.
fp : 1-D sequence of floats
The y-coordinates of the data points, same length as `xp`.
left : float, optional
Value to return for `x < xp[0]`, default is `fp[0]`.
right : float, optional
Value to return for `x > xp[-1]`, defaults is `fp[-1]`.
Returns
-------
y : {float, ndarray}
The interpolated values, same shape as `x`.
Raises
------
ValueError
If `xp` and `fp` have different length
Notes
-----
Does not check that the x-coordinate sequence `xp` is increasing.
If `xp` is not increasing, the results are nonsense.
A simple check for increasingness is::
np.all(np.diff(xp) > 0)
Examples
--------
>>> xp = [1, 2, 3]
>>> fp = [3, 2, 0]
>>> np.interp(2.5, xp, fp)
1.0
>>> np.interp([0, 1, 1.5, 2.72, 3.14], xp, fp)
array([ 3. , 3. , 2.5, 0.56, 0. ])
>>> UNDEF = -99.0
>>> np.interp(3.14, xp, fp, right=UNDEF)
-99.0
Plot an interpolant to the sine function:
>>> x = np.linspace(0, 2*np.pi, 10)
>>> y = np.sin(x)
>>> xvals = np.linspace(0, 2*np.pi, 50)
>>> yinterp = np.interp(xvals, x, y)
>>> import matplotlib.pyplot as plt
>>> plt.plot(x, y, 'o')
>>> plt.plot(xvals, yinterp, '-x')
>>> plt.show()
intersect1d()
numpy.intersect1d(ar1, ar2)
Intersection returning repeated or unique elements common to both arrays.
Parameters
----------
ar1,ar2 : array_like
Input arrays.
Returns
-------
out : ndarray, shape(N,)
Sorted 1D array of common elements with repeating elements.
See Also
--------
intersect1d_nu : Returns only unique common elements.
numpy.lib.arraysetops : Module with a number of other functions for
performing set operations on arrays.
Examples
--------
>>> np.intersect1d([1,3,3],[3,1,1])
array([1, 1, 3, 3])
intersect1d_nu()
numpy.intersect1d_nu(ar1, ar2)
Intersection returning unique elements common to both arrays.
Parameters
----------
ar1,ar2 : array_like
Input arrays.
Returns
-------
out : ndarray, shape(N,)
Sorted 1D array of common and unique elements.
See Also
--------
intersect1d : Returns repeated or unique common elements.
numpy.lib.arraysetops : Module with a number of other functions for
performing set operations on arrays.
Examples
--------
>>> np.intersect1d_nu([1,3,3],[3,1,1])
array([1, 3])
inv()
numpy.linalg.inv(a)
Compute the inverse of a matrix.
Parameters
----------
a : array_like, shape (M, M)
Matrix to be inverted
Returns
-------
ainv : ndarray, shape (M, M)
Inverse of the matrix `a`
Raises
------
LinAlgError
If `a` is singular or not square.
Examples
--------
>>> a = np.array([[1., 2.], [3., 4.]])
>>> np.linalg.inv(a)
array([[-2. , 1. ],
[ 1.5, -0.5]])
>>> np.dot(a, np.linalg.inv(a))
array([[ 1., 0.],
[ 0., 1.]])
>>> from numpy import *
>>> from numpy.linalg import inv
>>> a = array([[3,1,5],[1,0,8],[2,1,4]])
>>> print a
[[3 1 5]
[1 0 8]
[2 1 4]]
>>> inva = inv(a)
>>> print inva
[[ 1.14285714 -0.14285714 -1.14285714]
[-1.71428571 -0.28571429 2.71428571]
[-0.14285714 0.14285714 0.14285714]]
>>> dot(a,inva)
array([[ 1.00000000e-00, 2.77555756e-17, 3.60822483e-16],
[ 0.00000000e+00, 1.00000000e+00, 0.00000000e+00],
[ -1.11022302e-16, 0.00000000e+00, 1.00000000e+00]])
See also: solve, pinv
invert()
numpy.invert(...)
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)
ipmt()
numpy.ipmt(rate, per, nper, pv, fv=0.0, when='end')
Not implemented. Compute the payment portion for loan interest.
Parameters
----------
rate : scalar or array_like of shape(M, )
Rate of interest as decimal (not per cent) per period
per : scalar or array_like of shape(M, )
Interest paid against the loan changes during the life or the loan.
The `per` is the payment period to calculate the interest amount.
nper : scalar or array_like of shape(M, )
Number of compounding periods
pv : scalar or array_like of shape(M, )
Present value
fv : scalar or array_like of shape(M, ), optional
Future value
when : {{'begin', 1}, {'end', 0}}, {string, int}, optional
When payments are due ('begin' (1) or 'end' (0)).
Defaults to {'end', 0}.
Returns
-------
out : ndarray
Interest portion of payment. If all input is scalar, returns a scalar
float. If any input is array_like, returns interest payment for each
input element. If multiple inputs are array_like, they all must have
the same shape.
See Also
--------
ppmt, pmt, pv
Notes
-----
The total payment is made up of payment against principal plus interest.
``pmt = ppmt + ipmt``
irr()
numpy.irr(values)
Return the Internal Rate of Return (IRR).
This is the rate of return that gives a net present value of 0.0.
Parameters
----------
values : array_like, shape(N,)
Input cash flows per time period. At least the first value would be
negative to represent the investment in the project.
Returns
-------
out : float
Internal Rate of Return for periodic input values.
Examples
--------
>>> np.irr([-100, 39, 59, 55, 20])
0.2809484211599611
iscomplex()
numpy.iscomplex(x)
Return a bool array, True if element is complex (non-zero imaginary part).
For scalars, return a boolean.
Parameters
----------
x : array_like
Input array.
Returns
-------
out : ndarray, bool
Output array.
Examples
--------
>>> x = np.array([1,2,3.j])
>>> np.iscomplex(x)
array([False, False, True], dtype=bool)
>>> import numpy as np
>>> a = np.array([1,2,3.j])
>>> np.iscomplex(a)
array([False, False, True], dtype=bool)
iscomplexobj()
numpy.iscomplexobj(x)
Return True if x is a complex type or an array of complex numbers.
Unlike iscomplex(x), complex(3.0) is considered a complex object.
>>> import numpy as np
>>> a = np.array([1,2,3.j])
>>> np.iscomplexobj(a)
True
>>> a = np.array([1,2,3])
>>> np.iscomplexobj(a)
False
>>> a = np.array([1,2,3], dtype=np.complex)
>>> np.iscomplexobj(a)
True
isfinite()
numpy.isfinite(...)
y = isfinite(x)
Returns True for each element that is a finite number.
Shows which elements of the input are finite (not infinity or not
Not a Number).
Parameters
----------
x : array_like
Input values.
y : array_like, optional
A boolean array with the same shape and type as `x` to store the result.
Returns
-------
y : ndarray, bool
For scalar input data, the result is a new numpy boolean with value True
if the input data is finite; otherwise the value is False (input is
either positive infinity, negative infinity or Not a Number).
For array input data, the result is an numpy boolean array with the same
dimensions as the input and the values are True if the corresponding
element of the input is finite; otherwise the values are False (element
is either positive infinity, negative infinity or Not a Number). If the
second argument is supplied then an numpy integer array is returned with
values 0 or 1 corresponding to False and True, respectively.
See Also
--------
isinf : Shows which elements are negative or negative infinity.
isneginf : Shows which elements are negative infinity.
isposinf : Shows which elements are positive infinity.
isnan : Shows which elements are Not a Number (NaN).
Notes
-----
Not a Number, positive infinity and negative infinity are considered
to be non-finite.
Numpy uses the IEEE Standard for Binary Floating-Point for Arithmetic
(IEEE 754). This means that Not a Number is not equivalent to infinity.
Also that positive infinity is not equivalent to negative infinity. But
infinity is equivalent to positive infinity.
Errors result if second argument is also supplied with scalar input or
if first and second arguments have different shapes.
Examples
--------
>>> np.isfinite(1)
True
>>> np.isfinite(0)
True
>>> np.isfinite(np.nan)
False
>>> np.isfinite(np.inf)
False
>>> np.isfinite(np.NINF)
False
>>> np.isfinite([np.log(-1.),1.,np.log(0)])
array([False, True, False], dtype=bool)
>>> x=np.array([-np.inf, 0., np.inf])
>>> y=np.array([2,2,2])
>>> np.isfinite(x,y)
array([0, 1, 0])
>>> y
array([0, 1, 0])
isfortran()
numpy.isfortran(a)
Returns True if array is arranged in Fortran-order and dimension > 1.
Parameters
----------
a : ndarray
Input array to test.
isinf()
numpy.isinf(...)
y = isinf(x)
Shows which elements of the input are positive or negative infinity.
Returns a numpy boolean scalar or array resulting from an element-wise test
for positive or negative infinity.
Parameters
----------
x : array_like
input values
y : array_like, optional
An array with the same shape as `x` to store the result.
Returns
-------
y : {ndarray, bool}
For scalar input data, the result is a new numpy boolean with value True
if the input data is positive or negative infinity; otherwise the value
is False.
For array input data, the result is an numpy boolean array with the same
dimensions as the input and the values are True if the corresponding
element of the input is positive or negative infinity; otherwise the
values are False. If the second argument is supplied then an numpy
integer array is returned with values 0 or 1 corresponding to False and
True, respectively.
See Also
--------
isneginf : Shows which elements are negative infinity.
isposinf : Shows which elements are positive infinity.
isnan : Shows which elements are Not a Number (NaN).
isfinite: Shows which elements are not: Not a number, positive and
negative infinity
Notes
-----
Numpy uses the IEEE Standard for Binary Floating-Point for Arithmetic
(IEEE 754). This means that Not a Number is not equivalent to infinity.
Also that positive infinity is not equivalent to negative infinity. But
infinity is equivalent to positive infinity.
Errors result if second argument is also supplied with scalar input or
if first and second arguments have different shapes.
Numpy's definitions for positive infinity (PINF) and negative infinity
(NINF) may be change in the future versions.
Examples
--------
>>> np.isinf(np.inf)
True
>>> np.isinf(np.nan)
False
>>> np.isinf(np.NINF)
True
>>> np.isinf([np.inf, -np.inf, 1.0, np.nan])
array([ True, True, False, False], dtype=bool)
>>> x=np.array([-np.inf, 0., np.inf])
>>> y=np.array([2,2,2])
>>> np.isinf(x,y)
array([1, 0, 1])
>>> y
array([1, 0, 1])
isnan()
numpy.isnan(...)
y = isnan(x)
Returns a numpy boolean scalar or array resulting from an element-wise test
for Not a Number (NaN).
Parameters
----------
x : array_like
input data.
Returns
-------
y : {ndarray, bool}
For scalar input data, the result is a new numpy boolean with value True
if the input data is NaN; otherwise the value is False.
For array input data, the result is an numpy boolean array with the same
dimensions as the input and the values are True if the corresponding
element of the input is Not a Number; otherwise the values are False.
See Also
--------
isinf : Tests for infinity.
isneginf : Tests for negative infinity.
isposinf : Tests for positive infinity.
isfinite : Shows which elements are not: Not a number, positive infinity
and negative infinity
Notes
-----
Numpy uses the IEEE Standard for Binary Floating-Point for Arithmetic
(IEEE 754). This means that Not a Number is not equivalent to infinity.
Examples
--------
>>> np.isnan(np.nan)
True
>>> np.isnan(np.inf)
False
>>> np.isnan([np.log(-1.),1.,np.log(0)])
array([ True, False, False], dtype=bool)
isneginf()
numpy.isneginf(x, y=None)
Return True where x is -infinity, and False otherwise.
Parameters
----------
x : array_like
The input array.
y : array_like
A boolean array with the same shape as `x` to store the result.
Returns
-------
y : ndarray
A boolean array where y[i] = True only if x[i] = -Inf.
See Also
--------
isposinf, isfinite
Examples
--------
>>> np.isneginf([-np.inf, 0., np.inf])
array([ True, False, False], dtype=bool)
isposinf()
numpy.isposinf(x, y=None)
Shows which elements of the input are positive infinity.
Returns a numpy array resulting from an element-wise test for positive
infinity.
Parameters
----------
x : array_like
The input array.
y : array_like
A boolean array with the same shape as `x` to store the result.
Returns
-------
y : ndarray
A numpy boolean array with the same dimensions as the input.
If second argument is not supplied then a numpy boolean array is returned
with values True where the corresponding element of the input is positive
infinity and values False where the element of the input is not positive
infinity.
If second argument is supplied then an numpy integer array is returned
with values 1 where the corresponding element of the input is positive
positive infinity.
See Also
--------
isinf : Shows which elements are negative or positive infinity.
isneginf : Shows which elements are negative infinity.
isnan : Shows which elements are Not a Number (NaN).
isfinite: Shows which elements are not: Not a number, positive and
negative infinity
Notes
-----
Numpy uses the IEEE Standard for Binary Floating-Point for Arithmetic
(IEEE 754). This means that Not a Number is not equivalent to infinity.
Also that positive infinity is not equivalent to negative infinity. But
infinity is equivalent to positive infinity.
Errors result if second argument is also supplied with scalar input or
if first and second arguments have different shapes.
Numpy's definitions for positive infinity (PINF) and negative infinity
(NINF) may be change in the future versions.
Examples
--------
>>> np.isposinf(np.PINF)
array(True, dtype=bool)
>>> np.isposinf(np.inf)
array(True, dtype=bool)
>>> np.isposinf(np.NINF)
array(False, dtype=bool)
>>> np.isposinf([-np.inf, 0., np.inf])
array([False, False, True], dtype=bool)
>>> x=np.array([-np.inf, 0., np.inf])
>>> y=np.array([2,2,2])
>>> np.isposinf(x,y)
array([1, 0, 0])
>>> y
array([1, 0, 0])
isreal()
numpy.isreal(x)
Returns a bool array where True if the corresponding input element is real.
True if complex part is zero.
Parameters
----------
x : array_like
Input array.
Returns
-------
out : ndarray, bool
Boolean array of same shape as `x`.
Examples
--------
>>> np.isreal([1+1j, 1+0j, 4.5, 3, 2, 2j])
>>> array([False, True, True, True, True, False], dtype=bool)
isrealobj()
numpy.isrealobj(x)
Return True if x is not a complex type.
Unlike isreal(x), complex(3.0) is considered a complex object.
isscalar()
numpy.isscalar(num)
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
issctype()
numpy.issctype(rep)
Determines whether the given object represents
a numeric array type.
issubclass_()
numpy.issubclass_(arg1, arg2)
issubdtype()
numpy.issubdtype(arg1, arg2)
Returns True if first argument is a typecode lower/equal in type hierarchy.
Parameters
----------
arg1 : dtype_like
dtype or string representing a typecode.
arg2 : dtype_like
dtype or string representing a typecode.
See Also
--------
numpy.core.numerictypes : Overview of numpy type hierarchy.
Examples
--------
>>> np.issubdtype('S1', str)
True
>>> np.issubdtype(np.float64, np.float32)
False
issubsctype()
numpy.issubsctype(arg1, arg2)
item()
ndarray.item(...)
a.item()
Copy the first element of array to a standard Python scalar and return
it. The array must be of size one.
>>> from numpy import *
>>> a = array([5])
>>> type(a[0])
<type 'numpy.int32'>
>>> a.item()
5
>>> type(a.item())
<type 'int'>
>>> b = array([2,3,4])
>>> b[1].item()
3
>>> type(b[1].item())
<type 'int'>
>>> b.item(2)
4
>>> type(b.item(2))
<type 'int'>
>>> type(b[2])
<type 'numpy.int32'>
See also: []
itemset()
ndarray.itemset(...)
iterable()
numpy.iterable(y)
ix_()
numpy.ix_(*args)
Construct an open mesh from multiple sequences.
This function takes n 1-d sequences and returns n outputs with n
dimensions each such that the shape is 1 in all but one dimension and
the dimension with the non-unit shape value cycles through all n
dimensions.
Using ix_() one can quickly construct index arrays that will index
the cross product.
a[ix_([1,3,7],[2,5,8])] returns the array
a[1,2] a[1,5] a[1,8]
a[3,2] a[3,5] a[3,8]
a[7,2] a[7,5] a[7,8]
>>> from numpy import *
>>> a = arange(9).reshape(3,3)
>>> print a
[[0 1 2]
[3 4 5]
[6 7 8]]
>>> indices = ix_([0,1,2],[1,2,0])
>>> print indices
(array([[0],
[1],
[2]]), array([[1, 2, 0]]))
>>> print a[indices]
[[1 2 0]
[4 5 3]
[7 8 6]]
>>>
>>>
...
...
...
See also: [], indices, cross, outer
kaiser()
numpy.kaiser(M, beta)
Return the Kaiser window.
The Kaiser window is a taper formed by using a Bessel function.
Parameters
----------
M : int
Number of points in the output window. If zero or less, an
empty array is returned.
beta : float
Shape parameter for window.
Returns
-------
out : array
The window, normalized to one (the value one
appears only if the number of samples is odd).
See Also
--------
bartlett, blackman, hamming, hanning
Notes
-----
The Kaiser window is defined as
.. math:: w(n) = I_0\left( \beta \sqrt{1-\frac{4n^2}{(M-1)^2}}
\right)/I_0(\beta)
with
.. math:: \quad -\frac{M-1}{2} \leq n \leq \frac{M-1}{2},
where :math:`I_0` is the modified zeroth-order Bessel function.
The Kaiser was named for Jim Kaiser, who discovered a simple approximation
to the DPSS window based on Bessel functions.
The Kaiser window is a very good approximation to the Digital Prolate
Spheroidal Sequence, or Slepian window, which is the transform which
maximizes the energy in the main lobe of the window relative to total
energy.
The Kaiser can approximate many other windows by varying the beta
parameter.
==== =======================
beta Window shape
==== =======================
0 Rectangular
5 Similar to a Hamming
6 Similar to a Hanning
8.6 Similar to a Blackman
==== =======================
A beta value of 14 is probably a good starting point. Note that as beta
gets large, the window narrows, and so the number of samples needs to be
large enough to sample the increasingly narrow spike, otherwise nans will
get returned.
Most references to the Kaiser 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.
References
----------
.. [1] J. F. Kaiser, "Digital Filters" - Ch 7 in "Systems analysis by
digital computer", Editors: F.F. Kuo and J.F. Kaiser, p 218-285.
John Wiley and Sons, New York, (1966).
.. [2] E.R. Kanasewich, "Time Sequence Analysis in Geophysics", The
University of Alberta Press, 1975, pp. 177-178.
.. [3] Wikipedia, "Window function",
http://en.wikipedia.org/wiki/Window_function
Examples
--------
>>> from numpy import kaiser
>>> kaiser(12, 14)
array([ 7.72686684e-06, 3.46009194e-03, 4.65200189e-02,
2.29737120e-01, 5.99885316e-01, 9.45674898e-01,
9.45674898e-01, 5.99885316e-01, 2.29737120e-01,
4.65200189e-02, 3.46009194e-03, 7.72686684e-06])
Plot the window and the frequency response:
>>> from numpy import clip, log10, array, kaiser
>>> from scipy.fftpack import fft, fftshift
>>> import matplotlib.pyplot as plt
>>> window = kaiser(51, 14)
>>> plt.plot(window)
>>> plt.title("Kaiser 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 Kaiser window")
>>> plt.ylabel("Magnitude [dB]")
>>> plt.xlabel("Normalized frequency [cycles per sample]")
>>> plt.axis('tight'); plt.show()
kron()
numpy.kron(a, b)
Kronecker product of two arrays.
Computes the Kronecker product, a composite array made of blocks of the
second array scaled by the first.
Parameters
----------
a, b : array_like
Returns
-------
out : ndarray
See Also
--------
outer : The outer product
Notes
-----
The function assumes that the number of dimenensions of `a` and `b`
are the same, if necessary prepending the smallest with ones.
If `a.shape = (r0,r1,..,rN)` and `b.shape = (s0,s1,...,sN)`,
the Kronecker product has shape `(r0*s0, r1*s1, ..., rN*SN)`.
The elements are products of elements from `a` and `b`, organized
explicitly by::
kron(a,b)[k0,k1,...,kN] = a[i0,i1,...,iN] * b[j0,j1,...,jN]
where::
kt = it * st + jt, t = 0,...,N
In the common 2-D case (N=1), the block structure can be visualized::
[[ a[0,0]*b, a[0,1]*b, ... , a[0,-1]*b ],
[ ... ... ],
[ a[-1,0]*b, a[-1,1]*b, ... , a[-1,-1]*b ]]
Examples
--------
>>> np.kron([1,10,100], [5,6,7])
array([ 5, 6, 7, 50, 60, 70, 500, 600, 700])
>>> np.kron([5,6,7], [1,10,100])
array([ 5, 50, 500, 6, 60, 600, 7, 70, 700])
>>> np.kron(np.eye(2), np.ones((2,2)))
array([[ 1., 1., 0., 0.],
[ 1., 1., 0., 0.],
[ 0., 0., 1., 1.],
[ 0., 0., 1., 1.]])
>>> a = np.arange(100).reshape((2,5,2,5))
>>> b = np.arange(24).reshape((2,3,4))
>>> c = np.kron(a,b)
>>> c.shape
(2, 10, 6, 20)
>>> I = (1,3,0,2)
>>> J = (0,2,1)
>>> J1 = (0,) + J # extend to ndim=4
>>> S1 = (1,) + b.shape
>>> K = tuple(np.array(I) * np.array(S1) + np.array(J1))
>>> C[K] == A[I]*B[J]
True
ldexp()
numpy.ldexp(...)
y = ldexp(x1,x2)
Compute y = x1 * 2**x2.
left_shift()
numpy.left_shift(...)
y = left_shift(x1,x2)
Shift the bits of an integer to the left.
Bits are shifted to the left by appending `x2` 0s at the right of `x1`.
Since the internal representation of numbers is in binary format, this
operation is equivalent to multiplying `x1` by ``2**x2``.
Parameters
----------
x1 : array_like of integer type
Input values.
x2 : array_like of integer type
Number of zeros to append to `x1`.
Returns
-------
out : array of integer type
Return `x1` with bits shifted `x2` times to the left.
See Also
--------
right_shift : Shift the bits of an integer to the right.
binary_repr : Return the binary representation of the input number
as a string.
Examples
--------
>>> np.left_shift(5, [1,2,3])
array([10, 20, 40])
less()
numpy.less(...)
y = less(x1,x2)
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)
less_equal()
numpy.less_equal(...)
y = less_equal(x1,x2)
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)
lexsort()
numpy.lexsort(...)
lexsort(keys, axis=-1)
Perform an indirect sort using a list of keys.
Imagine three input keys, ``a``, ``b`` and ``c``. These can be seen as
columns in a spreadsheet. The first row of the spreadsheet would
therefore be ``a[0], b[0], c[0]``. Lexical sorting orders the different
rows by first sorting on the on first column (key), then the second,
and so forth. At each step, the previous ordering is preserved
when equal keys are encountered.
Parameters
----------
keys : (k,N) array or tuple containing k (N,)-shaped sequences
The `k` different "columns" to be sorted. The last column is the
primary sort column.
axis : int, optional
Axis to be indirectly sorted. By default, sort over the last axis.
Returns
-------
indices : (N,) ndarray of ints
Array of indices that sort the keys along the specified axis.
See Also
--------
argsort : Indirect sort.
ndarray.sort : In-place sort.
sort : Return a sorted copy of an array.
Examples
--------
Sort names: first by surname, then by name.
>>> surnames = ('Hertz', 'Galilei', 'Hertz')
>>> first_names = ('Heinrich', 'Galileo', 'Gustav')
>>> ind = np.lexsort((first_names, surnames))
>>> ind
array([1, 2, 0])
>>> [surnames[i] + ", " + first_names[i] for i in ind]
['Galilei, Galileo', 'Hertz, Gustav', 'Hertz, Heinrich']
Sort two columns of numbers:
>>> a = [1,5,1,4,3,4,4] # First column
>>> b = [9,4,0,4,0,2,1] # Second column
>>> ind = np.lexsort((b,a)) # Sort by second, then first column
>>> print ind
[2 0 4 6 5 3 1]
>>> [(a[i],b[i]) for i in ind]
[(1, 0), (1, 9), (3, 0), (4, 1), (4, 2), (4, 4), (5, 4)]
Note that the first elements are sorted. For each first element,
the second elements are also sorted.
A normal ``argsort`` would have yielded:
>>> [(a[i],b[i]) for i in np.argsort(a)]
[(1, 9), (1, 0), (3, 0), (4, 4), (4, 2), (4, 1), (5, 4)]
Structured arrays are sorted lexically:
>>> x = np.array([(1,9), (5,4), (1,0), (4,4), (3,0), (4,2), (4,1)],
... dtype=np.dtype([('x', int), ('y', int)]))
>>> np.argsort(x) # or np.argsort(x, order=('x', 'y'))
array([2, 0, 4, 6, 5, 3, 1])
>>> from numpy import *
>>> serialnr = array([1023, 5202, 6230, 1671, 1682, 5241])
>>> height = array([40., 42., 60., 60., 98., 40.])
>>> width = array([50., 20., 70., 60., 15., 30.])
>>>
>>>
>>>
>>>
>>> indices = lexsort(keys = (width, height))
>>> indices
array([5, 0, 1, 3, 2, 4])
>>> for n in indices:
... print serialnr[n], height[n], width[n]
...
5241 40.0 30.0
1023 40.0 50.0
5202 42.0 20.0
1671 60.0 60.0
6230 60.0 70.0
1682 98.0 15.0
>>>
>>> a = vstack([serialnr,width,height])
>>> print a
[[ 1023. 5202. 6230. 1671. 1682. 5241.]
[ 50. 20. 70. 60. 15. 30.]
[ 40. 42. 60. 60. 98. 40.]]
>>> indices = lexsort(a)
>>> a.take(indices, axis=-1)
array([[ 5241., 1023., 5202., 1671., 6230., 1682.],
[ 30., 50., 20., 60., 70., 15.],
[ 40., 40., 42., 60., 60., 98.]])
See also: sort, argsort
linspace()
numpy.linspace(start, stop, num=50, endpoint=True, retstep=False)
Return evenly spaced numbers over a specified interval.
Returns `num` evenly spaced samples, calculated over the
interval [`start`, `stop` ].
The endpoint of the interval can optionally be excluded.
Parameters
----------
start : {float, int}
The starting value of the sequence.
stop : {float, int}
The end value of the sequence, unless `endpoint` is set to False.
In that case, the sequence consists of all but the last of ``num + 1``
evenly spaced samples, so that `stop` is excluded. Note that the step
size changes when `endpoint` is False.
num : int, optional
Number of samples to generate. Default is 50.
endpoint : bool, optional
If True, `stop` is the last sample. Otherwise, it is not included.
Default is True.
retstep : bool, optional
If True, return (`samples`, `step`), where `step` is the spacing
between samples.
Returns
-------
samples : ndarray
There are `num` equally spaced samples in the closed interval
``[start, stop]`` or the half-open interval ``[start, stop)``
(depending on whether `endpoint` is True or False).
step : float (only if `retstep` is True)
Size of spacing between samples.
See Also
--------
arange : Similiar to `linspace`, but uses a step size (instead of the
number of samples).
logspace : Samples uniformly distributed in log space.
Examples
--------
>>> np.linspace(2.0, 3.0, num=5)
array([ 2. , 2.25, 2.5 , 2.75, 3. ])
>>> np.linspace(2.0, 3.0, num=5, endpoint=False)
array([ 2. , 2.2, 2.4, 2.6, 2.8])
>>> np.linspace(2.0, 3.0, num=5, retstep=True)
(array([ 2. , 2.25, 2.5 , 2.75, 3. ]), 0.25)
Graphical illustration:
>>> import matplotlib.pyplot as plt
>>> N = 8
>>> y = np.zeros(N)
>>> x1 = np.linspace(0, 10, N, endpoint=True)
>>> x2 = np.linspace(0, 10, N, endpoint=False)
>>> plt.plot(x1, y, 'o')
>>> plt.plot(x2, y + 0.5, 'o')
>>> plt.ylim([-0.5, 1])
>>> plt.show()
>>> from numpy import *
>>> linspace(0,5,num=6)
array([ 0., 1., 2., 3., 4., 5.])
>>> linspace(0,5,num=10)
array([ 0. , 0.55555556, 1.11111111, 1.66666667, 2.22222222,
2.77777778, 3.33333333, 3.88888889, 4.44444444, 5. ])
>>> linspace(0,5,num=10,endpoint=False)
array([ 0. , 0.5, 1. , 1.5, 2. , 2.5, 3. , 3.5, 4. , 4.5])
>>> stepsize = linspace(0,5,num=10,endpoint=False,retstep=True)
>>> stepsize
(array([ 0. , 0.5, 1. , 1.5, 2. , 2.5, 3. , 3.5, 4. , 4.5]), 0.5)
>>> myarray, stepsize = linspace(0,5,num=10,endpoint=False,retstep=True)
>>> stepsize
0.5
See also: arange, logspace, r_
load()
numpy.load(file, memmap=False)
Load a pickled, ``.npy``, or ``.npz`` binary file.
Parameters
----------
file : file-like object or string
The file to read. It must support ``seek()`` and ``read()`` methods.
memmap : bool
If True, then memory-map the ``.npy`` file (or unzip the ``.npz`` file
into a temporary directory and memory-map each component). This has
no effect for a pickled file.
Returns
-------
result : array, tuple, dict, etc.
Data stored in the file.
Raises
------
IOError
If the input file does not exist or cannot be read.
Notes
-----
- If file contains pickle data, then whatever is stored in the
pickle is returned.
- If the file is a ``.npy`` file, then an array is returned.
- If the file is a ``.npz`` file, then a dictionary-like object is
returned, containing {filename: array} key-value pairs, one for
every file in the archive.
Examples
--------
>>> np.save('/tmp/123', np.array([1, 2, 3])
>>> np.load('/tmp/123.npy')
array([1, 2, 3])
loads()
numpy.loads(...)
loads(string) -- Load a pickle from the given string
loadtxt()
numpy.loadtxt(fname, dtype=<type 'float'>, comments='#', delimiter=None, converters=None, skiprows=0, usecols=None, unpack=False)
Load data from a text file.
Each row in the text file must have the same number of values.
Parameters
----------
fname : file or string
File or filename to read. If the filename extension is ``.gz``,
the file is first decompressed.
dtype : data-type
Data type of the resulting array. If this is a record data-type,
the resulting array will be 1-dimensional, and each row will be
interpreted as an element of the array. In this case, the number
of columns used must match the number of fields in the data-type.
comments : string, optional
The character used to indicate the start of a comment.
delimiter : string, optional
The string used to separate values. By default, this is any
whitespace.
converters : {}
A dictionary mapping column number to a function that will convert
that column to a float. E.g., if column 0 is a date string:
``converters = {0: datestr2num}``. Converters can also be used to
provide a default value for missing data:
``converters = {3: lambda s: float(s or 0)}``.
skiprows : int
Skip the first `skiprows` lines.
usecols : sequence
Which columns to read, with 0 being the first. For example,
``usecols = (1,4,5)`` will extract the 2nd, 5th and 6th columns.
unpack : bool
If True, the returned array is transposed, so that arguments may be
unpacked using ``x, y, z = loadtxt(...)``
Returns
-------
out : ndarray
Data read from the text file.
See Also
--------
scipy.io.loadmat : reads Matlab(R) data files
Examples
--------
>>> from StringIO import StringIO # StringIO behaves like a file object
>>> c = StringIO("0 1\n2 3")
>>> np.loadtxt(c)
array([[ 0., 1.],
[ 2., 3.]])
>>> d = StringIO("M 21 72\nF 35 58")
>>> np.loadtxt(d, dtype={'names': ('gender', 'age', 'weight'),
... 'formats': ('S1', 'i4', 'f4')})
array([('M', 21, 72.0), ('F', 35, 58.0)],
dtype=[('gender', '|S1'), ('age', '<i4'), ('weight', '<f4')])
>>> c = StringIO("1,0,2\n3,0,4")
>>> x,y = np.loadtxt(c, delimiter=',', usecols=(0,2), unpack=True)
>>> x
array([ 1., 3.])
>>> y
array([ 2., 4.])
>>> from numpy import *
>>>
>>> data = loadtxt("myfile.txt")
>>> t,z = data[:,0], data[:,3]
>>>
>>> t,x,y,z = loadtxt("myfile.txt", unpack=True)
>>> t,z = loadtxt("myfile.txt", usecols = (0,3), unpack=True)
>>> data = loadtxt("myfile.txt", skiprows = 7)
>>> data = loadtxt("myfile.txt", comments = '!')
>>> data = loadtxt("myfile.txt", delimiter=';')
>>> data = loadtxt("myfile.txt", dtype = int)
See also: savetxt, fromfile
log()
numpy.log(...)
y = log(x)
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
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])
log10()
numpy.log10(...)
y = log10(x)
Compute the logarithm in base 10 element-wise.
Parameters
----------
x : array_like
Input values.
Returns
-------
y : ndarray
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])
log1p()
numpy.log1p(...)
y = log1p(x)
`log(1 + x)` in base `e`, elementwise.
Parameters
----------
x : array_like
Input values.
Returns
-------
y : ndarray
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
log2()
numpy.log2(x, y=None)
Return the base 2 logarithm.
Parameters
----------
x : array_like
Input array.
y : array_like
Optional output array with the same shape as `x`.
Returns
-------
y : ndarray
The logarithm to the base 2 of `x` elementwise.
NaNs are returned where `x` is negative.
See Also
--------
log, log1p, log10
Examples
--------
>>> np.log2([-1,2,4])
array([ NaN, 1., 2.])
logical_and()
numpy.logical_and(...)
y = logical_and(x1,x2)
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)
>>> from numpy import *
>>> logical_and(array([0,0,1,1]), array([0,1,0,1]))
array([False, False, False, True], dtype=bool)
>>> logical_and(array([False,False,True,True]), array([False,True,False,True]))
array([False, False, False, True], dtype=bool)
See also: logical_or, logical_not, logical_xor, bitwise_and
logical_not()
numpy.logical_not(...)
y = logical_not(x)
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)
>>> from numpy import *
>>> logical_not(array([0,1]))
>>> logical_not(array([False,True]))
See also: logical_or, logical_not, logical_xor, bitwise_and
logical_or()
numpy.logical_or(...)
y = logical_or(x1,x2)
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)
>>> from numpy import *
>>> logical_or(array([0,0,1,1]), array([0,1,0,1]))
>>> logical_or(array([False,False,True,True]), array([False,True,False,True]))
See also: logical_and, logical_not, logical_xor, bitwise_or
logical_xor()
numpy.logical_xor(...)
y = logical_xor(x1,x2)
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)
>>> from numpy import *
>>> logical_xor(array([0,0,1,1]), array([0,1,0,1]))
>>> logical_xor(array([False,False,True,True]), array([False,True,False,True]))
See also: logical_or, logical_not, logical_or, bitwise_xor
logspace()
numpy.logspace(start, stop, num=50, endpoint=True, base=10.0)
Return numbers spaced evenly on a log scale.
In linear space, the sequence starts at ``base ** start``
(`base` to the power of `start`) and ends with ``base ** stop``
(see `endpoint` below).
Parameters
----------
start : float
``base ** start`` is the starting value of the sequence.
stop : float
``base ** stop`` is the final value of the sequence, unless `endpoint`
is False. In that case, ``num + 1`` values are spaced over the
interval in log-space, of which all but the last (a sequence of
length ``num``) are returned.
num : integer, optional
Number of samples to generate. Default is 50.
endpoint : boolean, optional
If true, `stop` is the last sample. Otherwise, it is not included.
Default is True.
base : float, optional
The base of the log space. The step size between the elements in
``ln(samples) / ln(base)`` (or ``log_base(samples)``) is uniform.
Default is 10.0.
Returns
-------
samples : ndarray
`num` samples, equally spaced on a log scale.
See Also
--------
arange : Similiar to linspace, with the step size specified instead of the
number of samples. Note that, when used with a float endpoint, the
endpoint may or may not be included.
linspace : Similar to logspace, but with the samples uniformly distributed
in linear space, instead of log space.
Notes
-----
Logspace is equivalent to the code
>>> y = linspace(start, stop, num=num, endpoint=endpoint)
>>> power(base, y)
Examples
--------
>>> np.logspace(2.0, 3.0, num=4)
array([ 100. , 215.443469 , 464.15888336, 1000. ])
>>> np.logspace(2.0, 3.0, num=4, endpoint=False)
array([ 100. , 177.827941 , 316.22776602, 562.34132519])
>>> np.logspace(2.0, 3.0, num=4, base=2.0)
array([ 4. , 5.0396842 , 6.34960421, 8. ])
Graphical illustration:
>>> import matplotlib.pyplot as plt
>>> N = 10
>>> x1 = np.logspace(0.1, 1, N, endpoint=True)
>>> x2 = np.logspace(0.1, 1, N, endpoint=False)
>>> y = np.zeros(N)
>>> plt.plot(x1, y, 'o')
>>> plt.plot(x2, y + 0.5, 'o')
>>> plt.ylim([-0.5, 1])
>>> plt.show()
>>> from numpy import *
>>> logspace(-2, 3, num = 6)
array([ 1.00000000e-02, 1.00000000e-01, 1.00000000e+00,
1.00000000e+01, 1.00000000e+02, 1.00000000e+03])
>>> logspace(-2, 3, num = 10)
array([ 1.00000000e-02, 3.59381366e-02, 1.29154967e-01,
4.64158883e-01, 1.66810054e+00, 5.99484250e+00,
2.15443469e+01, 7.74263683e+01, 2.78255940e+02,
1.00000000e+03])
>>> logspace(-2, 3, num = 6, endpoint=False)
array([ 1.00000000e-02, 6.81292069e-02, 4.64158883e-01,
3.16227766e+00, 2.15443469e+01, 1.46779927e+02])
>>> exp(linspace(log(0.01), log(1000), num=6, endpoint=False))
array([ 1.00000000e-02, 6.81292069e-02, 4.64158883e-01,
3.16227766e+00, 2.15443469e+01, 1.46779927e+02])
See also: arange, linspace, r_
lookfor()
numpy.lookfor(what, module=None, import_modules=True, regenerate=False)
Do a keyword search on docstrings.
A list of of objects that matched the search is displayed,
sorted by relevance.
Parameters
----------
what : str
String containing words to look for.
module : str, module
Module whose docstrings to go through.
import_modules : bool
Whether to import sub-modules in packages.
Will import only modules in ``__all__``.
regenerate : bool
Whether to re-generate the docstring cache.
Examples
--------
>>> np.lookfor('binary representation')
Search results for 'binary representation'
------------------------------------------
numpy.binary_repr
Return the binary representation of the input number as a string.
lstsq()
numpy.linalg.lstsq(a, b, rcond=-1)
Return the least-squares solution to an equation.
Solves the equation `a x = b` by computing a vector `x` that minimizes
the norm `|| b - a x ||`.
Parameters
----------
a : array_like, shape (M, N)
Input equation coefficients.
b : array_like, shape (M,) or (M, K)
Equation target values. If `b` is two-dimensional, the least
squares solution is calculated for each of the `K` target sets.
rcond : float, optional
Cutoff for ``small`` singular values of `a`.
Singular values smaller than `rcond` times the largest singular
value are considered zero.
Returns
-------
x : ndarray, shape(N,) or (N, K)
Least squares solution. The shape of `x` depends on the shape of
`b`.
residues : ndarray, shape(), (1,), or (K,)
Sums of residues; squared Euclidian norm for each column in
`b - a x`.
If the rank of `a` is < N or > M, this is an empty array.
If `b` is 1-dimensional, this is a (1,) shape array.
Otherwise the shape is (K,).
rank : integer
Rank of matrix `a`.
s : ndarray, shape(min(M,N),)
Singular values of `a`.
Raises
------
LinAlgError
If computation does not converge.
Notes
-----
If `b` is a matrix, then all array results returned as
matrices.
Examples
--------
Fit a line, ``y = mx + c``, through some noisy data-points:
>>> x = np.array([0, 1, 2, 3])
>>> y = np.array([-1, 0.2, 0.9, 2.1])
By examining the coefficients, we see that the line should have a
gradient of roughly 1 and cuts the y-axis at more-or-less -1.
We can rewrite the line equation as ``y = Ap``, where ``A = [[x 1]]``
and ``p = [[m], [c]]``. Now use `lstsq` to solve for `p`:
>>> A = np.vstack([x, np.ones(len(x))]).T
>>> A
array([[ 0., 1.],
[ 1., 1.],
[ 2., 1.],
[ 3., 1.]])
>>> m, c = np.linalg.lstsq(A, y)[0]
>>> print m, c
1.0 -0.95
Plot the data along with the fitted line:
>>> import matplotlib.pyplot as plt
>>> plt.plot(x, y, 'o', label='Original data', markersize=10)
>>> plt.plot(x, m*x + c, 'r', label='Fitted line')
>>> plt.legend()
>>> plt.show()
lstsq() is most often used in the context of least-squares fitting of data. Suppose you obtain some noisy data y as a function of a variable t, e.g. velocity as a function of time. You can use lstsq() to fit a model to the data, if the model is linear in its parameters, that is if
y = p0 * f0(t) + p1 * f1(t) + ... + pN-1 * fN-1(t) + noise
where the pi are the parameters you want to obtain through fitting and the fi(t) are known functions of t. What follows is an example how you can do this.
First, for the example's sake, some data is simulated:
>>> from numpy import *
>>> from numpy.random import normal
>>> t = arange(0.0, 10.0, 0.05)
>>> y = 2.0 * sin(2.*pi*t*0.6) + 2.7 * cos(2.*pi*t*0.6) + normal(0.0, 1.0, len(t))
We would like to fit this data with: model(t) = p0 * sin(2.*pi*t*0.6) + p1 * cos(2.*pi*t*0.6), where p0 and p1 are the unknown fit parameters. Here we go:
>>> from numpy.linalg import lstsq
>>> Nparam = 2
>>> A = zeros((len(t),Nparam), float)
>>> A[:,0] = sin(2.*pi*t*0.6)
>>> A[:,1] = cos(2.*pi*t*0.6)
>>> (p, residuals, rank, s) = lstsq(A,y)
>>> p
array([ 1.9315685 , 2.71165171])
>>> residuals
array([ 217.23783374])
>>> rank
2
>>> s
array([ 10., 10.])
See also: pinv, polyfit, solve
mat()
numpy.mat(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 *
>>> mat('1 3 4; 5 6 9')
matrix([[1, 3, 4],
[5, 6, 9]])
>>> a = array([[1,2],[3,4]])
>>> m = mat(a)
>>> m
matrix([[1, 2],
[3, 4]])
>>> a[0]
array([1, 2])
>>> m[0]
matrix([[1, 2]])
>>> a.ravel()
array([1, 2, 3, 4])
>>> m.ravel()
matrix([[1, 2, 3, 4]])
>>> a*a
array([[ 1, 4],
[ 9, 16]])
>>> m*m
matrix([[ 7, 10],
[15, 22]])
>>> a**3
array([[ 1, 8],
[27, 64]])
>>> m**3
matrix([[ 37, 54],
[ 81, 118]])
>>> m.T
matrix([[1, 3],
[2, 4]])
>>> m.H
matrix([[1, 3],
[2, 4]])
>>> m.I
matrix([[-2. , 1. ],
[ 1.5, -0.5]])
See also: bmat, array, dot, asmatrix
matrix()
numpy.matrix(...)
matrix(data, dtype=None, copy=True)
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, the string is interpreted as a matrix
with commas or spaces separating columns, and semicolons
separating rows.
dtype : data-type
Data-type of the output matrix.
copy : bool
If data is already an ndarray, then this flag determines whether
the data is copied, or whether a view is constructed.
See Also
--------
array
Examples
--------
>>> a = np.matrix('1 2; 3 4')
>>> print a
[[1 2]
[3 4]]
>>> np.matrix([[1, 2], [3, 4]])
matrix([[1, 2],
[3, 4]])
>>> from numpy import *
>>> matrix('1 3 4; 5 6 9')
matrix([[1, 3, 4],
[5, 6, 9]])
See also: mat, asmatrix
max()
numpy.max(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])
ndarray.max(...)
a.max(axis=None, out=None)
Return the maximum along a given axis.
Refer to `numpy.amax` for full documentation.
See Also
--------
numpy.amax : equivalent function
>>> from numpy import *
>>> a = array([10,20,30])
>>> a.max()
30
>>> a = array([[10,50,30],[60,20,40]])
>>> a.max()
60
>>> a.max(axis=0)
array([60, 50, 40])
>>> a.max(axis=1)
array([50, 60])
>>> max(a)
See also: nan, argmax, maximum, ptp
maximum()
numpy.maximum(...)
y = maximum(x1,x2)
Element-wise maximum of array elements.
Compare two arrays and returns a new array containing
the element-wise maxima.
Parameters
----------
x1, x2 : array_like
The arrays holding the elements to be compared.
Returns
-------
y : {ndarray, scalar}
The maximum of `x1` and `x2`, element-wise. Returns scalar if
both `x1` and `x2` are scalars.
See Also
--------
minimum :
element-wise minimum
Notes
-----
Equivalent to ``np.where(x1 > x2, x1, x2)`` but faster and does proper
broadcasting.
Examples
--------
>>> np.maximum([2, 3, 4], [1, 5, 2])
array([2, 5, 4])
>>> np.maximum(np.eye(2), [0.5, 2])
array([[ 1. , 2. ],
[ 0.5, 2. ]])
>>> from numpy import *
>>> a = array([1,0,5])
>>> b = array([3,2,4])
>>> maximum(a,b)
array([3, 2, 5])
>>> max(a.tolist(),b.tolist())
[3, 2, 4]
See also: minimum, max, argmax
maximum_sctype()
numpy.maximum_sctype(t)
returns the sctype of highest precision of the same general kind as 't'
may_share_memory()
numpy.may_share_memory(a, b)
Determine if two arrays can share memory
The memory-bounds of a and b are computed. If they overlap then
this function returns True. Otherwise, it returns False.
A return of True does not necessarily mean that the two arrays
share any element. It just means that they *might*.
mean()
numpy.mean(a, axis=None, dtype=None, out=None)
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. 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
array, a conversion is attempted.
axis : int, optional
Axis along which the means are computed. The default is to compute
the mean of the flattened array.
dtype : dtype, 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 : 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 : ndarray, see dtype parameter above
If `out=None`, returns a new array containing the mean values,
otherwise a reference to the output array is returned.
See Also
--------
average : Weighted average
Notes
-----
The arithmetic mean is the sum of the elements along the axis divided
by the number of elements.
Examples
--------
>>> a = np.array([[1,2],[3,4]])
>>> np.mean(a)
2.5
>>> np.mean(a,0)
array([ 2., 3.])
>>> np.mean(a,1)
array([ 1.5, 3.5])
ndarray.mean(...)
a.mean(axis=None, dtype=None, out=None)
Returns the average of the array elements along given axis.
Refer to `numpy.mean` for full documentation.
See Also
--------
numpy.mean : equivalent function
>>> from numpy import *
>>> a = array([1,2,7])
>>> a.mean()
3.3333333333333335
>>> a = array([[1,2,7],[4,9,6]])
>>> a.mean()
4.833333333333333
>>> a.mean(axis=0)
array([ 2.5, 5.5, 6.5])
>>> a.mean(axis=1)
array([ 3.33333333, 6.33333333])
See also: average, median, var, std, sum
numpy.median(a, axis=None, out=None, overwrite_input=False)
Compute the median along the specified axis.
Returns the median of the array elements.
Parameters
----------
a : array_like
Input array or object that can be converted to an array.
axis : {None, int}, optional
Axis along which the medians are computed. The default (axis=None) is to
compute the median along a flattened version of the array.
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 (of the output) will be cast if necessary.
overwrite_input : {False, True}, optional
If True, then allow use of memory of input array (a) for
calculations. The input array will be modified by the call to
median. This will save memory when you do not need to preserve
the contents of the input array. Treat the input as undefined,
but it will probably be fully or partially sorted. Default is
False. Note that, if `overwrite_input` is True and the input
is not already an ndarray, an error will be raised.
Returns
-------
median : ndarray
A new array holding the result (unless `out` is specified, in
which case that array is returned instead). If the input contains
integers, or floats of smaller precision than 64, then the output
data-type is float64. Otherwise, the output data-type is the same
as that of the input.
See Also
--------
mean
Notes
-----
Given a vector V of length N, the median of V is the middle value of
a sorted copy of V, ``V_sorted`` - i.e., ``V_sorted[(N-1)/2]``, when N is
odd. When N is even, it is the average of the two middle values of
``V_sorted``.
Examples
--------
>>> a = np.array([[10, 7, 4], [3, 2, 1]])
>>> a
array([[10, 7, 4],
[ 3, 2, 1]])
>>> np.median(a)
3.5
>>> np.median(a, axis=0)
array([ 6.5, 4.5, 2.5])
>>> np.median(a, axis=1)
array([ 7., 2.])
>>> m = np.median(a, axis=0)
>>> out = np.zeros_like(m)
>>> np.median(a, axis=0, out=m)
array([ 6.5, 4.5, 2.5])
>>> m
array([ 6.5, 4.5, 2.5])
>>> b = a.copy()
>>> np.median(b, axis=1, overwrite_input=True)
array([ 7., 2.])
>>> assert not np.all(a==b)
>>> b = a.copy()
>>> np.median(b, axis=None, overwrite_input=True)
3.5
>>> assert not np.all(a==b)
>>> from numpy import *
>>> a = array([1,2,3,4,9])
>>> median(a)
3
>>> a = array([1,2,3,4,9,0])
>>> median(a)
2.5
See also: average, mean, var, std
meshgrid()
numpy.meshgrid(x, y)
Return coordinate matrices from two coordinate vectors.
Parameters
----------
x, y : ndarray
Two 1D arrays representing the x and y coordinates
Returns
-------
X, Y : ndarray
For vectors `x`, `y` with lengths Nx=len(`x`) and Ny=len(`y`),
return `X`, `Y` where `X` and `Y` are (Ny, Nx) shaped arrays
with the elements of `x` and y repeated to fill the matrix along
the first dimension for `x`, the second for `y`.
See Also
--------
numpy.mgrid : Construct a multi-dimensional "meshgrid"
using indexing notation.
Examples
--------
>>> X, Y = numpy.meshgrid([1,2,3], [4,5,6,7])
>>> X
array([[1, 2, 3],
[1, 2, 3],
[1, 2, 3],
[1, 2, 3]])
>>> Y
array([[4, 4, 4],
[5, 5, 5],
[6, 6, 6],
[7, 7, 7]])
mgrid
numpy.mgrid
Construct a multi-dimensional "meshgrid".
grid = nd_grid() creates an instance which will return a mesh-grid
when indexed. The dimension and number of the output arrays are equal
to the number of indexing dimensions. If the step length is not a
complex number, then the stop is not inclusive.
However, if the step length is a **complex number** (e.g. 5j), then the
integer part of its magnitude is interpreted as specifying the
number of points to create between the start and stop values, where
the stop value **is inclusive**.
If instantiated with an argument of sparse=True, the mesh-grid is
open (or not fleshed out) so that only one-dimension of each returned
argument is greater than 1
Examples
--------
>>> mgrid = np.lib.index_tricks.nd_grid()
>>> mgrid[0:5,0:5]
array([[[0, 0, 0, 0, 0],
[1, 1, 1, 1, 1],
[2, 2, 2, 2, 2],
[3, 3, 3, 3, 3],
[4, 4, 4, 4, 4]],
<BLANKLINE>
[[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4]]])
>>> mgrid[-1:1:5j]
array([-1. , -0.5, 0. , 0.5, 1. ])
>>> ogrid = np.lib.index_tricks.nd_grid(sparse=True)
>>> ogrid[0:5,0:5]
[array([[0],
[1],
[2],
[3],
[4]]), array([[0, 1, 2, 3, 4]])]
>>> from numpy import *
>>> m = mgrid[1:3,2:5]
>>> print m
[[[1 1 1]
[2 2 2]]
[[2 3 4]
[2 3 4]]]
>>> m[0,1,2]
2
>>> m[1,1,2]
4
See also: indices, ogrid
min()
numpy.min(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])
ndarray.min(...)
a.min(axis=None, out=None)
Return the minimum along a given axis.
Refer to `numpy.amin` for full documentation.
See Also
--------
numpy.amin : equivalent function
>>> from numpy import *
>>> a = array([10,20,30])
>>> a.min()
10
>>> a = array([[10,50,30],[60,20,40]])
>>> a.min()
10
>>> a.min(axis=0)
array([10, 20, 30])
>>> a.min(axis=1)
array([10, 20])
>>> min(a)
See also: nan, max, minimum, argmin, ptp
minimum()
numpy.minimum(...)
y = minimum(x1,x2)
Element-wise minimum of array elements.
Compare two arrays and returns a new array containing
the element-wise minima.
Parameters
----------
x1, x2 : array_like
The arrays holding the elements to be compared.
Returns
-------
y : {ndarray, scalar}
The minimum of `x1` and `x2`, element-wise. Returns scalar if
both `x1` and `x2` are scalars.
See Also
--------
maximum :
element-wise maximum
Notes
-----
Equivalent to ``np.where(x1 < x2, x1, x2)`` but faster and does proper
broadcasting.
Examples
--------
>>> np.minimum([2, 3, 4], [1, 5, 2])
array([1, 3, 2])
>>> np.minimum(np.eye(2), [0.5, 2])
array([[ 0.5, 0. ],
[ 0. , 1. ]])
>>> from numpy import *
>>> a = array([1,0,5])
>>> b = array([3,2,4])
>>> minimum(a,b)
array([1, 0, 4])
>>> min(a.tolist(),b.tolist())
[1, 0, 5]
See also: min, maximum, argmin
mintypecode()
numpy.mintypecode(typechars, typeset='GDFgdf', default='d')
Return a minimum data type character from typeset that
handles all typechars given
The returned type character must be the smallest size such that
an array of the returned type can handle the data from an array of
type t for each t in typechars (or if typechars is an array,
then its dtype.char).
If the typechars does not intersect with the typeset, then default
is returned.
If t in typechars is not a string then t=asarray(t).dtype.char is
applied.
mirr()
numpy.mirr(values, finance_rate, reinvest_rate)
Modified internal rate of return.
Parameters
----------
values : array_like
Cash flows (must contain at least one positive and one negative value)
or nan is returned.
finance_rate : scalar
Interest rate paid on the cash flows
reinvest_rate : scalar
Interest rate received on the cash flows upon reinvestment
Returns
-------
out : float
Modified internal rate of return
mod()
numpy.mod(...)
y = remainder(x1,x2)
Returns element-wise remainder of division.
Computes `x1 - floor(x1/x2)*x2`.
Parameters
----------
x1 : array_like
Dividend array.
x2 : array_like
Divisor array.
Returns
-------
y : ndarray
The remainder of 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])
modf()
numpy.modf(...)
y1,y2 = modf(x)
Return the fractional and integral part of a number.
The fractional and integral parts are negative if the given number is
negative.
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)
msort()
numpy.msort(a)
Return a copy of an array sorted along the first axis.
Parameters
----------
a : array_like
Array to be sorted.
Returns
-------
sorted_array : ndarray
Array of the same type and shape as `a`.
See Also
--------
sort
Notes
-----
``np.msort(a)`` is equivalent to ``np.sort(a, axis=0)``.
multiply()
numpy.multiply(...)
y = multiply(x1,x2)
Multiply arguments elementwise.
Parameters
----------
x1, x2 : array_like
The arrays to be multiplied.
Returns
-------
y : ndarray
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.]])
>>> from numpy import *
>>> multiply(array([3,6]), array([4,7]))
array([12, 42])
See also: dot
nan
numpy.nan
float(x) -> floating point number
Convert a string or number to a floating point number, if possible.
>>> from numpy import *
>>> sqrt(array([-1.0]))
array([ nan])
>>> x = array([2, nan, 1])
>>> isnan(x)
array([False, True, False], dtype=bool)
>>> isfinite(x)
array([True, False, True], dtype=bool)
>>> nansum(x)
3.0
>>> nanmax(x)
2.0
>>> nanmin(x)
1.0
>>> nanargmin(x)
2
>>> nanargmax(x)
0
>>> nan_to_num(x)
array([ 2., 0., 1.])
See also: inf
nan_to_num()
numpy.nan_to_num(x)
Replace nan with zero and inf with large numbers.
Parameters
----------
x : array_like
Input data.
Returns
-------
out : ndarray
Array with the same shape and dtype as `x`. Nan is replaced
by zero, and inf (-inf) is replaced by the largest (smallest)
floating point value that fits in the output dtype.
Examples
--------
>>> x = np.array([np.inf, -np.inf, np.nan, -128, 128])
>>> np.nan_to_num(x)
array([ 1.79769313e+308, -1.79769313e+308, 0.00000000e+000,
-1.28000000e+002, 1.28000000e+002])
nanargmax()
numpy.nanargmax(a, axis=None)
Return indices of the maximum values over an axis, ignoring NaNs.
Parameters
----------
a : array_like
Input data.
axis : int, optional
Axis along which to operate. By default flattened input is used.
Returns
-------
index_array : ndarray
An array of indices or a single index value.
See Also
--------
argmax, nanargmin
Examples
--------
>>> a = np.array([[np.nan, 4], [2, 3]])
>>> np.argmax(a)
0
>>> np.nanargmax(a)
1
>>> np.nanargmax(a, axis=0)
array([1, 1])
>>> np.nanargmax(a, axis=1)
array([1, 0])
nanargmin()
numpy.nanargmin(a, axis=None)
Return indices of the minimum values along an axis, ignoring NaNs.
See Also
--------
nanargmax : corresponding function for maxima; see for details.
nanmax()
numpy.nanmax(a, axis=None)
Return the maximum of array elements over the given axis ignoring any NaNs.
Parameters
----------
a : array_like
Array containing numbers whose maximum is desired. If `a` is not
an array, a conversion is attempted.
axis : int, optional
Axis along which the maximum is computed.The default is to compute
the maximum of the flattened array.
Returns
-------
y : ndarray
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. The
the same dtype as `a` is returned.
See Also
--------
numpy.amax : Maximum across array including any Not a Numbers.
numpy.nanmin : Minimum across array ignoring any Not a Numbers.
isnan : Shows which elements are Not a Number (NaN).
isfinite: Shows which elements are not: Not a Number, positive and
negative infinity
Notes
-----
Numpy uses the IEEE Standard for Binary Floating-Point for Arithmetic
(IEEE 754). This means that Not a Number is not equivalent to infinity.
Positive infinity is treated as a very large number and negative infinity
is treated as a very small (i.e. negative) number.
If the input has a integer type, an integer type is returned unless
the input contains NaNs and infinity.
Examples
--------
>>> a = np.array([[1, 2], [3, np.nan]])
>>> np.nanmax(a)
3.0
>>> np.nanmax(a, axis=0)
array([ 3., 2.])
>>> np.nanmax(a, axis=1)
array([ 2., 3.])
When positive infinity and negative infinity are present:
>>> np.nanmax([1, 2, np.nan, np.NINF])
2.0
>>> np.nanmax([1, 2, np.nan, np.inf])
inf
nanmin()
numpy.nanmin(a, axis=None)
Return the minimum of array elements over the given axis ignoring any NaNs.
Parameters
----------
a : array_like
Array containing numbers whose sum is desired. If `a` is not
an array, a conversion is attempted.
axis : int, optional
Axis along which the minimum is computed.The default is to compute
the minimum of the flattened array.
Returns
-------
y : {ndarray, 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. The
the same dtype as `a` is returned.
See Also
--------
numpy.amin : Minimum across array including any Not a Numbers.
numpy.nanmax : Maximum across array ignoring any Not a Numbers.
isnan : Shows which elements are Not a Number (NaN).
isfinite: Shows which elements are not: Not a Number, positive and
negative infinity
Notes
-----
Numpy uses the IEEE Standard for Binary Floating-Point for Arithmetic
(IEEE 754). This means that Not a Number is not equivalent to infinity.
Positive infinity is treated as a very large number and negative infinity
is treated as a very small (i.e. negative) number.
If the input has a integer type, an integer type is returned unless
the input contains NaNs and infinity.
Examples
--------
>>> a = np.array([[1, 2], [3, np.nan]])
>>> np.nanmin(a)
1.0
>>> np.nanmin(a, axis=0)
array([ 1., 2.])
>>> np.nanmin(a, axis=1)
array([ 1., 3.])
When positive infinity and negative infinity are present:
>>> np.nanmin([1, 2, np.nan, np.inf])
1.0
>>> np.nanmin([1, 2, np.nan, np.NINF])
-inf
nansum()
numpy.nansum(a, axis=None)
Return the sum of array elements over a given axis treating
Not a Numbers (NaNs) as zero.
Parameters
----------
a : array_like
Array containing numbers whose sum is desired. If `a` is not an
array, a conversion is attempted.
axis : int, optional
Axis along which the sum is computed. The default is to compute
the sum of the flattened array.
Returns
-------
y : ndarray
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 with
the same dtype as `a`.
See Also
--------
numpy.sum : Sum across array including Not a Numbers.
isnan : Shows which elements are Not a Number (NaN).
isfinite: Shows which elements are not: Not a Number, positive and
negative infinity
Notes
-----
Numpy uses the IEEE Standard for Binary Floating-Point for Arithmetic
(IEEE 754). This means that Not a Number is not equivalent to infinity.
If positive or negative infinity are present the result is positive or
negative infinity. But if both positive and negative infinity are present,
the result is Not A Number (NaN).
Arithmetic is modular when using integer types (all elements of `a` must
be finite i.e. no elements that are NaNs, positive infinity and negative
infinity because NaNs are floating point types), and no error is raised
on overflow.
Examples
--------
>>> np.nansum(1)
1
>>> np.nansum([1])
1
>>> np.nansum([1, np.nan])
1.0
>>> a = np.array([[1, 1], [1, np.nan]])
>>> np.nansum(a)
3.0
>>> np.nansum(a, axis=0)
array([ 2., 1.])
When positive infinity and negative infinity are present
>>> np.nansum([1, np.nan, np.inf])
inf
>>> np.nansum([1, np.nan, np.NINF])
-inf
>>> np.nansum([1, np.nan, np.inf, np.NINF])
nan
ndenumerate()
numpy.ndenumerate(...)
Multidimensional index iterator.
Return an iterator yielding pairs of array coordinates and values.
Parameters
----------
a : ndarray
Input array.
Examples
--------
>>> a = np.array([[1,2],[3,4]])
>>> for index, x in np.ndenumerate(a):
... print index, x
(0, 0) 1
(0, 1) 2
(1, 0) 3
(1, 1) 4
>>> from numpy import *
>>> a = arange(9).reshape(3,3) + 10
>>> a
array([[10, 11, 12],
[13, 14, 15],
[16, 17, 18]])
>>> b = ndenumerate(a)
>>> for position,value in b: print position,value
...
(0, 0) 10
(0, 1) 11
(0, 2) 12
(1, 0) 13
(1, 1) 14
(1, 2) 15
(2, 0) 16
(2, 1) 17
(2, 2) 18
See also: broadcast, ndindex
ndim() or .ndim
numpy.ndim(a)
Return the number of dimensions of an array.
Parameters
----------
a : array_like
Input array. If it is not already an ndarray, a conversion is
attempted.
Returns
-------
number_of_dimensions : int
The number of dimensions in `a`. Scalars are zero-dimensional.
See Also
--------
ndarray.ndim : equivalent method
shape : dimensions of array
ndarray.shape : dimensions of array
Examples
--------
>>> np.ndim([[1,2,3],[4,5,6]])
2
>>> np.ndim(np.array([[1,2,3],[4,5,6]]))
2
>>> np.ndim(1)
0
ndarray.ndim
Number of array dimensions.
Examples
--------
>>> x = np.array([1,2,3])
>>> x.ndim
1
>>> y = np.zeros((2,3,4))
>>> y.ndim
3
>>> from numpy import *
>>> a = arange(12).reshape(3,4)
>>> a
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
>>> a.ndim
2
>>> a.shape = (2,2,3)
array([[[ 0, 1, 2],
[ 3, 4, 5]],
[[ 6, 7, 8],
[ 9, 10, 11]]])
>>> a.ndim
3
>>> len(a.shape)
3
See also: shape
ndindex()
numpy.ndindex(...)
Pass in a sequence of integers corresponding
to the number of dimensions in the counter. This iterator
will then return an N-dimensional counter.
Example:
>>> for index in np.ndindex(3,2,1):
... print index
(0, 0, 0)
(0, 1, 0)
(1, 0, 0)
(1, 1, 0)
(2, 0, 0)
(2, 1, 0)
>>> for index in ndindex(4,3,2):
print index
(0,0,0)
(0,0,1)
(0,1,0)
...
(3,1,1)
(3,2,0)
(3,2,1)
See also: broadcast, ndenumerate
negative()
numpy.negative(...)
y = negative(x)
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.])
newaxis
numpy.newaxis
>>> from numpy import *
>>> x = arange(3)
>>> x
array([0, 1, 2])
>>> x[:,newaxis]
array([[0],
[1],
[2]])
>>> x[:,newaxis,newaxis]
array([[[0]],
[[1]],
[[2]]])
>>> x[:,newaxis] * x
array([[0, 0, 0],
[0, 1, 2],
[0, 2, 4]])
>>> y = arange(3,6)
>>> x[:,newaxis] * y
array([[ 0, 0, 0],
[ 3, 4, 5],
[ 6, 8, 10]])
>>> x.shape
(3,)
>>> x[newaxis,:].shape
(1,3)
>>> x[:,newaxis].shape
(3,1)
See also: [], atleast_1d, atleast_2d, atleast_3d, expand_dims
newbuffer()
numpy.newbuffer(...)
newbuffer(size)
Return a new uninitialized buffer object of size bytes
newbyteorder()
ndarray.newbyteorder(...)
a.newbyteorder(byteorder)
Equivalent to a.view(a.dtype.newbytorder(byteorder))
nonzero()
numpy.nonzero(a)
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
Input array.
Returns
-------
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.
ndarray.nonzero :
Equivalent ndarray method.
Examples
--------
>>> 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]))
>>> x[np.nonzero(x)]
array([ 1., 1., 1.])
>>> np.transpose(np.nonzero(x))
array([[0, 0],
[1, 1],
[2, 2]])
ndarray.nonzero(...)
a.nonzero()
Return the indices of the elements that are non-zero.
Refer to `numpy.nonzero` for full documentation.
See Also
--------
numpy.nonzero : equivalent function
>>> from numpy import *
>>> x = array([1,0,2,-1,0,0,8])
>>> indices = x.nonzero()
>>> indices
(array([0, 2, 3, 6]),)
>>> x[indices]
array([1, 2, -1, 8])
>>> y = array([[0,1,0],[2,0,3]])
>>> indices = y.nonzero()
>>> indices
(array([0, 1, 1]), array([1, 0, 2]))
>>> y[indices[0],indices[1]]
array([3, 4, 5])
>>> y[indices]
array([3, 4, 5])
>>> y = array([1,3,5,7])
>>> indices = (y >= 5).nonzero()
>>> y[indices]
array([5, 7])
>>> nonzero(y)
(array([0, 1, 2, 3]),)
See also: [], where, compress, choose, take
not_equal()
numpy.not_equal(...)
y = not_equal(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)
nper()
numpy.nper(rate, pmt, pv, fv=0, when='end')
Compute the number of periods.
Parameters
----------
rate : array_like
Rate of interest (per period)
pmt : array_like
Payment
pv : array_like
Present value
fv : array_like, optional
Future value
when : {{'begin', 1}, {'end', 0}}, {string, int}, optional
When payments are due ('begin' (1) or 'end' (0))
Notes
-----
The number of periods ``nper`` is computed by solving the equation::
fv + pv*(1+rate)**nper + pmt*(1+rate*when)/rate * ((1+rate)**nper - 1) == 0
or, when ``rate == 0``::
fv + pv + pmt * nper == 0
Examples
--------
If you only had $150 to spend as payment, how long would it take to pay-off
a loan of $8,000 at 7% annual interest?
>>> np.nper(0.07/12, -150, 8000)
64.073348770661852
So, over 64 months would be required to pay off the loan.
The same analysis could be done with several different interest rates
and/or payments and/or total amounts to produce an entire table.
>>> np.nper(*(np.ogrid[0.06/12:0.071/12:0.01/12, -200:-99:100, 6000:7001:1000]))
array([[[ 32.58497782, 38.57048452],
[ 71.51317802, 86.37179563]],
<BLANKLINE>
[[ 33.07413144, 39.26244268],
[ 74.06368256, 90.22989997]]])
npv()
numpy.npv(rate, values)
Returns the NPV (Net Present Value) of a cash flow series.
Parameters
----------
rate : scalar
The discount rate.
values : array_like, shape(M, )
The values of the time series of cash flows. Must be the same
increment as the `rate`.
Returns
-------
out : float
The NPV of the input cash flow series `values` at the discount `rate`.
Notes
-----
Returns the result of:
.. math :: \sum_{t=1}^M{\frac{values_t}{(1+rate)^{t
}}}
obj2sctype()
numpy.obj2sctype(rep, default=None)
ogrid
numpy.ogrid
Construct a multi-dimensional "meshgrid".
grid = nd_grid() creates an instance which will return a mesh-grid
when indexed. The dimension and number of the output arrays are equal
to the number of indexing dimensions. If the step length is not a
complex number, then the stop is not inclusive.
However, if the step length is a **complex number** (e.g. 5j), then the
integer part of its magnitude is interpreted as specifying the
number of points to create between the start and stop values, where
the stop value **is inclusive**.
If instantiated with an argument of sparse=True, the mesh-grid is
open (or not fleshed out) so that only one-dimension of each returned
argument is greater than 1
Examples
--------
>>> mgrid = np.lib.index_tricks.nd_grid()
>>> mgrid[0:5,0:5]
array([[[0, 0, 0, 0, 0],
[1, 1, 1, 1, 1],
[2, 2, 2, 2, 2],
[3, 3, 3, 3, 3],
[4, 4, 4, 4, 4]],
<BLANKLINE>
[[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4]]])
>>> mgrid[-1:1:5j]
array([-1. , -0.5, 0. , 0.5, 1. ])
>>> ogrid = np.lib.index_tricks.nd_grid(sparse=True)
>>> ogrid[0:5,0:5]
[array([[0],
[1],
[2],
[3],
[4]]), array([[0, 1, 2, 3, 4]])]
>>> from numpy import *
>>> x,y = ogrid[0:3,0:3]
>>> x
array([[0],
[1],
[2]])
>>> y
array([[0, 1, 2]])
>>> print x*y
[[0 0 0]
[0 1 2]
[0 2 4]]
See also: mgrid
ones()
numpy.ones(shape, dtype=None, order='C')
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.]])
>>> from numpy import *
>>> ones(5)
array([ 1., 1., 1., 1., 1.])
>>> ones((2,3), int)
array([[1, 1, 1],
[1, 1, 1]])
See also: ones_like, zeros, empty, eye, identity
ones_like()
numpy.ones_like(...)
y = ones_like(x)
Returns an array of ones 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]])
>>> from numpy import *
>>> a = array([[1,2,3],[4,5,6]])
>>> ones_like(a)
array([[1, 1, 1],
[1, 1, 1]])
See also: ones, zeros_like
outer()
numpy.outer(a, b)
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)
>>> from numpy import *
>>> x = array([1,2,3])
>>> y = array([10,20,30])
>>> outer(x,y)
array([[10, 20, 30],
[20, 40, 60],
[30, 60, 90]])
See also: inner, cross
packbits()
numpy.packbits(...)
out = numpy.packbits(myarray, axis=None)
myarray : an integer type array whose elements should be packed to bits
This routine packs the elements of a binary-valued dataset into a
NumPy array of type uint8 ('B') whose bits correspond to
the logical (0 or nonzero) value of the input elements.
The dimension over-which bit-packing is done is given by axis.
The shape of the output has the same number of dimensions as the input
(unless axis is None, in which case the output is 1-d).
Example:
>>> a = array([[[1,0,1],
... [0,1,0]],
... [[1,1,0],
... [0,0,1]]])
>>> b = numpy.packbits(a,axis=-1)
>>> b
array([[[160],[64]],[[192],[32]]], dtype=uint8)
Note that 160 = 128 + 32
192 = 128 + 64
permutation()
numpy.random.permutation(...)
permutation(x)
Randomly permute a sequence, or return a permuted range.
Parameters
----------
x : int or array_like
If `x` is an integer, randomly permute ``np.arange(x)``.
If `x` is an array, make a copy and shuffle the elements
randomly.
Returns
-------
out : ndarray
Permuted sequence or array range.
Examples
--------
>>> np.random.permutation(10)
array([1, 7, 4, 3, 0, 9, 2, 5, 8, 6])
>>> np.random.permutation([1, 4, 9, 12, 15])
array([15, 1, 9, 4, 12])
>>> from numpy import *
>>> from numpy.random import permutation
>>> permutation(4)
array([0, 3, 1, 2])
>>> permutation(4)
array([2, 1, 0, 3])
>>> permutation(4)
array([3, 0, 2, 1])
See also: shuffle, bytes, seed
piecewise()
numpy.piecewise(x, condlist, funclist, *args, **kw)
Evaluate a piecewise-defined function.
Given a set of conditions and corresponding functions, evaluate each
function on the input data wherever its condition is true.
Parameters
----------
x : (N,) ndarray
The input domain.
condlist : list of M (N,)-shaped boolean arrays
Each boolean array corresponds to a function in `funclist`. Wherever
`condlist[i]` is True, `funclist[i](x)` is used as the output value.
Each boolean array in `condlist` selects a piece of `x`,
and should therefore be of the same shape as `x`.
The length of `condlist` must correspond to that of `funclist`.
If one extra function is given, i.e. if the length of `funclist` is
M+1, then that extra function is the default value, used wherever
all conditions are false.
funclist : list of M or M+1 callables, f(x,*args,**kw), or values
Each function is evaluated over `x` wherever its corresponding
condition is True. It should take an array as input and give an array
or a scalar value as output. If, instead of a callable,
a value is provided then a constant function (``lambda x: value``) is
assumed.
args : tuple, optional
Any further arguments given to `piecewise` are passed to the functions
upon execution, i.e., if called ``piecewise(...,...,1,'a')``, then
each function is called as ``f(x,1,'a')``.
kw : dictionary, optional
Keyword arguments used in calling `piecewise` are passed to the
functions upon execution, i.e., if called
``piecewise(...,...,lambda=1)``, then each function is called as
``f(x,lambda=1)``.
Returns
-------
out : ndarray
The output is the same shape and type as x and is found by
calling the functions in `funclist` on the appropriate portions of `x`,
as defined by the boolean arrays in `condlist`. Portions not covered
by any condition have undefined values.
Notes
-----
This is similar to choose or select, except that functions are
evaluated on elements of `x` that satisfy the corresponding condition from
`condlist`.
The result is::
|--
|funclist[0](x[condlist[0]])
out = |funclist[1](x[condlist[1]])
|...
|funclist[n2](x[condlist[n2]])
|--
Examples
--------
Define the sigma function, which is -1 for ``x < 0`` and +1 for ``x >= 0``.
>>> x = np.arange(6) - 2.5 # x runs from -2.5 to 2.5 in steps of 1
>>> np.piecewise(x, [x < 0, x >= 0.5], [-1,1])
array([-1., -1., -1., 1., 1., 1.])
Define the absolute value, which is ``-x`` for ``x <0`` and ``x`` for
``x >= 0``.
>>> np.piecewise(x, [x < 0, x >= 0], [lambda x: -x, lambda x: x])
array([ 2.5, 1.5, 0.5, 0.5, 1.5, 2.5])
>>> from numpy import *
>>> f1 = lambda x: x*x
>>> f2 = lambda x: 2*x
>>> x = arange(-2.,3.,0.1)
>>> condition = (x>1)&(x<2)
>>> y = piecewise(x,condition, [f1,1.])
>>> y = piecewise(x, fabs(x)<=1, [f1,0]) + piecewise(x, x>1, [f2,0])
>>> print y
<snip>
See also: select
pinv()
numpy.linalg.pinv(a, rcond=1.0000000000000001e-015)
Compute the (Moore-Penrose) pseudo-inverse of a matrix.
Calculate the generalized inverse of a matrix using its
singular-value decomposition (SVD) and including all
`large` singular values.
Parameters
----------
a : array_like (M, N)
Matrix to be pseudo-inverted.
rcond : float
Cutoff for `small` singular values.
Singular values smaller than rcond*largest_singular_value are
considered zero.
Returns
-------
B : ndarray (N, M)
The pseudo-inverse of `a`. If `a` is an np.matrix instance, then so
is `B`.
Raises
------
LinAlgError
In case SVD computation does not converge.
Examples
--------
>>> a = np.random.randn(9, 6)
>>> B = np.linalg.pinv(a)
>>> np.allclose(a, np.dot(a, np.dot(B, a)))
True
>>> np.allclose(B, np.dot(B, np.dot(a, B)))
True
>>> from numpy import *
>>> from numpy.linalg import pinv,svd,lstsq
>>> A = array([[1., 3., 5.],[2., 4., 6.]])
>>> b = array([1., 3.])
>>>
>>>
>>>
>>>
>>> pinvA = pinv(A)
>>> print pinvA
[[-1.33333333 1.08333333]
[-0.33333333 0.33333333]
[ 0.66666667 -0.41666667]]
>>> x = dot(pinvA, b)
>>> print x
[ 1.91666667 0.66666667 -0.58333333]
>>>
>>>
>>>
>>> x,resids,rank,s = lstsq(A,b)
>>> print x
[ 1.91666667 0.66666667 -0.58333333]
>>>
>>>
>>>
>>> U,sigma,V = svd(A)
>>> S = zeros_like(A.transpose())
>>> for n in range(len(sigma)): S[n,n] = 1. / sigma[n]
>>> dot(V.transpose(), dot(S, U.transpose()))
array([[-1.33333333, 1.08333333],
[-0.33333333, 0.33333333],
[ 0.66666667, -0.41666667]])
See also: inv, lstsq, solve, svd
pkgload()
numpy.pkgload(*packages, **options)
Load one or more packages into parent package top-level namespace.
This function is intended to shorten the need to import many
subpackages, say of scipy, constantly with statements such as
import scipy.linalg, scipy.fftpack, scipy.etc...
Instead, you can say:
import scipy
scipy.pkgload('linalg','fftpack',...)
or
scipy.pkgload()
to load all of them in one call.
If a name which doesn't exist in scipy's namespace is
given, a warning is shown.
Parameters
----------
*packages : arg-tuple
the names (one or more strings) of all the modules one
wishes to load into the top-level namespace.
verbose= : integer
verbosity level [default: -1].
verbose=-1 will suspend also warnings.
force= : bool
when True, force reloading loaded packages [default: False].
postpone= : bool
when True, don't load packages [default: False]
place()
numpy.place(arr, mask, vals)
Changes elements of an array based on conditional and input values.
Similar to ``putmask(a, mask, vals)`` but the 1D array `vals` has the
same number of elements as the non-zero values of `mask`. Inverse of
``extract``.
Sets `a`.flat[n] = `values`\[n] for each n where `mask`.flat[n] is true.
Parameters
----------
a : array_like
Array to put data into.
mask : array_like
Boolean mask array.
values : array_like, shape(number of non-zero `mask`, )
Values to put into `a`.
See Also
--------
putmask, put, take
pmt()
numpy.pmt(rate, nper, pv, fv=0, when='end')
Compute the payment against loan principal plus interest.
Parameters
----------
rate : array_like
Rate of interest (per period)
nper : array_like
Number of compounding periods
pv : array_like
Present value
fv : array_like
Future value
when : {{'begin', 1}, {'end', 0}}, {string, int}
When payments are due ('begin' (1) or 'end' (0))
Returns
-------
out : ndarray
Payment against loan plus interest. If all input is scalar, returns a
scalar float. If any input is array_like, returns payment for each
input element. If multiple inputs are array_like, they all must have
the same shape.
Notes
-----
The payment ``pmt`` is computed by solving the equation::
fv +
pv*(1 + rate)**nper +
pmt*(1 + rate*when)/rate*((1 + rate)**nper - 1) == 0
or, when ``rate == 0``::
fv + pv + pmt * nper == 0
Examples
--------
What would the monthly payment need to be to pay off a $200,000 loan in 15
years at an annual interest rate of 7.5%?
>>> np.pmt(0.075/12, 12*15, 200000)
-1854.0247200054619
In order to pay-off (i.e. have a future-value of 0) the $200,000 obtained
today, a monthly payment of $1,854.02 would be required.
poisson()
numpy.random.poisson(...)
poisson(lam=1.0, size=None)
Poisson distribution.
>>> from numpy import *
>>> from numpy.random import *
>>> poisson(lam=0.5, size=(2,3))
array([[2, 0, 0],
[1, 1, 0]])
See also: random_sample, uniform, standard_normal, seed
poly()
numpy.poly(seq_of_zeros)
Return polynomial coefficients given a sequence of roots.
Calculate the coefficients of a polynomial given the zeros
of the polynomial.
If a square matrix is given, then the coefficients for
characteristic equation of the matrix, defined by
:math:`\mathrm{det}(\mathbf{A} - \lambda \mathbf{I})`,
are returned.
Parameters
----------
seq_of_zeros : ndarray
A sequence of polynomial roots or a square matrix.
Returns
-------
coefs : ndarray
A sequence of polynomial coefficients representing the polynomial
:math:`\mathrm{coefs}[0] x^{n-1} + \mathrm{coefs}[1] x^{n-2} +
... + \mathrm{coefs}[2] x + \mathrm{coefs}[n]`
See Also
--------
numpy.poly1d : A one-dimensional polynomial class.
numpy.roots : Return the roots of the polynomial coefficients in p
numpy.polyfit : Least squares polynomial fit
Examples
--------
Given a sequence of polynomial zeros,
>>> b = np.roots([1, 3, 1, 5, 6])
>>> np.poly(b)
array([ 1., 3., 1., 5., 6.])
Given a square matrix,
>>> P = np.array([[19, 3], [-2, 26]])
>>> np.poly(P)
array([ 1., -45., 500.])
poly1d()
numpy.poly1d(...)
A one-dimensional polynomial class.
Parameters
----------
c_or_r : array_like
Polynomial coefficients, in decreasing powers. For example,
``(1, 2, 3)`` implies :math:`x^2 + 2x + 3`. If `r` is set
to True, these coefficients specify the polynomial roots
(values where the polynomial evaluate to 0) instead.
r : bool, optional
If True, `c_or_r` gives the polynomial roots. Default is False.
Examples
--------
Construct the polynomial :math:`x^2 + 2x + 3`:
>>> p = np.poly1d([1, 2, 3])
>>> print np.poly1d(p)
2
1 x + 2 x + 3
Evaluate the polynomial:
>>> p(0.5)
4.25
Find the roots:
>>> p.r
array([-1.+1.41421356j, -1.-1.41421356j])
Show the coefficients:
>>> p.c
array([1, 2, 3])
Display the order (the leading zero-coefficients are removed):
>>> p.order
2
Show the coefficient of the k-th power in the polynomial
(which is equivalent to ``p.c[-(i+1)]``):
>>> p[1]
2
Polynomials can be added, substracted, multplied and divided
(returns quotient and remainder):
>>> p * p
poly1d([ 1, 4, 10, 12, 9])
>>> (p**3 + 4) / p
(poly1d([ 1., 4., 10., 12., 9.]), poly1d([4]))
``asarray(p)`` gives the coefficient array, so polynomials can be
used in all functions that accept arrays:
>>> p**2 # square of polynomial
poly1d([ 1, 4, 10, 12, 9])
>>> np.square(p) # square of individual coefficients
array([1, 4, 9])
The variable used in the string representation of `p` can be modified,
using the `variable` parameter:
>>> p = np.poly1d([1,2,3], variable='z')
>>> print p
2
1 z + 2 z + 3
Construct a polynomial from its roots:
>>> np.poly1d([1, 2], True)
poly1d([ 1, -3, 2])
This is the same polynomial as obtained by:
>>> np.poly1d([1, -1]) * np.poly1d([1, -2])
poly1d([ 1, -3, 2])
>>> from numpy import *
>>> p1 = poly1d([2,3],r=1)
>>> print p1
2
1 x - 5 x + 6
>>> p2 = poly1d([2,3],r=0)
>>> print p2
2 x + 3
>>> print p1+p2
2
1 x - 3 x + 9
>>> quotient,remainder = p1/p2
>>> print quotient,remainder
0.5 x - 3
15
>>> p3 = p1*p2
>>> print p3
3 2
2 x - 7 x - 3 x + 18
>>> p3([1,2,3,4])
array([10, 0, 0, 22])
>>> p3[2]
-7
>>> p3.r
array([-1.5, 3. , 2. ])
>>> p3.c
array([ 2, -7, -3, 18])
>>> p3.o
3
>>> print p3.deriv(m=2)
12 x - 14
>>> print p3.integ(m=2,k=[1,2])
5 4 3 2
0.1 x - 0.5833 x - 0.5 x + 9 x + 1 x + 2
polyadd()
numpy.polyadd(a1, a2)
Returns sum of two polynomials.
Returns sum of polynomials; `a1` + `a2`. Input polynomials are
represented as an array_like sequence of terms or a poly1d object.
Parameters
----------
a1 : {array_like, poly1d}
Polynomial as sequence of terms.
a2 : {array_like, poly1d}
Polynomial as sequence of terms.
Returns
-------
out : {ndarray, poly1d}
Array representing the polynomial terms.
See Also
--------
polyval, polydiv, polymul, polyadd
polyder()
numpy.polyder(p, m=1)
Return the derivative of the specified order of a polynomial.
Parameters
----------
p : poly1d or sequence
Polynomial to differentiate.
A sequence is interpreted as polynomial coefficients, see `poly1d`.
m : int, optional
Order of differentiation (default: 1)
Returns
-------
der : poly1d
A new polynomial representing the derivative.
See Also
--------
polyint : Anti-derivative of a polynomial.
poly1d : Class for one-dimensional polynomials.
Examples
--------
The derivative of the polynomial :math:`x^3 + x^2 + x^1 + 1` is:
>>> p = np.poly1d([1,1,1,1])
>>> p2 = np.polyder(p)
>>> p2
poly1d([3, 2, 1])
which evaluates to:
>>> p2(2.)
17.0
We can verify this, approximating the derivative with
``(f(x + h) - f(x))/h``:
>>> (p(2. + 0.001) - p(2.)) / 0.001
17.007000999997857
The fourth-order derivative of a 3rd-order polynomial is zero:
>>> np.polyder(p, 2)
poly1d([6, 2])
>>> np.polyder(p, 3)
poly1d([6])
>>> np.polyder(p, 4)
poly1d([ 0.])
polydiv()
numpy.polydiv(u, v)
Returns the quotient and remainder of polynomial division.
The input arrays specify the polynomial terms in turn with a length equal
to the polynomial degree plus 1.
Parameters
----------
u : {array_like, poly1d}
Dividend polynomial.
v : {array_like, poly1d}
Divisor polynomial.
Returns
-------
q : ndarray
Polynomial terms of quotient.
r : ndarray
Remainder of polynomial division.
See Also
--------
poly, polyadd, polyder, polydiv, polyfit, polyint, polymul, polysub,
polyval
Examples
--------
.. math:: \frac{3x^2 + 5x + 2}{2x + 1} = 1.5x + 1.75, remainder 0.25
>>> x = np.array([3.0, 5.0, 2.0])
>>> y = np.array([2.0, 1.0])
>>> np.polydiv(x, y)
>>> (array([ 1.5 , 1.75]), array([ 0.25]))
polyfit()
numpy.polyfit(x, y, deg, rcond=None, full=False)
Least squares polynomial fit.
Fit a polynomial ``p(x) = p[0] * x**deg + ... + p[deg]`` of degree `deg`
to points `(x, y)`. Returns a vector of coefficients `p` that minimises
the squared error.
Parameters
----------
x : array_like, shape (M,)
x-coordinates of the M sample points ``(x[i], y[i])``.
y : array_like, shape (M,) or (M, K)
y-coordinates of the sample points. Several data sets of sample
points sharing the same x-coordinates can be fitted at once by
passing in a 2D-array that contains one dataset per column.
deg : int
Degree of the fitting polynomial
rcond : float, optional
Relative condition number of the fit. Singular values smaller than this
relative to the largest singular value will be ignored. The default
value is len(x)*eps, where eps is the relative precision of the float
type, about 2e-16 in most cases.
full : bool, optional
Switch determining nature of return value. When it is
False (the default) just the coefficients are returned, when True
diagnostic information from the singular value decomposition is also
returned.
Returns
-------
p : ndarray, shape (M,) or (M, K)
Polynomial coefficients, highest power first.
If `y` was 2-D, the coefficients for `k`-th data set are in ``p[:,k]``.
residuals, rank, singular_values, rcond : present only if `full` = True
Residuals of the least-squares fit, the effective rank of the scaled
Vandermonde coefficient matrix, its singular values, and the specified
value of `rcond`. For more details, see `linalg.lstsq`.
Warns
-----
RankWarning
The rank of the coefficient matrix in the least-squares fit is
deficient. The warning is only raised if `full` = False.
The warnings can be turned off by
>>> import warnings
>>> warnings.simplefilter('ignore', np.RankWarning)
See Also
--------
polyval : Computes polynomial values.
linalg.lstsq : Computes a least-squares fit.
scipy.interpolate.UnivariateSpline : Computes spline fits.
Notes
-----
The solution minimizes the squared error
.. math ::
E = \sum_{j=0}^k |p(x_j) - y_j|^2
in the equations::
x[0]**n * p[n] + ... + x[0] * p[1] + p[0] = y[0]
x[1]**n * p[n] + ... + x[1] * p[1] + p[0] = y[1]
...
x[k]**n * p[n] + ... + x[k] * p[1] + p[0] = y[k]
The coefficient matrix of the coefficients `p` is a Vandermonde matrix.
`polyfit` issues a `RankWarning` when the least-squares fit is badly
conditioned. This implies that the best fit is not well-defined due
to numerical error. The results may be improved by lowering the polynomial
degree or by replacing `x` by `x` - `x`.mean(). The `rcond` parameter
can also be set to a value smaller than its default, but the resulting
fit may be spurious: including contributions from the small singular
values can add numerical noise to the result.
Note that fitting polynomial coefficients is inherently badly conditioned
when the degree of the polynomial is large or the interval of sample points
is badly centered. The quality of the fit should always be checked in these
cases. When polynomial fits are not satisfactory, splines may be a good
alternative.
References
----------
.. [1] Wikipedia, "Curve fitting",
http://en.wikipedia.org/wiki/Curve_fitting
.. [2] Wikipedia, "Polynomial interpolation",
http://en.wikipedia.org/wiki/Polynomial_interpolation
Examples
--------
>>> x = np.array([0.0, 1.0, 2.0, 3.0, 4.0, 5.0])
>>> y = np.array([0.0, 0.8, 0.9, 0.1, -0.8, -1.0])
>>> z = np.polyfit(x, y, 3)
array([ 0.08703704, -0.81349206, 1.69312169, -0.03968254])
It is convenient to use `poly1d` objects for dealing with polynomials:
>>> p = np.poly1d(z)
>>> p(0.5)
0.6143849206349179
>>> p(3.5)
-0.34732142857143039
>>> p(10)
22.579365079365115
High-order polynomials may oscillate wildly:
>>> p30 = np.poly1d(np.polyfit(x, y, 30))
/... RankWarning: Polyfit may be poorly conditioned...
>>> p30(4)
-0.80000000000000204
>>> p30(5)
-0.99999999999999445
>>> p30(4.5)
-0.10547061179440398
Illustration:
>>> import matplotlib.pyplot as plt
>>> xp = np.linspace(-2, 6, 100)
>>> plt.plot(x, y, '.', xp, p(xp), '-', xp, p30(xp), '--')
>>> plt.ylim(-2,2)
>>> plt.show()
>>> from numpy import *
>>> x = array([1,2,3,4,5])
>>> y = array([6, 11, 18, 27, 38])
>>> polyfit(x,y,2)
array([ 1., 2., 3.])
>>> polyfit(x,y,1)
array([ 8., -4.])
See also: lstsq
polyint()
numpy.polyint(p, m=1, k=None)
Return an antiderivative (indefinite integral) of a polynomial.
The returned order `m` antiderivative `P` of polynomial `p` satisfies
:math:`\frac{d^m}{dx^m}P(x) = p(x)` and is defined up to `m - 1`
integration constants `k`. The constants determine the low-order
polynomial part
.. math:: \frac{k_{m-1}}{0!} x^0 + \ldots + \frac{k_0}{(m-1)!}x^{m-1}
of `P` so that :math:`P^{(j)}(0) = k_{m-j-1}`.
Parameters
----------
p : {array_like, poly1d}
Polynomial to differentiate.
A sequence is interpreted as polynomial coefficients, see `poly1d`.
m : int, optional
Order of the antiderivative. (Default: 1)
k : {None, list of `m` scalars, scalar}, optional
Integration constants. They are given in the order of integration:
those corresponding to highest-order terms come first.
If ``None`` (default), all constants are assumed to be zero.
If `m = 1`, a single scalar can be given instead of a list.
See Also
--------
polyder : derivative of a polynomial
poly1d.integ : equivalent method
Examples
--------
The defining property of the antiderivative:
>>> p = np.poly1d([1,1,1])
>>> P = np.polyint(p)
poly1d([ 0.33333333, 0.5 , 1. , 0. ])
>>> np.polyder(P) == p
True
The integration constants default to zero, but can be specified:
>>> P = np.polyint(p, 3)
>>> P(0)
0.0
>>> np.polyder(P)(0)
0.0
>>> np.polyder(P, 2)(0)
0.0
>>> P = np.polyint(p, 3, k=[6,5,3])
>>> P
poly1d([ 0.01666667, 0.04166667, 0.16666667, 3., 5., 3. ])
Note that 3 = 6 / 2!, and that the constants are given in the order of
integrations. Constant of the highest-order polynomial term comes first:
>>> np.polyder(P, 2)(0)
6.0
>>> np.polyder(P, 1)(0)
5.0
>>> P(0)
3.0
polymul()
numpy.polymul(a1, a2)
Returns product of two polynomials represented as sequences.
The input arrays specify the polynomial terms in turn with a length equal
to the polynomial degree plus 1.
Parameters
----------
a1 : {array_like, poly1d}
First multiplier polynomial.
a2 : {array_like, poly1d}
Second multiplier polynomial.
Returns
-------
out : {ndarray, poly1d}
Product of inputs.
See Also
--------
poly, polyadd, polyder, polydiv, polyfit, polyint, polysub,
polyval
polysub()
numpy.polysub(a1, a2)
Returns difference from subtraction of two polynomials input as sequences.
Returns difference of polynomials; `a1` - `a2`. Input polynomials are
represented as an array_like sequence of terms or a poly1d object.
Parameters
----------
a1 : {array_like, poly1d}
Minuend polynomial as sequence of terms.
a2 : {array_like, poly1d}
Subtrahend polynomial as sequence of terms.
Returns
-------
out : {ndarray, poly1d}
Array representing the polynomial terms.
See Also
--------
polyval, polydiv, polymul, polyadd
Examples
--------
.. math:: (2 x^2 + 10x - 2) - (3 x^2 + 10x -4) = (-x^2 + 2)
>>> np.polysub([2, 10, -2], [3, 10, -4])
array([-1, 0, 2])
polyval()
numpy.polyval(p, x)
Evaluate a polynomial at specific values.
If p is of length N, this function returns the value:
p[0]*(x**N-1) + p[1]*(x**N-2) + ... + p[N-2]*x + p[N-1]
If x is a sequence then p(x) will be returned for all elements of x.
If x is another polynomial then the composite polynomial p(x) will
be returned.
Parameters
----------
p : {array_like, poly1d}
1D array of polynomial coefficients from highest degree to zero or an
instance of poly1d.
x : {array_like, poly1d}
A number, a 1D array of numbers, or an instance of poly1d.
Returns
-------
values : {ndarray, poly1d}
If either p or x is an instance of poly1d, then an instance of poly1d
is returned, otherwise a 1D array is returned. In the case where x is
a poly1d, the result is the composition of the two polynomials, i.e.,
substitution is used.
See Also
--------
poly1d: A polynomial class.
Notes
-----
Horner's method is used to evaluate the polynomial. Even so, for
polynomials of high degree the values may be inaccurate due to
rounding errors. Use carefully.
Examples
--------
>>> np.polyval([3,0,1], 5) # 3 * 5**2 + 0 * 5**1 + 1
76
power()
numpy.power(...)
y = power(x1,x2)
Returns element-wise base array raised to power from second array.
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]])
ppmt()
numpy.ppmt(rate, per, nper, pv, fv=0.0, when='end')
Not implemented. Compute the payment against loan principal.
Parameters
----------
rate : array_like
Rate of interest (per period)
per : array_like, int
Amount paid against the loan changes. The `per` is the period of
interest.
nper : array_like
Number of compounding periods
pv : array_like
Present value
fv : array_like, optional
Future value
when : {{'begin', 1}, {'end', 0}}, {string, int}
When payments are due ('begin' (1) or 'end' (0))
See Also
--------
pmt, pv, ipmt
prod()
numpy.prod(a, axis=None, dtype=None, out=None)
Return the product of array elements over a given axis.
Parameters
----------
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 of the
output values will be cast if necessary.
Returns
-------
product_along_axis : ndarray, 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
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.])
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
ndarray.prod(...)
a.prod(axis=None, dtype=None, out=None)
Return the product of the array elements over the given axis
Refer to `numpy.prod` for full documentation.
See Also
--------
numpy.prod : equivalent function
>>> from numpy import *
>>> a = array([1,2,3])
>>> a.prod()
6
>>> prod(a)
6
>>> a = array([[1,2,3],[4,5,6]])
>>> a.prod(dtype=float)
720.0
>>> a.prod(axis=0)
array([ 4, 10, 18])
>>> a.prod(axis=1)
array([ 6, 120])
See also: cumprod, sum
product()
numpy.product(a, axis=None, dtype=None, out=None)
Return the product of array elements over a given axis.
See Also
--------
prod : equivalent function; see for details.
ptp()
numpy.ptp(a, axis=None, out=None)
Range of values (maximum - minimum) along an axis.
The name of the function comes from the acronym for 'peak to peak'.
Parameters
----------
a : array_like
Input values.
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 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.
Examples
--------
>>> x = np.arange(4).reshape((2,2))
>>> x
array([[0, 1],
[2, 3]])
>>> np.ptp(x, axis=0)
array([2, 2])
>>> np.ptp(x, axis=1)
array([1, 1])
ndarray.ptp(...)
a.ptp(axis=None, out=None)
Peak to peak (maximum - minimum) value along a given axis.
Refer to `numpy.ptp` for full documentation.
See Also
--------
numpy.ptp : equivalent function
>>> from numpy import *
>>> a = array([5,15,25])
>>> a.ptp()
20
>>> a = array([[5,15,25],[3,13,33]])
>>> a.ptp()
30
>>> a.ptp(axis=0)
array([2, 2, 8])
>>> a.ptp(axis=1)
array([20, 30])
See also: max, min
put()
numpy.put(a, ind, v, mode='raise')
Changes specific elements of one array by replacing from another array.
Set `a`.flat[n] = `v`\[n] for all n in `ind`. If `v` is shorter than
`ind`, it will repeat which is different than `a[ind]` = `v`.
Parameters
----------
a : array_like (contiguous)
Target array.
ind : array_like
Target indices, interpreted as integers.
v : array_like
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
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):
::
ind = array(indices, copy=False)
v = array(values, copy=False).astype(a.dtype)
for i in ind: a.flat[i] = v[i]
Examples
--------
>>> x = np.arange(5)
>>> np.put(x,[0,2,4],[-1,-2,-3])
>>> print x
[-1 1 -2 3 -3]
ndarray.put(...)
a.put(indices, values, mode='raise')
Set a.flat[n] = values[n] for all n in indices.
Refer to `numpy.put` for full documentation.
See Also
--------
numpy.put : equivalent function
>>> from nump import *
>>> a = array([10,20,30,40])
>>> a.put([60,70,80], [0,3,2])
>>> a
array([60, 20, 80, 70])
>>> a[[0,3,2]] = [60,70,80]
>>> a.put([40,50], [0,3,2,1])
>>> a
array([40, 50, 40, 50])
>>> put(a, [0,3], [90])
>>> a
array([90, 50, 40, 90])
See also: putmask, take
putmask()
numpy.putmask(...)
putmask(a, mask, values)
Changes elements of an array based on conditional and input values.
Sets `a`.flat[n] = `values`\[n] for each n where `mask`.flat[n] is true.
If `values` is not the same size as `a` and `mask` then it will repeat.
This gives behavior different from `a[mask] = values`.
Parameters
----------
a : array_like
Array to put data into
mask : array_like
Boolean mask array
values : array_like
Values to put
See Also
--------
place, put, take
Examples
--------
>>> a = np.array([10,20,30,40])
>>> mask = np.array([True,False,True,True])
>>> a.putmask([60,70,80,90], mask)
>>> a
array([60, 20, 80, 90])
>>> a = np.array([10,20,30,40])
>>> a[mask]
array([60, 80, 90])
>>> a[mask] = np.array([60,70,80,90])
>>> a
array([60, 20, 70, 80])
>>> a.putmask([10,90], mask)
>>> a
array([10, 20, 10, 90])
>>> np.putmask(a, mask, [60,70,80,90])
>>> from nump import *
>>> a = array([10,20,30,40])
>>> mask = array([True,False,True,True])
>>> a.putmask([60,70,80,90], mask)
>>> a
array([60, 20, 80, 90])
>>> a = array([10,20,30,40])
>>> a[mask]
array([60, 80, 90])
>>> a[mask] = array([60,70,80,90])
>>> a
array([60, 20, 70, 80])
>>> a.putmask([10,90], mask)
>>> a
array([10, 20, 10, 90])
>>> putmask(a, mask, [60,70,80,90])
See also: put, take
pv()
numpy.pv(rate, nper, pmt, fv=0.0, when='end')
Compute the present value.
Parameters
----------
rate : array_like
Rate of interest (per period)
nper : array_like
Number of compounding periods
pmt : array_like
Payment
fv : array_like, optional
Future value
when : {{'begin', 1}, {'end', 0}}, {string, int}, optional
When payments are due ('begin' (1) or 'end' (0))
Returns
-------
out : ndarray, float
Present value of a series of payments or investments.
Notes
-----
The present value ``pv`` is computed by solving the equation::
fv +
pv*(1 + rate)**nper +
pmt*(1 + rate*when)/rate*((1 + rate)**nper - 1) = 0
or, when ``rate = 0``::
fv + pv + pmt * nper = 0
r_
numpy.r_
Translates slice objects to concatenation along the first axis.
For example:
>>> np.r_[np.array([1,2,3]), 0, 0, np.array([4,5,6])]
array([1, 2, 3, 0, 0, 4, 5, 6])
>>> from numpy import *
>>> r_[1:5]
array([1, 2, 3, 4])
>>> r_[1:10:4]
array([1, 5, 9])
>>> r_[1:10:4j]
array([ 1., 4., 7., 10.])
>>> r_[1:5,7,1:10:4]
array([1, 2, 3, 4, 7, 1, 5, 9])
>>> r_['r', 1:3]
matrix([[1, 2]])
>>> r_['c',1:3]
matrix([[1],
[2]])
>>> a = array([[1,2,3],[4,5,6]])
>>> r_[a,a]
array([[1, 2, 3],
[4, 5, 6],
[1, 2, 3],
[4, 5, 6]])
>>> r_['-1',a,a]
array([[1, 2, 3, 1, 2, 3],
[4, 5, 6, 4, 5, 6]])
See also: c_, s_, arange, linspace, hstack, vstack, column_stack, concatenate, bmat
radians()
numpy.radians(...)
y = radians(x)
Convert angles from degrees to radians.
Parameters
----------
x : array_like
Angles in degrees.
Returns
-------
y : ndarray
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
randint()
numpy.random.randint(...)
randint(low, high=None, size=None)
Return random integers x such that low <= x < high.
If high is None, then 0 <= x < low.
Synonym for random_integers()
See random_integers
random_integers()
numpy.random.random_integers(...)
random_integers(low, high=None, size=None)
Return random integers x such that low <= x <= high.
If high is None, then 1 <= x <= low.
>>> from numpy import *
>>> from numpy.random import *
>>> random_integers(-1,5,(2,2))
array([[ 3, -1],
[-1, 0]])
See also: random_sample, uniform, poisson, seed
random_sample()
numpy.random.random_sample(...)
random_sample(size=None)
Return random floats in the half-open interval [0.0, 1.0).
>>> from numpy import *
>>> from numpy.random import *
>>> random_sample((3,2))
array([[ 0.76228008, 0.00210605],
[ 0.44538719, 0.72154003],
[ 0.22876222, 0.9452707 ]])
See also: ranf, sample, rand, seed
ranf()
numpy.random.ranf(...)
random_sample(size=None)
Return random floats in the half-open interval [0.0, 1.0).
Synonym for random_sample
See random_sample, sample
rank()
numpy.rank(a)
Return the number of dimensions of an array.
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.
Returns
-------
number_of_dimensions : int
The number of dimensions in the array.
See Also
--------
ndim : equivalent function
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])
1
>>> np.rank(np.array([[1,2,3],[4,5,6]]))
2
>>> np.rank(1)
0
rate()
numpy.rate(nper, pmt, pv, fv, when='end', guess=0.10000000000000001, tol=9.9999999999999995e-007, maxiter=100)
Compute the rate of interest per period.
Parameters
----------
nper : array_like
Number of compounding periods
pmt : array_like
Payment
pv : array_like
Present value
fv : array_like
Future value
when : {{'begin', 1}, {'end', 0}}, {string, int}, optional
When payments are due ('begin' (1) or 'end' (0))
guess : float, optional
Starting guess for solving the rate of interest
tol : float, optional
Required tolerance for the solution
maxiter : int, optional
Maximum iterations in finding the solution
Notes
-----
The rate of interest ``rate`` is computed by solving the equation::
fv + pv*(1+rate)**nper + pmt*(1+rate*when)/rate * ((1+rate)**nper - 1) = 0
or, if ``rate = 0``::
fv + pv + pmt * nper = 0
ravel()
numpy.ravel(a, order='C')
Return a flattened array.
A 1-d array, containing the elements of the input, is returned. A copy is
made only if needed.
Parameters
----------
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
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 : ndarray
Output of the same dtype as `a`, and of shape ``(a.size(),)`` (or
``(np.prod(a.shape),)``).
See Also
--------
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
--------
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]
ndarray.ravel(...)
a.ravel([order])
Return a flattened array.
Refer to `numpy.ravel` for full documentation.
See Also
--------
numpy.ravel : equivalent function
>>> from numpy import *
>>> a = array([[1,2],[3,4]])
>>> a.ravel()
array([1, 2, 3, 4])
>>> b = a[:,0].ravel()
>>> b
array([1, 3])
>>> c = a[0,:].ravel()
>>> c
array([1, 2])
>>> b[0] = -1
>>> c[1] = -2
>>> a
array([[ 1, -2],
[ 3, 4]])
>>> ravel(a)
See also: flatten
real() or .real
numpy.real(val)
Return the real part of the elements of the array.
Parameters
----------
val : array_like
Input array.
Returns
-------
out : ndarray
If `val` is real, the type of `val` is used for the output. If `val`
has complex elements, the returned type is float.
See Also
--------
real_if_close, imag, angle
Examples
--------
>>> a = np.array([1+2j,3+4j,5+6j])
>>> a.real
array([ 1., 3., 5.])
>>> a.real = 9
>>> a
array([ 9.+2.j, 9.+4.j, 9.+6.j])
>>> a.real = np.array([9,8,7])
>>> a
array([ 9.+2.j, 8.+4.j, 7.+6.j])
ndarray.real
The real part of the array.
Examples
--------
>>> x = np.sqrt([1+0j, 0+1j])
>>> x.real
array([ 1. , 0.70710678])
>>> x.real.dtype
dtype('float64')
>>> from numpy import *
>>> a = array([1+2j,3+4j,5+6j])
>>> a.real
array([ 1., 3., 5.])
>>> a.real = 9
>>> a
array([ 9.+2.j, 9.+4.j, 9.+6.j])
>>> a.real = array([9,8,7])
>>> a
array([ 9.+2.j, 8.+4.j, 7.+6.j])
See also: imag, angle
real_if_close()
numpy.real_if_close(a, tol=100)
If complex input returns a real array if complex parts are close to zero.
"Close to zero" is defined as `tol` * (machine epsilon of the type for
`a`).
Parameters
----------
a : array_like
Input array.
tol : scalar
Tolerance for the complex part of the elements in the array.
Returns
-------
out : ndarray
If `a` is real, the type of `a` is used for the output. If `a`
has complex elements, the returned type is float.
See Also
--------
real, imag, angle
Notes
-----
Machine epsilon varies from machine to machine and between data types
but Python floats on most platforms have a machine epsilon equal to
2.2204460492503131e-16. You can use 'np.finfo(np.float).eps' to print
out the machine epsilon for floats.
Examples
--------
>>> np.finfo(np.float).eps # DOCTEST +skip
2.2204460492503131e-16
>>> np.real_if_close([2.1 + 4e-14j], tol = 1000)
array([ 2.1])
>>> np.real_if_close([2.1 + 4e-13j], tol = 1000)
array([ 2.1 +4.00000000e-13j])
recarray()
numpy.recarray(...)
Construct an ndarray that allows field access using attributes.
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 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
--------
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')])
numpy.core.records.recarray(...)
Construct an ndarray that allows field access using attributes.
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 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
--------
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')])
>>> from numpy import *
>>> num = 2
>>> a = recarray(num, formats='i4,f8,f8',names='id,x,y')
>>> a['id'] = [3,4]
>>> a['id']
array([3, 4])
>>> a = rec.fromrecords([(35,1.2,7.3),(85,9.3,3.2)], names='id,x,y')
>>> a['id']
array([35, 85])
See also: array, dtype
reciprocal()
numpy.reciprocal(...)
y = reciprocal(x)
Return element-wise reciprocal.
Parameters
----------
x : array_like
Input value.
Returns
-------
y : ndarray
Return value.
Examples
--------
>>> reciprocal(2.)
0.5
>>> reciprocal([1, 2., 3.33])
array([ 1. , 0.5 , 0.3003003])
reduce
>>> from numpy import *
>>> add.reduce(array([1.,2.,3.,4.]))
10.0
>>> multiply.reduce(array([1.,2.,3.,4.]))
24.0
>>> add.reduce(array([[1,2,3],[4,5,6]]), axis = 0)
array([5, 7, 9])
>>> add.reduce(array([[1,2,3],[4,5,6]]), axis = 1)
array([ 6, 15])
See also: accumulate, sum, prod
remainder()
numpy.remainder(...)
y = remainder(x1,x2)
Returns element-wise remainder of division.
Computes `x1 - floor(x1/x2)*x2`.
Parameters
----------
x1 : array_like
Dividend array.
x2 : array_like
Divisor array.
Returns
-------
y : ndarray
The remainder of 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])
repeat()
numpy.repeat(a, repeats, axis=None)
Repeat elements of an array.
Parameters
----------
a : array_like
Input array.
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 : ndarray
Output array which has the same shape as `a`, except along
the given axis.
See Also
--------
tile : Tile an array.
Examples
--------
>>> x = np.array([[1,2],[3,4]])
>>> np.repeat(x, 2)
array([1, 1, 2, 2, 3, 3, 4, 4])
>>> np.repeat(x, 3, axis=1)
array([[1, 1, 1, 2, 2, 2],
[3, 3, 3, 4, 4, 4]])
>>> np.repeat(x, [1, 2], axis=0)
array([[1, 2],
[3, 4],
[3, 4]])
ndarray.repeat(...)
a.repeat(repeats, axis=None)
Repeat elements of an array.
Refer to `numpy.repeat` for full documentation.
See Also
--------
numpy.repeat : equivalent function
>>> from numpy import *
>>> repeat(7., 4)
array([ 7., 7., 7., 7.])
>>> a = array([10,20])
>>> a.repeat([3,2])
array([10, 10, 10, 20, 20])
>>> repeat(a, [3,2])
>>> a = array([[10,20],[30,40]])
>>> a.repeat([3,2,1,1])
array([10, 10, 10, 20, 20, 30, 40])
>>> a.repeat([3,2],axis=0)
array([[10, 20],
[10, 20],
[10, 20],
[30, 40],
[30, 40]])
>>> a.repeat([3,2],axis=1)
array([[10, 10, 10, 20, 20],
[30, 30, 30, 40, 40]])
See also: tile
require()
numpy.require(a, dtype=None, requirements=None)
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
The object to be converted to a type-and-requirement satisfying array
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 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.
reshape()
numpy.reshape(a, newshape, order='C')
Gives a new shape to an array without changing its data.
Parameters
----------
a : array_like
Array to be reshaped.
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.
One shape dimension can be -1. In this case, the value is inferred
from the length of the array and remaining dimensions.
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 : ndarray
This will be a new view object if possible; otherwise, it will
be a copy.
See Also
--------
ndarray.reshape : Equivalent method.
Examples
--------
>>> a = np.array([[1,2,3], [4,5,6]])
>>> np.reshape(a, 6)
array([1, 2, 3, 4, 5, 6])
>>> np.reshape(a, 6, order='F')
array([1, 4, 2, 5, 3, 6])
>>> np.reshape(a, (3,-1)) # the unspecified value is inferred to be 2
array([[1, 2],
[3, 4],
[5, 6]])
ndarray.reshape(...)
a.reshape(shape, order='C')
Returns an array containing the same data with a new shape.
Refer to `numpy.reshape` for full documentation.
See Also
--------
numpy.reshape : equivalent function
>>> from numpy import *
>>> x = arange(12)
>>> x.reshape(3,4)
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
>>> x.reshape(3,2,2)
array([[[ 0, 1],
[ 2, 3]],
[[ 4, 5],
[ 6, 7]],
[[ 8, 9],
[10, 11]]])
>>> x.reshape(2,-1)
array([[ 0, 1, 2, 3, 4, 5],
[ 6, 7, 8, 9, 10, 11]])
>>> x.reshape(12)
array([0,1,2,3,4,5,6,7,8,9,10,11])
>>> reshape(x,(2,6))
See also: shape, resize
resize()
numpy.resize(a, new_shape)
Return a new array with the specified shape.
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 resized.
new_shape : {tuple, int}
Shape of resized array.
Returns
-------
reshaped_array : ndarray
The new array is formed from the data in the old array, repeated if
necessary to fill out the required number of elements.
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]])
ndarray.resize(...)
a.resize(new_shape, refcheck=True, order=False)
Change shape and size of array in-place.
Parameters
----------
a : ndarray
Input array.
new_shape : {tuple, int}
Shape of resized array.
refcheck : bool, optional
If False, memory referencing will not be checked. Default is True.
order : bool, optional
<needs an explanation>. Default if False.
Returns
-------
None
Raises
------
ValueError
If `a` does not own its own data, or references or views to it exist.
Examples
--------
Shrinking an array: array is flattened in C-order, resized, and reshaped:
>>> a = np.array([[0,1],[2,3]])
>>> a.resize((2,1))
>>> a
array([[0],
[1]])
Enlarging an array: as above, but missing entries are filled with zeros:
>>> b = np.array([[0,1],[2,3]])
>>> b.resize((2,3))
>>> b
array([[0, 1, 2],
[3, 0, 0]])
Referencing an array prevents resizing:
>>> c = a
>>> a.resize((1,1))
Traceback (most recent call last):
...
ValueError: cannot resize an array that has been referenced ...
>>> from numpy import *
>>> a = array([1,2,3,4])
>>> a.resize(2,2)
>>> print a
[[1 2]
[3 4]]
>>> a.resize(3,2)
>>> print a
[[1 2]
[3 4]
[0 0]]
>>> a.resize(2,4)
>>> print a
[[1 2 3 4]
[0 0 0 0]]
>>> a.resize(2,1)
>>> print a
[[1]
[2]]
But, there is a caveat:
>>> b = array([1,2,3,4])
>>> c = b # c is reference to b, it doesn't 'own' its data
>>> c.resize(2,2) # no problem, nr of elements doesn't change
>>> c.resize(2,3) # doesn't work, c is only a reference
Traceback (most recent call last):
File "<stdin>", line 1, in ?
ValueError: cannot resize an array that has been referenced or is referencing
another array in this way. Use the resize function
>>> b.resize(2,3) # doesn't work, b is referenced by another array
Traceback (most recent call last):
File "<stdin>", line 1, in ?
ValueError: cannot resize an array that has been referenced or is referencing
another array in this way. Use the resize function
and it's not always obvious what the reference is:
>>> d = arange(4)
>>> d
array([0, 1, 2, 3])
>>> d.resize(5) # doesn't work, but where's the reference?
Traceback (most recent call last):
File "<stdin>", line 1, in ?
ValueError: cannot resize an array that has been referenced or is referencing
another array in this way. Use the resize function
>>> _ # '_' was a reference to d!
array([0, 1, 2, 3])
>>> d = resize(d, 5) # this does work, however
>>> d
array([0, 1, 2, 3, 0])
See also: reshape
restoredot()
numpy.restoredot(...)
restoredot() restores dots to defaults.
right_shift()
numpy.right_shift(...)
y = right_shift(x1,x2)
Shift the bits of an integer to the right.
Bits are shifted to the right by removing `x2` bits at the right of `x1`.
Since the internal representation of numbers is in binary format, this
operation is equivalent to dividing `x1` by ``2**x2``.
Parameters
----------
x1 : array_like, int
Input values.
x2 : array_like, int
Number of bits to remove at the right of `x1`.
Returns
-------
out : ndarray, int
Return `x1` with bits shifted `x2` times to the right.
See Also
--------
left_shift : Shift the bits of an integer to the left.
binary_repr : Return the binary representation of the input number
as a string.
Examples
--------
>>> np.right_shift(10, [1,2,3])
array([5, 2, 1])
rint()
numpy.rint(...)
y = rint(x)
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.])
roll()
numpy.roll(a, shift, axis=None)
Roll array elements along a given axis.
Elements that roll beyond the last position are re-introduced at
the first.
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]])
rollaxis()
numpy.rollaxis(a, axis, start=0)
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).shape
(5, 3, 4, 6)
>>> np.rollaxis(a, 1, 4).shape
(3, 5, 6, 4)
>>> from numpy import *
>>> a = arange(3*4*5).reshape(3,4,5)
>>> a.shape
(3, 4, 5)
>>> b = rollaxis(a,1,0)
>>> b.shape
(4, 3, 5)
>>> b = rollaxis(a,0,2)
>>> b.shape
(4, 3, 5)
See also: swapaxes, transpose
roots()
numpy.roots(p)
Return the roots of a polynomial with coefficients given in p.
The values in the rank-1 array `p` are coefficients of a polynomial.
If the length of `p` is n+1 then the polynomial is described by
p[0] * x**n + p[1] * x**(n-1) + ... + p[n-1]*x + p[n]
Parameters
----------
p : array_like of shape(M,)
Rank-1 array of polynomial co-efficients.
Returns
-------
out : ndarray
An array containing the complex roots of the polynomial.
Raises
------
ValueError:
When `p` cannot be converted to a rank-1 array.
Examples
--------
>>> coeff = [3.2, 2, 1]
>>> print np.roots(coeff)
[-0.3125+0.46351241j -0.3125-0.46351241j]
rot90()
numpy.rot90(m, k=1)
Rotate an array by 90 degrees in the counter-clockwise direction.
The first two dimensions are rotated; therefore, the array must be at
least 2-D.
Parameters
----------
m : array_like
Array of two or more dimensions.
k : integer
Number of times the array is rotated by 90 degrees.
Returns
-------
y : ndarray
Rotated array.
See Also
--------
fliplr : Flip an array horizontally.
flipud : Flip an array vertically.
Examples
--------
>>> m = np.array([[1,2],[3,4]], int)
>>> m
array([[1, 2],
[3, 4]])
>>> np.rot90(m)
array([[2, 4],
[1, 3]])
>>> np.rot90(m, 2)
array([[4, 3],
[2, 1]])
>>> from numpy import *
>>> a = arange(12).reshape(4,3)
>>> a
array([[ 0, 1, 2],
[ 3, 4, 5],
[ 6, 7, 8],
[ 9, 10, 11]])
>>> rot90(a)
array([[ 2, 5, 8, 11],
[ 1, 4, 7, 10],
[ 0, 3, 6, 9]])
See also: fliplr, flipud
round()
numpy.round(a, decimals=0, out=None)
Round an array to the given number of decimals.
Refer to `around` for full documentation.
See Also
--------
around : equivalent function
ndarray.round(...)
a.round(decimals=0, out=None)
Return an array rounded a to the given number of decimals.
Refer to `numpy.around` for full documentation.
See Also
--------
numpy.around : equivalent function
round(decimals=0, out=None) -> reference to rounded values.
>>> from numpy import *
>>> array([1.2345, -1.647]).round()
array([ 1., -2.])
>>> array([1, -1]).round()
array([ 1, -1])
>>> array([1.2345, -1.647]).round(decimals=1)
array([ 1.2, -1.6])
>>> array([1.2345+2.34j, -1.647-0.238j]).round()
array([ 1.+2.j, -2.-0.j])
>>> array([0.0, 0.5, 1.0, 1.5, 2.0, 2.5]).round()
array([ 0., 0., 1., 2., 2., 2.])
>>> a = zeros(3, dtype=int)
>>> array([1.2345, -1.647, 3.141]).round(out=a)
array([ 1, -2, 3])
>>> a
array([ 1, -2, 3])
>>> round_(array([1.2345, -1.647]))
array([ 1., -2.])
>>> around(array([1.2345, -1.647]))
array([ 1., -2.])
See also: ceil, floor, fix, astype
round_()
numpy.round_(a, decimals=0, out=None)
Round an array to the given number of decimals.
Refer to `around` for full documentation.
See Also
--------
around : equivalent function
row_stack()
numpy.row_stack(tup)
Stack arrays vertically.
`vstack` can be used to rebuild arrays divided by `vsplit`.
Parameters
----------
tup : sequence of arrays
Tuple containing arrays to be stacked. The arrays must have the same
shape along all but the first axis.
See Also
--------
array_split : Split an array into a list of multiple sub-arrays of
near-equal size.
split : Split array into a list of multiple sub-arrays of equal size.
vsplit : Split array into a list of multiple sub-arrays vertically.
dsplit : Split array into a list of multiple sub-arrays along the 3rd axis
(depth).
concatenate : Join arrays together.
hstack : Stack arrays in sequence horizontally (column wise).
dstack : Stack arrays in sequence depth wise (along third dimension).
Examples
--------
>>> a = np.array([1, 2, 3])
>>> b = np.array([2, 3, 4])
>>> np.vstack((a,b))
array([[1, 2, 3],
[2, 3, 4]])
>>> a = np.array([[1], [2], [3]])
>>> b = np.array([[2], [3], [4]])
>>> np.vstack((a,b))
array([[1],
[2],
[3],
[2],
[3],
[4]])
s_
numpy.s_
A nicer way to build up index tuples for arrays.
For any index combination, including slicing and axis insertion,
'a[indices]' is the same as 'a[index_exp[indices]]' for any
array 'a'. However, 'index_exp[indices]' can be used anywhere
in Python code and returns a tuple of slice objects that can be
used in the construction of complex index expressions.
>>> from numpy import *
>>> s_[1:5]
slice(1, 5, None)
>>> s_[1:10:4]
slice(1, 10, 4)
>>> s_[1:10:4j]
slice(1, 10, 4j)
>>> s_['r',1:3]
('r', slice(1, 3, None))
>>> s_['c',1:3]
('c', slice(1, 3, None))
See also: r_, c_, slice, index_exp
safe_eval()
numpy.safe_eval(source)
Protected string evaluation.
Evaluate a string containing a Python literal expression without
allowing the execution of arbitrary non-literal code.
Parameters
----------
source : str
Returns
-------
obj : object
Raises
------
SyntaxError
If the code has invalid Python syntax, or if it contains non-literal
code.
Examples
--------
>>> from numpy.lib.utils import safe_eval
>>> safe_eval('1')
1
>>> safe_eval('[1, 2, 3]')
[1, 2, 3]
>>> safe_eval('{"foo": ("bar", 10.0)}')
{'foo': ('bar', 10.0)}
>>> safe_eval('import os')
Traceback (most recent call last):
...
SyntaxError: invalid syntax
>>> safe_eval('open("/home/user/.ssh/id_dsa").read()')
Traceback (most recent call last):
...
SyntaxError: Unsupported source construct: compiler.ast.CallFunc
>>> safe_eval('dict')
Traceback (most recent call last):
...
SyntaxError: Unknown name: dict
sample()
numpy.random.sample(...)
random_sample(size=None)
Return random floats in the half-open interval [0.0, 1.0).
Synonym for random_sample
See also: random_sample, ranf
save()
numpy.save(file, arr)
Save an array to a binary file in NumPy format.
Parameters
----------
f : file or string
File or filename to which the data is saved. If the filename
does not already have a ``.npy`` extension, it is added.
x : array_like
Array data.
Examples
--------
>>> from tempfile import TemporaryFile
>>> outfile = TemporaryFile()
>>> x = np.arange(10)
>>> np.save(outfile, x)
>>> outfile.seek(0)
>>> np.load(outfile)
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
savetxt()
numpy.savetxt(fname, X, fmt='%.18e', delimiter=' ')
Save an array to file.
Parameters
----------
fname : filename or a file handle
If the filename ends in .gz, the file is automatically saved in
compressed gzip format. The load() command understands gzipped
files transparently.
X : array_like
Data.
fmt : string or sequence of strings
A single format (%10.5f), a sequence of formats, or a
multi-format string, e.g. 'Iteration %d -- %10.5f', in which
case delimiter is ignored.
delimiter : str
Character separating columns.
Notes
-----
Further explanation of the `fmt` parameter
(``%[flag]width[.precision]specifier``):
flags:
``-`` : left justify
``+`` : Forces to preceed result with + or -.
``0`` : Left pad the number with zeros instead of space (see width).
width:
Minimum number of characters to be printed. The value is not truncated
if it has more characters.
precision:
- For integer specifiers (eg. ``d,i,o,x``), the minimum number of
digits.
- For ``e, E`` and ``f`` specifiers, the number of digits to print
after the decimal point.
- For ``g`` and ``G``, the maximum number of significant digits.
- For ``s``, the maximum number of characters.
specifiers:
``c`` : character
``d`` or ``i`` : signed decimal integer
``e`` or ``E`` : scientific notation with ``e`` or ``E``.
``f`` : decimal floating point
``g,G`` : use the shorter of ``e,E`` or ``f``
``o`` : signed octal
``s`` : string of characters
``u`` : unsigned decimal integer
``x,X`` : unsigned hexadecimal integer
This is not an exhaustive specification.
Examples
--------
>>> savetxt('test.out', x, delimiter=',') # X is an array
>>> savetxt('test.out', (x,y,z)) # x,y,z equal sized 1D arrays
>>> savetxt('test.out', x, fmt='%1.4e') # use exponential notation
>>> from numpy import *
>>> savetxt("myfile.txt", data)
>>> savetxt("myfile.txt", x)
>>> savetxt("myfile.txt", (x,y))
>>> savetxt("myfile.txt", transpose((x,y)))
>>> savetxt("myfile.txt", transpose((x,y)), fmt='%6.3f')
>>> savetxt("myfile.txt", data, delimiter = ';')
See also: loadtxt, tofile
savez()
numpy.savez(file, *args, **kwds)
Save several arrays into an .npz file format which is a zipped-archive
of arrays
If keyword arguments are given, then filenames are taken from the keywords.
If arguments are passed in with no keywords, then stored file names are
arr_0, arr_1, etc.
Parameters
----------
file : string
File name of .npz file.
args : Arguments
Function arguments.
kwds : Keyword arguments
Keywords.
sctype2char()
numpy.sctype2char(sctype)
searchsorted()
numpy.searchsorted(a, v, side='left')
Find indices where elements should be inserted to maintain order.
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_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 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 : array of ints
Array of insertion points with the same shape as `v`.
See Also
--------
sort : In-place sort.
histogram : Produce histogram from 1-D data.
Notes
-----
Binary search is used to find the required insertion points.
Examples
--------
>>> 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])
ndarray.searchsorted(...)
a.searchsorted(v, side='left')
Find indices where elements of v should be inserted in a to maintain order.
For full documentation, see `numpy.searchsorted`
See Also
--------
numpy.searchsorted : equivalent function
searchsorted(keys, side="left")
>>> from numpy import *
>>> a = array([1,2,2,3])
>>> a.searchsorted(2)
1
>>> a.searchsorted(2, side='right')
3
>>> a.searchsorted(4)
4
>>> a.searchsorted([[1,2],[2,3]])
array([[0, 1],
[1, 3]])
>>> searchsorted(a,2)
1
See also: sort, histogram
seed()
numpy.random.seed(...)
seed(seed=None)
Seed the generator.
seed can be an integer, an array (or other sequence) of integers of any
length, or None. If seed is None, then RandomState will try to read data
from /dev/urandom (or the Windows analogue) if available or seed from
the clock otherwise.
>>> seed([1])
>>> rand(3)
array([ 0.13436424, 0.84743374, 0.76377462])
>>> seed([1])
>>> rand(3)
array([ 0.13436424, 0.84743374, 0.76377462])
>>> rand(3)
array([ 0.25506903, 0.49543509, 0.44949106])
select()
numpy.select(condlist, choicelist, default=0)
Return an array drawn from elements in choicelist, depending on conditions.
Parameters
----------
condlist : list of N boolean arrays of length M
The conditions C_0 through C_(N-1) which determine
from which vector the output elements are taken.
choicelist : list of N arrays of length M
Th vectors V_0 through V_(N-1), from which the output
elements are chosen.
Returns
-------
output : 1-dimensional array of length M
The output at position m is the m-th element of the first
vector V_n for which C_n[m] is non-zero. Note that the
output depends on the order of conditions, since the
first satisfied condition is used.
Notes
-----
Equivalent to:
::
output = []
for m in range(M):
output += [V[m] for V,C in zip(values,cond) if C[m]]
or [default]
Examples
--------
>>> t = np.arange(10)
>>> s = np.arange(10)*100
>>> condlist = [t == 4, t > 5]
>>> choicelist = [s, t]
>>> np.select(condlist, choicelist)
array([ 0, 0, 0, 0, 400, 0, 6, 7, 8, 9])
>>> from numpy import *
>>> x = array([5., -2., 1., 0., 4., -1., 3., 10.])
>>> select([x < 0, x == 0, x <= 5], [x-0.1, 0.0, x+0.2], default = 100.)
array([ 5.2, -2.1, 1.2, 0. , 4.2, -1.1, 3.2, 100. ])
>>>
>>>
>>>
>>> result = zeros_like(x)
>>> for n in range(len(x)):
... if x[n] < 0: result[n] = x[n]-0.1
... elif x[n] == 0: result[n] = 0.0
... elif x[n] <= 5: result[n] = x[n]+0.2
... else: result[n] = 100.
...
>>> result
array([ 5.2, -2.1, 1.2, 0. , 4.2, -1.1, 3.2, 100. ])
See also: choose, piecewise
set_numeric_ops()
numpy.set_numeric_ops(...)
set_numeric_ops(op1=func1, op2=func2, ...)
Set numerical operators for array objects.
Parameters
----------
op1, op2, ... : callable
Each ``op = func`` pair describes an operator to be replaced.
For example, ``add = lambda x, y: np.add(x, y) % 5`` would replace
addition by modulus 5 addition.
Returns
-------
saved_ops : list of callables
A list of all operators, stored before making replacements.
Notes
-----
.. WARNING::
Use with care! Incorrect usage may lead to memory errors.
A function replacing an operator cannot make use of that operator.
For example, when replacing add, you may not use ``+``. Instead,
directly call ufuncs:
>>> def add_mod5(x, y):
... return np.add(x, y) % 5
...
>>> old_funcs = np.set_numeric_ops(add=add_mod5)
>>> x = np.arange(12).reshape((3, 4))
>>> x + x
array([[0, 2, 4, 1],
[3, 0, 2, 4],
[1, 3, 0, 2]])
>>> ignore = np.set_numeric_ops(**old_funcs) # restore operators
set_printoptions()
numpy.set_printoptions(precision=None, threshold=None, edgeitems=None, linewidth=None, suppress=None, nanstr=None, infstr=None)
Set printing options.
These options determine the way floating point numbers, arrays and
other NumPy objects are displayed.
Parameters
----------
precision : int, optional
Number of digits of precision for floating point output (default 8).
threshold : int, optional
Total number of array elements which trigger summarization
rather than full repr (default 1000).
edgeitems : int, optional
Number of array items in summary at beginning and end of
each dimension (default 3).
linewidth : int, optional
The number of characters per line for the purpose of inserting
line breaks (default 75).
suppress : bool, optional
Whether or not suppress printing of small floating point values
using scientific notation (default False).
nanstr : string, optional
String representation of floating point not-a-number (default nan).
infstr : string, optional
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.])
>>> from numpy import *
>>> x = array([pi, 1.e-200])
>>> x
array([ 3.14159265e+000, 1.00000000e-200])
>>> set_printoptions(precision=3, suppress=True)
>>> x
array([ 3.142, 0. ])
>>>
>>> help(set_printoptions)
set_string_function()
numpy.set_string_function(...)
set_string_function(f, repr=1)
Set a Python function to be used when pretty printing arrays.
Parameters
----------
f : Python function
Function to be used to pretty print arrays. The function should expect
a single array argument and return a string of the representation of
the array.
repr : int
Unknown.
Examples
--------
>>> def pprint(arr):
... return 'HA! - What are you going to do now?'
...
>>> np.set_string_function(pprint)
>>> a = np.arange(10)
>>> a
HA! - What are you going to do now?
>>> print a
[0 1 2 3 4 5 6 7 8 9]
setbufsize()
numpy.setbufsize(size)
Set the size of the buffer used in ufuncs.
Parameters
----------
size : int
Size of buffer.
setdiff1d()
numpy.setdiff1d(ar1, ar2)
Set difference of 1D arrays with unique elements.
Use unique1d() to generate arrays with only unique elements to use as
inputs to this function.
Parameters
----------
ar1 : array_like
Input array.
ar2 : array_like
Input comparison array.
Returns
-------
difference : ndarray
The values in ar1 that are not in ar2.
See Also
--------
numpy.lib.arraysetops : Module with a number of other functions for
performing set operations on arrays.
seterr()
numpy.seterr(all=None, divide=None, over=None, under=None, invalid=None)
Set how floating-point errors are handled.
Note that operations on integer scalar types (such as int16) are
handled like floating point, and are affected by these settings.
Parameters
----------
all : {'ignore', 'warn', 'raise', 'call'}, optional
Set treatment for all types of floating-point errors at once:
- ignore: Take no action when the exception occurs
- warn: Print a RuntimeWarning (via the Python `warnings` module)
- raise: Raise a FloatingPointError
- call: Call a function specified using the `seterrcall` function.
The default is not to change the current behavior.
divide : {'ignore', 'warn', 'raise', 'call'}, optional
Treatment for division by zero.
over : {'ignore', 'warn', 'raise', 'call'}, optional
Treatment for floating-point overflow.
under : {'ignore', 'warn', 'raise', 'call'}, optional
Treatment for floating-point underflow.
invalid : {'ignore', 'warn', 'raise', 'call'}, optional
Treatment for invalid floating-point operation.
Returns
-------
old_settings : dict
Dictionary containing the old settings.
See also
--------
seterrcall : set a callback function for the 'call' mode.
geterr, geterrcall
Notes
-----
The floating-point exceptions are defined in the IEEE 754 standard [1]:
- Division by zero: infinite result obtained from finite numbers.
- Overflow: result too large to be expressed.
- Underflow: result so close to zero that some precision
was lost.
- Invalid operation: result is not an expressible number, typically
indicates that a NaN was produced.
.. [1] http://en.wikipedia.org/wiki/IEEE_754
Examples
--------
Set mode:
>>> seterr(over='raise') # doctest: +SKIP
{'over': 'ignore', 'divide': 'ignore', 'invalid': 'ignore',
'under': 'ignore'}
>>> old_settings = seterr(all='warn', over='raise') # doctest: +SKIP
>>> int16(32000) * int16(3) # doctest: +SKIP
Traceback (most recent call last):
File "<stdin>", line 1, in ?
FloatingPointError: overflow encountered in short_scalars
>>> seterr(all='ignore') # doctest: +SKIP
{'over': 'ignore', 'divide': 'ignore', 'invalid': 'ignore',
'under': 'ignore'}
seterrcall()
numpy.seterrcall(func)
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
>>> np.seterrcall(saved_handler)
>>> np.seterr(**save_err)
seterrobj()
numpy.seterrobj(...)
seterrobj(errobj)
Used internally by `seterr`.
Parameters
----------
errobj : list
[buffer_size, error_mask, callback_func]
See Also
--------
seterrcall
setfield()
ndarray.setfield(...)
m.setfield(value, dtype, offset) -> None.
places val into field of the given array defined by the data type and offset.
setflags()
ndarray.setflags(...)
a.setflags(write=None, align=None, uic=None)
setmember1d()
numpy.setmember1d(ar1, ar2)
Return a boolean array set True where first element is in second array.
Boolean array is the shape of `ar1` containing True where the elements
of `ar1` are in `ar2` and False otherwise.
Use unique1d() to generate arrays with only unique elements to use as
inputs to this function.
Parameters
----------
ar1 : array_like
Input array.
ar2 : array_like
Input array.
Returns
-------
mask : ndarray, bool
The values `ar1[mask]` are in `ar2`.
See Also
--------
numpy.lib.arraysetops : Module with a number of other functions for
performing set operations on arrays.
setxor1d()
numpy.setxor1d(ar1, ar2)
Set exclusive-or of 1D arrays with unique elements.
Use unique1d() to generate arrays with only unique elements to use as
inputs to this function.
Parameters
----------
ar1 : array_like
Input array.
ar2 : array_like
Input array.
Returns
-------
xor : ndarray
The values that are only in one, but not both, of the input arrays.
See Also
--------
numpy.lib.arraysetops : Module with a number of other functions for
performing set operations on arrays.
shape() or .shape
numpy.shape(a)
Return the shape of an array.
Parameters
----------
a : array_like
Input array.
Returns
-------
shape : tuple
The elements of the tuple give the lengths of the corresponding array
dimensions.
See Also
--------
alen,
ndarray.shape : array method
Examples
--------
>>> np.shape(np.eye(3))
(3, 3)
>>> np.shape([[1,2]])
(1, 2)
>>> np.shape([0])
(1,)
>>> np.shape(0)
()
>>> a = np.array([(1,2),(3,4)], dtype=[('x', 'i4'), ('y', 'i4')])
>>> np.shape(a)
(2,)
>>> a.shape
(2,)
ndarray.shape
Tuple of array dimensions.
Examples
--------
>>> x = np.array([1,2,3,4])
>>> x.shape
(4,)
>>> y = np.zeros((4,5,6))
>>> y.shape
(4, 5, 6)
>>> y.shape = (2, 5, 2, 3, 2)
>>> y.shape
(2, 5, 2, 3, 2)
>>> from numpy import *
>>> x = arange(12)
>>> x.shape
(12,)
>>> x.shape = (3,4)
>>> x
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
>>> x.shape = (3,2,2)
>>> x
array([[[ 0, 1],
[ 2, 3]],
[[ 4, 5],
[ 6, 7]],
[[ 8, 9],
[10, 11]]])
>>> x.shape = (2,-1)
>>> x
array([[ 0, 1, 2, 3, 4, 5],
[ 6, 7, 8, 9, 10, 11]])
>>> x.shape = 12
>>> x
array([0,1,2,3,4,5,6,7,8,9,10,11])
See also: reshape
show_config()
numpy.show_config()
shuffle()
numpy.random.shuffle(...)
shuffle(x)
Modify a sequence in-place by shuffling its contents.
>>> from numpy import *
>>> from numpy.random import shuffle
>>> x = array([1,50,-1,3])
>>> shuffle(x)
>>> print x
[-1 3 50 1]
>>> x = ['a','b','c','z']
>>> shuffle(x)
>>> print x
['a', 'c', 'z', 'b']
See also: permutation, bytes
sign()
numpy.sign(...)
y = sign(x)
Returns an element-wise indication of the sign of a number.
The `sign` function returns ``-1 if x < 0, 0 if x==0, 1 if x > 0``.
Parameters
----------
x : array_like
Input values.
Returns
-------
y : ndarray
The sign of `x`.
Examples
--------
>>> np.sign([-5., 4.5])
array([-1., 1.])
>>> np.sign(0)
0
signbit()
numpy.signbit(...)
y = signbit(x)
Returns element-wise True where signbit is set (less than zero).
Parameters
----------
x: array_like
The input value(s).
Returns
-------
out : array_like, bool
Output.
Examples
--------
>>> np.signbit(-1.2)
True
>>> np.signbit(np.array([1, -2.3, 2.1]))
array([False, True, False], dtype=bool)
sin()
numpy.sin(...)
y = sin(x)
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()
sinc()
numpy.sinc(x)
Return the sinc function.
The sinc function is :math:`\sin(\pi x)/(\pi x)`.
Parameters
----------
x : ndarray
Array (possibly multi-dimensional) of values for which to to
calculate ``sinc(x)``.
Returns
-------
out : ndarray
``sinc(x)``, which has the same shape as the input.
Notes
-----
``sinc(0)`` is the limit value 1.
The name sinc is short for "sine cardinal" or "sinus cardinalis".
The sinc function is used in various signal processing applications,
including in anti-aliasing, in the construction of a
Lanczos resampling filter, and in interpolation.
For bandlimited interpolation of discrete-time signals, the ideal
interpolation kernel is proportional to the sinc function.
References
----------
.. [1] Weisstein, Eric W. "Sinc Function." From MathWorld--A Wolfram Web
Resource. http://mathworld.wolfram.com/SincFunction.html
.. [2] Wikipedia, "Sinc function",
http://en.wikipedia.org/wiki/Sinc_function
Examples
--------
>>> x = np.arange(-20., 21.)/5.
>>> np.sinc(x)
array([ -3.89804309e-17, -4.92362781e-02, -8.40918587e-02,
-8.90384387e-02, -5.84680802e-02, 3.89804309e-17,
6.68206631e-02, 1.16434881e-01, 1.26137788e-01,
8.50444803e-02, -3.89804309e-17, -1.03943254e-01,
-1.89206682e-01, -2.16236208e-01, -1.55914881e-01,
3.89804309e-17, 2.33872321e-01, 5.04551152e-01,
7.56826729e-01, 9.35489284e-01, 1.00000000e+00,
9.35489284e-01, 7.56826729e-01, 5.04551152e-01,
2.33872321e-01, 3.89804309e-17, -1.55914881e-01,
-2.16236208e-01, -1.89206682e-01, -1.03943254e-01,
-3.89804309e-17, 8.50444803e-02, 1.26137788e-01,
1.16434881e-01, 6.68206631e-02, 3.89804309e-17,
-5.84680802e-02, -8.90384387e-02, -8.40918587e-02,
-4.92362781e-02, -3.89804309e-17])
>>> import matplotlib.pyplot as plt
>>> plt.plot(x, sinc(x))
>>> plt.title("Sinc Function")
>>> plt.ylabel("Amplitude")
>>> plt.xlabel("X")
>>> plt.show()
It works in 2-D as well:
>>> x = np.arange(-200., 201.)/50.
>>> xx = np.outer(x, x)
>>> plt.imshow(sinc(xx))
sinh()
numpy.sinh(...)
y = sinh(x)
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`.
size() or .size
numpy.size(a, axis=None)
Return the number of elements along a given axis.
Parameters
----------
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 : int
Number of elements along the specified axis.
See Also
--------
shape : dimensions of array
ndarray.shape : dimensions of array
ndarray.size : number of elements in array
Examples
--------
>>> a = np.array([[1,2,3],[4,5,6]])
>>> np.size(a)
6
>>> np.size(a,1)
3
>>> np.size(a,0)
2
ndarray.size
Number of elements in the array.
Examples
--------
>>> x = np.zeros((3,5,2), dtype=np.complex128)
>>> x.size
30
slice
>>> s = slice(3,9,2)
>>> from numpy import *
>>> a = arange(20)
>>> a[s]
array([3, 5, 7])
>>> a[3:9:2]
array([3, 5, 7])
See also: [], ..., newaxis, s_, ix_, indices, index_exp
solve()
numpy.linalg.solve(a, b)
Solve the equation ``a x = b`` for ``x``.
Parameters
----------
a : array_like, shape (M, M)
Input equation coefficients.
b : array_like, shape (M,)
Equation target values.
Returns
-------
x : array, shape (M,)
Raises
------
LinAlgError
If `a` is singular or not square.
Examples
--------
Solve the system of equations ``3 * x0 + x1 = 9`` and ``x0 + 2 * x1 = 8``:
>>> a = np.array([[3,1], [1,2]])
>>> b = np.array([9,8])
>>> x = np.linalg.solve(a, b)
>>> x
array([ 2., 3.])
Check that the solution is correct:
>>> (np.dot(a, x) == b).all()
True
>>> from numpy import *
>>> from numpy.linalg import solve
>>>
>>>
>>>
>>>
>>>
>>>
>>> a = array([[3,1,5],[1,0,8],[2,1,4]])
>>> b = array([6,7,8])
>>> x = solve(a,b)
>>> print x
[-3.28571429 9.42857143 1.28571429]
>>>
>>> dot(a,x)
array([ 6., 7., 8.])
See also: inv
sometrue()
numpy.sometrue(a, axis=None, out=None)
Check whether some values are true.
Refer to `any` for full documentation.
See Also
--------
any : equivalent function
>>> from numpy import *
>>> b = array([True, False, True, True])
>>> sometrue(b)
True
>>> a = array([1, 5, 2, 7])
>>> sometrue(a >= 5)
True
See also: alltrue, all, any
sort()
numpy.sort(a, axis=-1, kind='quicksort', order=None)
Return a sorted copy of an array.
Parameters
----------
a : array_like
Array to be sorted.
axis : int or None, optional
Axis along which to sort. If None, the array is flattened before
sorting. The default is -1, which sorts along the last axis.
kind : {'quicksort', 'mergesort', 'heapsort'}, optional
Sorting algorithm. Default is 'quicksort'.
order : list, optional
When `a` is a structured array, this argument specifies which fields
to compare first, second, and so on. This list does not need to
include all of the fields.
Returns
-------
sorted_array : ndarray
Array of the same type and shape as `a`.
See Also
--------
ndarray.sort : Method to sort an array in-place.
argsort : Indirect sort.
lexsort : Indirect stable sort on multiple keys.
searchsorted : Find elements in a sorted array.
Notes
-----
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:
=========== ======= ============= ============ =======
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
=========== ======= ============= ============ =======
All the sort algorithms make temporary copies of the data when
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]])
>>> np.sort(a) # sort along the last axis
array([[1, 4],
[1, 3]])
>>> np.sort(a, axis=None) # sort the flattened array
array([1, 1, 3, 4])
>>> np.sort(a, axis=0) # sort along the first axis
array([[1, 1],
[3, 4]])
Use the `order` keyword to specify a field to use when sorting a
structured array:
>>> dtype = [('name', 'S10'), ('height', float), ('age', int)]
>>> values = [('Arthur', 1.8, 41), ('Lancelot', 1.9, 38),
... ('Galahad', 1.7, 38)]
>>> a = np.array(values, dtype=dtype) # create a structured array
>>> np.sort(a, order='height') # doctest: +SKIP
array([('Galahad', 1.7, 38), ('Arthur', 1.8, 41),
('Lancelot', 1.8999999999999999, 38)],
dtype=[('name', '|S10'), ('height', '<f8'), ('age', '<i4')])
Sort by age, then height if ages are equal:
>>> np.sort(a, order=['age', 'height']) # doctest: +SKIP
array([('Galahad', 1.7, 38), ('Lancelot', 1.8999999999999999, 38),
('Arthur', 1.8, 41)],
dtype=[('name', '|S10'), ('height', '<f8'), ('age', '<i4')])
ndarray.sort(...)
a.sort(axis=-1, kind='quicksort', order=None)
Sort an array, in-place.
Parameters
----------
axis : int, optional
Axis along which to sort. Default is -1, which means sort along the
last axis.
kind : {'quicksort', 'mergesort', 'heapsort'}, optional
Sorting algorithm. Default is 'quicksort'.
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.
See Also
--------
numpy.sort : Return a sorted copy of an array.
argsort : Indirect sort.
lexsort : Indirect stable sort on multiple keys.
searchsorted : Find elements in sorted array.
Notes
-----
See ``sort`` for notes on the different sorting algorithms.
Examples
--------
>>> a = np.array([[1,4], [3,1]])
>>> a.sort(axis=1)
>>> a
array([[1, 4],
[1, 3]])
>>> a.sort(axis=0)
>>> a
array([[1, 3],
[1, 4]])
Use the `order` keyword to specify a field to use when sorting a
structured array:
>>> a = np.array([('a', 2), ('c', 1)], dtype=[('x', 'S1'), ('y', int)])
>>> a.sort(order='y')
>>> a
array([('c', 1), ('a', 2)],
dtype=[('x', '|S1'), ('y', '<i4')])
sort(axis=-1, kind="quicksort")
>>> from numpy import *
>>> a = array([2,0,8,4,1])
>>> a.sort()
>>> a
array([0, 1, 2, 4, 8])
>>> a.sort(kind='mergesort')
>>> a = array([[8,4,1],[2,0,9]])
>>> a.sort(axis=0)
>>> a
array([[2, 0, 1],
[8, 4, 9]])
>>> a = array([[8,4,1],[2,0,9]])
>>> a.sort(axis=1)
>>> a
array([[1, 4, 8],
[0, 2, 9]])
>>> sort(a)
See also: argsort, lexsort
sort_complex()
numpy.sort_complex(a)
Sort a complex array using the real part first, then the imaginary part.
Parameters
----------
a : array_like
Input array
Returns
-------
out : complex ndarray
Always returns a sorted complex array.
Examples
--------
>>> np.sort_complex([5, 3, 6, 2, 1])
array([ 1.+0.j, 2.+0.j, 3.+0.j, 5.+0.j, 6.+0.j])
>>> np.sort_complex([5 + 2j, 3 - 1j, 6 - 2j, 2 - 3j, 1 - 5j])
array([ 1.-5.j, 2.-3.j, 3.-1.j, 5.+2.j, 6.-2.j])
source()
numpy.source(object, output=<open file '<stdout>', mode 'w' at 0x00AFF068>)
Print or write to a file the source code for a Numpy object.
Parameters
----------
object : numpy object
Input object.
output : file object, optional
If `output` not supplied then source code is printed to screen
(sys.stdout). File object must be created with either write 'w' or
append 'a' modes.
split()
numpy.split(ary, indices_or_sections, axis=0)
Split an array into multiple sub-arrays of equal size.
Parameters
----------
ary : ndarray
Array to be divided into sub-arrays.
indices_or_sections: integer or 1D array
If `indices_or_sections` is an integer, N, the array will be divided
into N equal arrays along `axis`. If such a split is not possible,
an error is raised.
If `indices_or_sections` is a 1D array of sorted integers, the entries
indicate where along `axis` the array is split. For example,
``[2, 3]`` would, for ``axis = 0``, result in
- ary[:2]
- ary[2:3]
- ary[3:]
If an index exceeds the dimension of the array along `axis`,
an empty sub-array is returned correspondingly.
axis : integer, optional
The axis along which to split. Default is 0.
Returns
-------
sub-arrays : list
A list of sub-arrays.
Raises
------
ValueError
If `indices_or_sections` is given as an integer, but
a split does not result in equal division.
See Also
--------
array_split : Split an array into multiple sub-arrays of equal or
near-equal size. Does not raise an exception if
an equal division cannot be made.
hsplit : Split array into multiple sub-arrays horizontally (column-wise).
vsplit : Split array into multiple sub-arrays vertically (row wise).
dsplit : Split array into multiple sub-arrays along the 3rd axis (depth).
concatenate : Join arrays together.
hstack : Stack arrays in sequence horizontally (column wise).
vstack : Stack arrays in sequence vertically (row wise).
dstack : Stack arrays in sequence depth wise (along third dimension).
Examples
--------
>>> x = np.arange(9.0)
>>> np.split(x, 3)
[array([ 0., 1., 2.]), array([ 3., 4., 5.]), array([ 6., 7., 8.])]
>>> x = np.arange(8.0)
>>> np.split(x, [3, 5, 6, 10])
<BLANKLINE>
[array([ 0., 1., 2.]),
array([ 3., 4.]),
array([ 5.]),
array([ 6., 7.]),
array([], dtype=float64)]
>>> from numpy import *
>>> a = array([[1,2,3,4],[5,6,7,8]])
>>> split(a,2,axis=0)
array([[1, 2, 3, 4]]), array([[5, 6, 7, 8]])]
>>> split(a,4,axis=1)
[array([[1],
[5]]), array([[2],
[6]]), array([[3],
[7]]), array([[4],
[8]])]
>>> split(a,3,axis=1)
Traceback (most recent call last):
<snip>
ValueError: array split does not result in an equal division
>>> split(a,[2,3],axis=1)
[array([[1, 2],
[5, 6]]), array([[3],
[7]]), array([[4],
[8]])]
See also: dsplit, hsplit, vsplit, array_split, concatenate
sqrt()
numpy.sqrt(...)
y = sqrt(x)
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
An array of the same shape as `x`, containing 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 return numpy.nan elements.
See Also
--------
numpy.lib.scimath.sqrt
A version which returns 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])
square()
numpy.square(...)
y = square(x)
Return the element-wise square of the input.
Parameters
----------
x : array_like
Input data.
Returns
-------
out : ndarray
Element-wise `x*x`, of the same shape and dtype as `x`.
Returns 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])
squeeze()
numpy.squeeze(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([[[0], [1], [2]]])
>>> x.shape
(1, 3, 1)
>>> np.squeeze(x).shape
(3,)
ndarray.squeeze(...)
a.squeeze()
Remove single-dimensional entries from the shape of `a`.
Refer to `numpy.squeeze` for full documentation.
See Also
--------
numpy.squeeze : equivalent function
>>> from numpy import *
>>> a = arange(6)
>>> a = a.reshape(1,2,1,1,3,1)
>>> a
array([[[[[[0],
[1],
[2]]]],
[[[[3],
[4],
[5]]]]]])
>>> a.squeeze()
array([[0, 1, 2],
[3, 4, 5]])
>>> squeeze(a)
standard_normal()
numpy.random.standard_normal(...)
standard_normal(size=None)
Standard Normal distribution (mean=0, stdev=1).
>>> standard_normal((2,3))
array([[ 1.12557608, -0.13464922, -0.35682992],
[-1.54090277, 1.21551589, -1.82854551]])
See also: randn, uniform, poisson, seed
std()
numpy.std(a, axis=None, dtype=None, out=None, ddof=0)
Compute the standard deviation along the specified axis.
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
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 : dtype, optional
Type to use in computing the standard deviation. For arrays of
integer type the default is float64, for arrays of float types it is
the same as the array type.
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 calculated
values) will be cast if necessary.
ddof : int, optional
Means Delta Degrees of Freedom. The divisor used in calculations
is ``N - ddof``, where ``N`` represents the number of elements.
By default `ddof` is zero (biased estimate).
Returns
-------
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
--------
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 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]])
>>> np.std(a)
1.1180339887498949
>>> np.std(a, 0)
array([ 1., 1.])
>>> np.std(a, 1)
array([ 0.5, 0.5])
ndarray.std(...)
a.std(axis=None, dtype=None, out=None, ddof=0)
Returns the standard deviation of the array elements along given axis.
Refer to `numpy.std` for full documentation.
See Also
--------
numpy.std : equivalent function
>>> from numpy import *
>>> a = array([1.,2,7])
>>> a.std()
2.6246692913372702
>>> a = array([[1.,2,7],[4,9,6]])
>>> a.std()
2.793842435706702
>>> a.std(axis=0)
array([ 1.5, 3.5, 0.5])
>>> a.std(axis=1)
array([ 2.62466929, 2.05480467])
See also: mean, var, cov
subtract()
numpy.subtract(...)
y = subtract(x1,x2)
Subtract arguments element-wise.
Parameters
----------
x1, x2 : array_like
The arrays to be subtracted from each other. If type is 'array_like'
the `x1` and `x2` shapes must be identical.
Returns
-------
y : ndarray
The difference of `x1` and `x2`, element-wise. 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.]])
sum()
numpy.sum(a, axis=None, dtype=None, out=None)
Return the sum of array elements over a given axis.
Parameters
----------
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 : ndarray
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])
2.0
>>> np.sum([0.5, 1.5], dtype=np.int32)
1
>>> np.sum([[0, 1], [0, 5]])
6
>>> np.sum([[0, 1], [0, 5]], axis=1)
array([1, 5])
If the accumulator is too small, overflow occurs:
>>> np.ones(128, dtype=np.int8).sum(dtype=np.int8)
-128
ndarray.sum(...)
a.sum(axis=None, dtype=None, out=None)
Return the sum of the array elements over the given axis.
Refer to `numpy.sum` for full documentation.
See Also
--------
numpy.sum : equivalent function
>>> from numpy import *
>>> a = array([1,2,3])
>>> a.sum()
6
>>> sum(a)
>>> a = array([[1,2,3],[4,5,6]])
>>> a.sum()
21
>>> a.sum(dtype=float)
21.0
>>> a.sum(axis=0)
array([5, 7, 9])
>>> a.sum(axis=1)
array([ 6, 15])
See also: accumulate, nan, cumsum, prod
svd()
numpy.linalg.svd(a, full_matrices=1, compute_uv=1)
Singular Value Decomposition.
Factorizes the matrix `a` into two unitary matrices, ``U`` and ``Vh``,
and a 1-dimensional array of singular values, ``s`` (real, non-negative),
such that ``a == U S Vh``, where ``S`` is the diagonal
matrix ``np.diag(s)``.
Parameters
----------
a : array_like, shape (M, N)
Matrix to decompose
full_matrices : boolean, optional
If True (default), ``U`` and ``Vh`` are shaped
``(M,M)`` and ``(N,N)``. Otherwise, the shapes are
``(M,K)`` and ``(K,N)``, where ``K = min(M,N)``.
compute_uv : boolean
Whether to compute ``U`` and ``Vh`` in addition to ``s``.
True by default.
Returns
-------
U : ndarray, shape (M, M) or (M, K) depending on `full_matrices`
Unitary matrix.
s : ndarray, shape (K,) where ``K = min(M, N)``
The singular values, sorted so that ``s[i] >= s[i+1]``.
Vh : ndarray, shape (N,N) or (K,N) depending on `full_matrices`
Unitary matrix.
Raises
------
LinAlgError
If SVD computation does not converge.
Notes
-----
If `a` is a matrix (in contrast to an ndarray), then so are all
the return values.
Examples
--------
>>> a = np.random.randn(9, 6) + 1j*np.random.randn(9, 6)
>>> U, s, Vh = np.linalg.svd(a)
>>> U.shape, Vh.shape, s.shape
((9, 9), (6, 6), (6,))
>>> U, s, Vh = np.linalg.svd(a, full_matrices=False)
>>> U.shape, Vh.shape, s.shape
((9, 6), (6, 6), (6,))
>>> S = np.diag(s)
>>> np.allclose(a, np.dot(U, np.dot(S, Vh)))
True
>>> s2 = np.linalg.svd(a, compute_uv=False)
>>> np.allclose(s, s2)
True
>>> from numpy import *
>>> from numpy.linalg import svd
>>> A = array([[1., 3., 5.],[2., 4., 6.]])
>>> U,sigma,V = svd(A)
>>> print U
[[-0.61962948 -0.78489445]
[-0.78489445 0.61962948]]
>>> print sigma
[ 9.52551809 0.51430058]
>>> print V
[[-0.2298477 -0.52474482 -0.81964194]
[ 0.88346102 0.24078249 -0.40189603]
[ 0.40824829 -0.81649658 0.40824829]]
>>> Sigma = zeros_like(A)
>>> n = min(A.shape)
>>> Sigma[:n,:n] = diag(sigma)
>>> print dot(U,dot(Sigma,V))
[[ 1. 3. 5.]
[ 2. 4. 6.]]
See also: pinv
swapaxes()
numpy.swapaxes(a, axis1, axis2)
Interchange two axes of an array.
Parameters
----------
a : array_like
Input array.
axis1 : int
First axis.
axis2 : int
Second axis.
Returns
-------
a_swapped : ndarray
If `a` is an ndarray, then a view of `a` is returned; otherwise
a new array is created.
Examples
--------
>>> x = np.array([[1,2,3]])
>>> np.swapaxes(x,0,1)
array([[1],
[2],
[3]])
>>> x = np.array([[[0,1],[2,3]],[[4,5],[6,7]]])
>>> 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]]])
ndarray.swapaxes(...)
a.swapaxes(axis1, axis2)
Return a view of the array with `axis1` and `axis2` interchanged.
Refer to `numpy.swapaxes` for full documentation.
See Also
--------
numpy.swapaxes : equivalent function
>>> from numpy import *
>>> a = arange(30)
>>> a = a.reshape(2,3,5)
>>> 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, 24],
[25, 26, 27, 28, 29]]])
>>> b = a.swapaxes(1,2)
>>> b
array([[[ 0, 5, 10],
[ 1, 6, 11],
[ 2, 7, 12],
[ 3, 8, 13],
[ 4, 9, 14]],
[[15, 20, 25],
[16, 21, 26],
[17, 22, 27],
[18, 23, 28],
[19, 24, 29]]])
>>> b.shape
(2, 5, 3)
>>> b[0,0,0] = -1
>>> print a[0,0,0]
See also: transpose, rollaxis
take()
numpy.take(a, indices, axis=None, out=None, mode='raise')
Take elements from an array along an axis.
This function does the same thing as "fancy" indexing (indexing arrays
using arrays); however, it can be easier to use if you need elements
along a given axis.
Parameters
----------
a : array_like
The source array.
indices : array_like, int
The indices of the values to extract.
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.
'raise' -- raise an error
'wrap' -- wrap around
'clip' -- clip to the range
Returns
-------
subarray : ndarray
The returned array has the same type as `a`.
See Also
--------
ndarray.take : equivalent method
Examples
--------
>>> a = [4, 3, 5, 7, 6, 8]
>>> indices = [0, 1, 4]
>>> np.take(a, indices)
array([4, 3, 6])
In this example if `a` is a ndarray, "fancy" indexing can be used.
>>> a = np.array(a)
>>> a[indices]
array([4, 3, 6])
ndarray.take(...)
a.take(indices, axis=None, out=None, mode='raise')
Return an array formed from the elements of a at the given indices.
Refer to `numpy.take` for full documentation.
See Also
--------
numpy.take : equivalent function
>>> from numpy import *
>>> a= array([10,20,30,40])
>>> a.take([0,0,3])
array([10, 10, 40])
>>> a[[0,0,3]]
array([10, 10, 40])
>>> a.take([[0,1],[0,1]])
array([[10, 20],
[10, 20]])
>>> a = array([[10,20,30],[40,50,60]])
>>> a.take([0,2],axis=1)
array([[10, 30],
[40, 60]])
>>> take(a,[0,2],axis=1)
See also: [], put, putmask, compress, choose
tan()
numpy.tan(...)
y = tan(x)
Compute tangent element-wise.
Parameters
----------
x : array_like
Angles in radians.
Returns
-------
y : ndarray
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])
tanh()
numpy.tanh(...)
y = tanh(x)
Hyperbolic tangent element-wise.
Parameters
----------
x : array_like
Input array.
Returns
-------
y : ndarray
The corresponding hyperbolic tangent values.
tensordot()
numpy.tensordot(a, b, axes=2)
Returns the tensor dot product for (ndim >= 1) arrays along an 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.
See Also
--------
dot
Notes
-----
r_{xxx, yyy} = \sum_k a_{xxx,k} b_{k,yyy}
When there is more than one axis to sum over, the corresponding
arguments to axes should be sequences of the same length with the first
axis to sum over given first in both sequences, the second axis second,
and so forth.
If the `axes` argument is an integer, N, then the last N dimensions of `a`
and first N dimensions of `b` are summed over.
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]
>>> from numpy import *
>>> a = arange(60.).reshape(3,4,5)
>>> b = arange(24.).reshape(4,3,2)
>>> c = tensordot(a,b, axes=([1,0],[0,1]))
>>> c.shape
(5,2)
>>>
>>> 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]
...
See also: dot
test()
numpy.test(self, label='fast', verbose=1, extra_argv=None, doctests=False, coverage=False, **kwargs)
Run tests for module using nose
Parameters
----------
label : {'fast', 'full', '', attribute identifer}
Identifies the tests 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 tests as in the
no -A option to nosetests - same as ''
None or '' - run all tests
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
doctests : boolean
If True, run doctests in module, default False
coverage : boolean
If True, report coverage of NumPy code, default False
(Requires the coverage module:
http://nedbatchelder.com/code/modules/coverage.html)
tile()
numpy.tile(A, reps)
Construct an array by repeating A the number of times given by reps.
Parameters
----------
A : array_like
The input array.
reps : array_like
The number of repetitions of `A` along each axis.
Returns
-------
c : ndarray
The output array.
See Also
--------
repeat
Notes
-----
If `reps` has length d, the result will have dimension of max(d, `A`.ndim).
If `A`.ndim < d, `A` is promoted to be d-dimensional by prepending new
axes. So a shape (3,) array is promoted to (1,3) for 2-D replication,
or shape (1,1,3) for 3-D replication. If this is not the desired behavior,
promote `A` to d-dimensions manually before calling this function.
If `A`.ndim > d, `reps` is promoted to `A`.ndim by pre-pending 1's to it.
Thus for an `A` of shape (2,3,4,5), a `reps` of (2,2) is treated as
(1,1,2,2).
Examples
--------
>>> a = np.array([0, 1, 2])
>>> np.tile(a, 2)
array([0, 1, 2, 0, 1, 2])
>>> np.tile(a, (2, 2))
array([[0, 1, 2, 0, 1, 2],
[0, 1, 2, 0, 1, 2]])
>>> np.tile(a, (2, 1, 2))
array([[[0, 1, 2, 0, 1, 2]],
<BLANKLINE>
[[0, 1, 2, 0, 1, 2]]])
>>> b = np.array([[1, 2], [3, 4]])
>>> np.tile(b, 2)
array([[1, 2, 1, 2],
[3, 4, 3, 4]])
>>> np.tile(b, (2, 1))
array([[1, 2],
[3, 4],
[1, 2],
[3, 4]])
>>> from numpy import *
>>> a = array([10,20])
>>> tile(a, (3,2))
array([[10, 20, 10, 20],
[10, 20, 10, 20],
[10, 20, 10, 20]])
>>> tile(42.0, (3,2))
array([[ 42., 42.],
[ 42., 42.],
[ 42., 42.]])
>>> tile([[1,2],[4,8]], (2,3))
array([[1, 2, 1, 2, 1, 2],
[4, 8, 4, 8, 4, 8],
[1, 2, 1, 2, 1, 2],
[4, 8, 4, 8, 4, 8]])
See also: hstack, vstack, r_, c_, concatenate, repeat
tofile()
ndarray.tofile(...)
a.tofile(fid, sep="", format="%s")
Write array to a file as text or binary.
Data is always written in 'C' order, independently of the order of `a`.
The data produced by this method can be recovered by using the function
fromfile().
This is a convenience function for quick storage of array data.
Information on endianess and precision is lost, so this method is not a
good choice for files intended to archive data or transport data between
machines with different endianess. Some of these problems can be overcome
by outputting the data as text files at the expense of speed and file size.
Parameters
----------
fid : file or string
An open file object or a string containing a filename.
sep : string
Separator between array items for text output.
If "" (empty), a binary file is written, equivalently to
file.write(a.tostring()).
format : string
Format string for text file output.
Each entry in the array is formatted to text by converting it to the
closest Python type, and using "format" % item.
>>> from numpy import *
>>> x = arange(10.)
>>> y = x**2
>>> y.tofile("myfile.dat")
>>> y.tofile("myfile.txt", sep=' ', format = "%e")
>>> y.tofile("myfile.txt", sep='\n', format = "%e")
See also: fromfile, loadtxt, savetxt
tolist()
ndarray.tolist(...)
a.tolist()
Return the array as a possibly nested list.
Return a copy of the array data as a hierarchical Python list.
Data items are converted to the nearest compatible Python type.
Parameters
----------
none
Returns
-------
y : list
The possibly nested list of array elements.
Notes
-----
The array may be recreated, ``a = np.array(a.tolist())``.
Examples
--------
>>> a = np.array([1, 2])
>>> a.tolist()
[1, 2]
>>> a = np.array([[1, 2], [3, 4]])
>>> list(a)
[array([1, 2]), array([3, 4])]
>>> a.tolist()
[[1, 2], [3, 4]]
>>> from numpy import *
>>> a = array([[1,2],[3,4]])
>>> a.tolist()
[[1, 2], [3, 4]]
tostring()
ndarray.tostring(...)
a.tostring(order='C')
Construct a Python string containing the raw data bytes in the array.
Parameters
----------
order : {'C', 'F', None}
Order of the data for multidimensional arrays:
C, Fortran, or the same as for the original array.
trace()
numpy.trace(a, offset=0, axis1=0, axis2=1, dtype=None, out=None)
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.
Parameters
----------
a : array_like
Array from whis the diagonals are taken.
offset : integer, optional
Offset of the diagonal from the main diagonal. Can be both positive
and negative. Defaults to main diagonal.
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 : 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 : 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 : 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.
Returns
-------
sum_along_diagonals : ndarray
If a is 2-d, a 0-d array containing the diagonal is
returned. If a has larger dimensions, then an array of
diagonals is returned.
Examples
--------
>>> np.trace(np.eye(3))
3.0
>>> a = np.arange(8).reshape((2,2,2))
>>> np.trace(a)
array([6, 8])
ndarray.trace(...)
a.trace(offset=0, axis1=0, axis2=1, dtype=None, out=None)
Return the sum along diagonals of the array.
Refer to `numpy.trace` for full documentation.
See Also
--------
numpy.trace : equivalent function
>>> from numpy import *
>>> a = arange(12).reshape(3,4)
>>> a
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
>>> a.diagonal()
array([ 0, 5, 10])
>>> a.trace()
15
>>> a.diagonal(offset=1)
array([ 1, 6, 11])
>>> a.trace(offset=1)
18
See also: diag, diagonal
transpose()
numpy.transpose(a, axes=None)
Permute the dimensions of an array.
Parameters
----------
a : array_like
Input array.
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
--------
>>> x = np.arange(4).reshape((2,2))
>>> x
array([[0, 1],
[2, 3]])
>>> np.transpose(x)
array([[0, 2],
[1, 3]])
>>> x = np.ones((1, 2, 3))
>>> np.transpose(x, (1, 0, 2)).shape
(2, 1, 3)
ndarray.transpose(...)
a.transpose(*axes)
Returns a view of 'a' with axes transposed. If no axes are given,
or None is passed, switches the order of the axes. For a 2-d
array, this is the usual matrix transpose. If axes are given,
they describe how the axes are permuted.
Examples
--------
>>> a = np.array([[1,2],[3,4]])
>>> a
array([[1, 2],
[3, 4]])
>>> a.transpose()
array([[1, 3],
[2, 4]])
>>> a.transpose((1,0))
array([[1, 3],
[2, 4]])
>>> a.transpose(1,0)
array([[1, 3],
[2, 4]])
A very simple example:
>>> a = array([[1,2,3],[4,5,6]])
>>> print a.shape
(2, 3)
>>> b = a.transpose()
>>> print b
[[1 4]
[2 5]
[3 6]]
>>> print b.shape
(3, 2)
From this, a more elaborate example can be understood:
>>> a = arange(30)
>>> a = a.reshape(2,3,5)
>>> 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, 24],
[25, 26, 27, 28, 29]]])
>>> b = a.transpose()
>>> b
array([[[ 0, 15],
[ 5, 20],
[10, 25]],
[[ 1, 16],
[ 6, 21],
[11, 26]],
[[ 2, 17],
[ 7, 22],
[12, 27]],
[[ 3, 18],
[ 8, 23],
[13, 28]],
[[ 4, 19],
[ 9, 24],
[14, 29]]])
>>> b.shape
(5, 3, 2)
>>> b = a.transpose(1,0,2)
>>> b
array([[[ 0, 1, 2, 3, 4],
[15, 16, 17, 18, 19]],
[[ 5, 6, 7, 8, 9],
[20, 21, 22, 23, 24]],
[[10, 11, 12, 13, 14],
[25, 26, 27, 28, 29]]])
>>> b.shape
(3, 2, 5)
>>> b = transpose(a, (1,0,2))
See also: T, swapaxes, rollaxis
trapz()
numpy.trapz(y, x=None, dx=1.0, axis=-1)
Integrate along the given axis using the composite trapezoidal rule.
Integrate `y` (`x`) along given axis.
Parameters
----------
y : array_like
Input array to integrate.
x : array_like, optional
If `x` is None, then spacing between all `y` elements is 1.
dx : scalar, optional
If `x` is None, spacing given by `dx` is assumed.
axis : int, optional
Specify the axis.
Examples
--------
>>> np.trapz([1,2,3])
>>> 4.0
>>> np.trapz([1,2,3], [4,6,8])
>>> 8.0
tri()
numpy.tri(N, M=None, k=0, dtype=<type 'float'>)
Construct an array filled with ones at and below the given diagonal.
Parameters
----------
N : int
Number of rows in the array.
M : int, optional
Number of columns in the array.
By default, `M` is taken equal to `N`.
k : int, optional
The sub-diagonal below which the array is filled.
`k` = 0 is the main diagonal, while `k` < 0 is below it,
and `k` > 0 is above. The default is 0.
dtype : dtype, optional
Data type of the returned array. The default is float.
Returns
-------
T : (N,M) ndarray
Array with a lower triangle filled with ones, in other words
``T[i,j] == 1`` for ``i <= j + k``.
Examples
--------
>>> np.tri(3, 5, 2, dtype=int)
array([[1, 1, 1, 0, 0],
[1, 1, 1, 1, 0],
[1, 1, 1, 1, 1]])
>>> np.tri(3, 5, -1)
array([[ 0., 0., 0., 0., 0.],
[ 1., 0., 0., 0., 0.],
[ 1., 1., 0., 0., 0.]])
>>> from numpy import *
>>> tri(3,4,k=0,dtype=float)
array([[ 1., 0., 0., 0.],
[ 1., 1., 0., 0.],
[ 1., 1., 1., 0.]])
>>> tri(3,4,k=1,dtype=int)
array([[1, 1, 0, 0],
[1, 1, 1, 0],
[1, 1, 1, 1]])
See also: tril, triu
tril()
numpy.tril(m, k=0)
Lower triangle of an array.
Return a copy of an array with elements above the `k`-th diagonal zeroed.
Parameters
----------
m : array_like, shape (M, N)
Input array.
k : int
Diagonal above which to zero elements.
`k = 0` is the main diagonal, `k < 0` is below it and `k > 0` is above.
Returns
-------
L : ndarray, shape (M, N)
Lower triangle of `m`, of same shape and data-type as `m`.
See Also
--------
triu
Examples
--------
>>> np.tril([[1,2,3],[4,5,6],[7,8,9],[10,11,12]], -1)
array([[ 0, 0, 0],
[ 4, 0, 0],
[ 7, 8, 0],
[10, 11, 12]])
>>> from numpy import *
>>> a = arange(10,100,10).reshape(3,3)
>>> a
array([[10, 20, 30],
[40, 50, 60],
[70, 80, 90]])
>>> tril(a,k=0)
array([[10, 0, 0],
[40, 50, 0],
[70, 80, 90]])
>>> tril(a,k=1)
array([[10, 20, 0],
[40, 50, 60],
[70, 80, 90]])
See also: tri, triu
trim_zeros()
numpy.trim_zeros(filt, trim='fb')
Trim the leading and trailing zeros from a 1D array.
Parameters
----------
filt : array_like
Input array.
trim : string, optional
A string with 'f' representing trim from front and 'b' to trim from
back.
Examples
--------
>>> a = np.array((0, 0, 0, 1, 2, 3, 2, 1, 0))
>>> np.trim_zeros(a)
array([1, 2, 3, 2, 1])
>>> from numpy import *
>>> x = array([0, 0, 0, 1, 2, 3, 0, 0])
>>> trim_zeros(x,'f')
array([1, 2, 3, 0, 0])
>>> trim_zeros(x,'b')
array([0, 0, 0, 1, 2, 3])
>>> trim_zeros(x,'bf')
array([1, 2, 3])
See also: compress
triu()
numpy.triu(m, k=0)
Upper triangle of an array.
Construct a copy of a matrix with elements below the k-th diagonal zeroed.
Please refer to the documentation for `tril`.
See Also
--------
tril
Examples
--------
>>> np.triu([[1,2,3],[4,5,6],[7,8,9],[10,11,12]], -1)
array([[ 1, 2, 3],
[ 4, 5, 6],
[ 0, 8, 9],
[ 0, 0, 12]])
>>> from numpy import *
>>> a = arange(10,100,10).reshape(3,3)
>>> a
array([[10, 20, 30],
[40, 50, 60],
[70, 80, 90]])
>>> triu(a,k=0)
array([[10, 20, 30],
[ 0, 50, 60],
[ 0, 0, 90]])
>>> triu(a,k=1)
array([[ 0, 20, 30],
[ 0, 0, 60],
[ 0, 0, 0]])
See also: tri, tril
true_divide()
numpy.true_divide(...)
y = true_divide(x1,x2)
Returns an element-wise, 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
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.
typeDict
numpy.typeDict
dict() -> new empty dictionary.
dict(mapping) -> new dictionary initialized from a mapping object's
(key, value) pairs.
dict(seq) -> new dictionary initialized as if via:
d = {}
for k, v in seq:
d[k] = v
dict(**kwargs) -> new dictionary initialized with the name=value pairs
in the keyword argument list. For example: dict(one=1, two=2)
>>> from numpy import *
>>> typeDict['short']
<type 'numpy.int16'>
>>> typeDict['uint16']
<type 'numpy.uint16'>
>>> typeDict['void']
<type 'numpy.void'>
>>> typeDict['S']
<type 'numpy.string_'>
See also: dtype, cast
typename()
numpy.typename(char)
Return a description for the given data type code.
Parameters
----------
char : str
Data type code.
Returns
-------
out : str
Description of the input data type code.
See Also
--------
typecodes
dtype
numpy.random.uniform(...)
uniform(low=0.0, high=1.0, size=1)
Draw samples from a uniform distribution.
Samples are uniformly distributed over the half-open interval
``[low, high)`` (includes low, but excludes high). In other words,
any value within the given interval is equally likely to be drawn
by `uniform`.
Parameters
----------
low : float, optional
Lower boundary of the output interval. All values generated will be
greater than or equal to low. The default value is 0.
high : float
Upper boundary of the output interval. All values generated will be
less than high. The default value is 1.0.
size : tuple of ints, int, optional
Shape of output. If the given size is, for example, (m,n,k),
m*n*k samples are generated. If no shape is specified, a single sample
is returned.
Returns
-------
out : ndarray
Drawn samples, with shape `size`.
See Also
--------
randint : Discrete uniform distribution, yielding integers.
random_integers : Discrete uniform distribution over the closed interval
``[low, high]``.
random_sample : Floats uniformly distributed over ``[0, 1)``.
random : Alias for `random_sample`.
rand : Convenience function that accepts dimensions as input, e.g.,
``rand(2,2)`` would generate a 2-by-2 array of floats, uniformly
distributed over ``[0, 1)``.
Notes
-----
The probability density function of the uniform distribution is
.. math:: p(x) = \frac{1}{b - a}
anywhere within the interval ``[a, b)``, and zero elsewhere.
Examples
--------
Draw samples from the distribution:
>>> s = np.random.uniform(-1,0,1000)
All values are within the given interval:
>>> np.all(s >= -1)
True
>>> np.all(s < 0)
True
Display the histogram of the samples, along with the
probability density function:
>>> import matplotlib.pyplot as plt
>>> count, bins, ignored = plt.hist(s, 15, normed=True)
>>> plt.plot(bins, np.ones_like(bins), linewidth=2, color='r')
>>> plt.show()
>>> from numpy import *
>>> from numpy.random import *
>>> uniform(low=0,high=10,size=(2,3))
array([[ 6.66689951, 4.50623001, 4.69973967],
[ 6.52977732, 3.24688284, 5.01917021]])
See also: standard_normal, poisson, seed
union1d()
numpy.union1d(ar1, ar2)
Union of 1D arrays with unique elements.
Use unique1d() to generate arrays with only unique elements to use as
inputs to this function.
Parameters
----------
ar1 : array_like, shape(M,)
Input array.
ar2 : array_like, shape(N,)
Input array.
Returns
-------
union : ndarray
Unique union of input arrays.
See also
--------
numpy.lib.arraysetops : Module with a number of other functions for
performing set operations on arrays.
unique()
numpy.unique(x)
Return the sorted, unique elements of an array or sequence.
Parameters
----------
x : array_like
Input array.
Returns
-------
y : ndarray
The sorted, unique elements are returned in a 1-D array.
Examples
--------
>>> np.unique([1, 1, 2, 2, 3, 3])
array([1, 2, 3])
>>> a = np.array([[1, 1], [2, 3]])
>>> np.unique(a)
array([1, 2, 3])
>>> from numpy import *
>>> x = array([2,3,2,1,0,3,4,0])
>>> unique(x)
array([0, 1, 2, 3, 4])
See also: compress, unique1d
unique1d()
numpy.unique1d(ar1, return_index=False, return_inverse=False)
Find the unique elements of an array.
Parameters
----------
ar1 : array_like
This array will be flattened if it is not already 1-D.
return_index : bool, optional
If True, also return the indices against `ar1` that result in the
unique array.
return_inverse : bool, optional
If True, also return the indices against the unique array that
result in `ar1`.
Returns
-------
unique : ndarray
The unique values.
unique_indices : ndarray, optional
The indices of the unique values. Only provided if `return_index` is
True.
unique_inverse : ndarray, optional
The indices to reconstruct the original array. Only provided if
`return_inverse` is True.
See Also
--------
numpy.lib.arraysetops : Module with a number of other functions
for performing set operations on arrays.
Examples
--------
>>> np.unique1d([1, 1, 2, 2, 3, 3])
array([1, 2, 3])
>>> a = np.array([[1, 1], [2, 3]])
>>> np.unique1d(a)
array([1, 2, 3])
Reconstruct the input from unique values:
>>> np.unique1d([1,2,6,4,2,3,2], return_index=True)
>>> x = [1,2,6,4,2,3,2]
>>> u, i = np.unique1d(x, return_inverse=True)
>>> u
array([1, 2, 3, 4, 6])
>>> i
array([0, 1, 4, 3, 1, 2, 1])
>>> [u[p] for p in i]
[1, 2, 6, 4, 2, 3, 2]
>>> np.unique1d([1, 1, 2, 2, 3, 3])
array([1, 2, 3])
>>> a = np.array([[1, 1], [2, 3]])
>>> np.unique1d(a)
array([1, 2, 3])
>>> np.unique1d([1,2,6,4,2,3,2], return_index=True)
(array([1, 2, 3, 4, 6]), array([0, 1, 5, 3, 2]))
>>> x = [1,2,6,4,2,3,2]
>>> u, i = np.unique1d(x, return_inverse=True)
>>> u
array([1, 2, 3, 4, 6])
>>> i
array([0, 1, 4, 3, 1, 2, 1])
>>> [u[p] for p in i]
[1, 2, 6, 4, 2, 3, 2]
See also: compress, unique
unpackbits()
numpy.unpackbits(...)
out = numpy.unpackbits(myarray, axis=None)
myarray - array of uint8 type where each element represents a bit-field
that should be unpacked into a boolean output array
The shape of the output array is either 1-d (if axis is None) or
the same shape as the input array with unpacking done along the
axis specified.
unravel_index()
numpy.unravel_index(x, dims)
Convert a flat index into an index tuple for an array of given shape.
Parameters
----------
x : int
Flattened index.
dims : shape tuple
Input shape.
Notes
-----
In the Examples section, since ``arr.flat[x] == arr.max()`` it may be
easier to use flattened indexing than to re-map the index to a tuple.
Examples
--------
>>> arr = np.ones((5,4))
>>> arr
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11],
[12, 13, 14, 15],
[16, 17, 18, 19]])
>>> x = arr.argmax()
>>> x
19
>>> dims = arr.shape
>>> idx = np.unravel_index(x, dims)
>>> idx
(4, 3)
>>> arr[idx] == arr.max()
True
unwrap()
numpy.unwrap(p, discont=3.1415926535897931, axis=-1)
Unwrap by changing deltas between values to 2*pi complement.
Unwrap radian phase `p` by changing absolute jumps greater than
`discont` to their 2*pi complement along the given axis.
Parameters
----------
p : array_like
Input array.
discont : float
Maximum discontinuity between values.
axis : integer
Axis along which unwrap will operate.
Returns
-------
out : ndarray
Output array
vander()
numpy.vander(x, N=None)
Generate a Van der Monde matrix.
The columns of the output matrix are decreasing powers of the input
vector. Specifically, the i-th output column is the input vector to
the power of ``N - i - 1``.
Parameters
----------
x : array_like
Input array.
N : int, optional
Order of (number of columns in) the output.
Returns
-------
out : ndarray
Van der Monde matrix of order `N`. The first column is ``x^(N-1)``,
the second ``x^(N-2)`` and so forth.
Examples
--------
>>> x = np.array([1, 2, 3, 5])
>>> N = 3
>>> np.vander(x, N)
array([[ 1, 1, 1],
[ 4, 2, 1],
[ 9, 3, 1],
[25, 5, 1]])
>>> np.column_stack([x**(N-1-i) for i in range(N)])
array([[ 1, 1, 1],
[ 4, 2, 1],
[ 9, 3, 1],
[25, 5, 1]])
>>> from numpy import *
>>> x = array([1,2,3,5])
>>> N=3
>>> vander(x,N)
array([[ 1, 1, 1],
[ 4, 2, 1],
[ 9, 3, 1],
[25, 5, 1]])
>>> column_stack([x**(N-1-i) for i in range(N)])
array([[ 1, 1, 1],
[ 4, 2, 1],
[ 9, 3, 1],
[25, 5, 1]])
var()
numpy.var(a, axis=None, dtype=None, out=None, ddof=0)
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,
otherwise over the specified axis.
Parameters
----------
a : array_like
Array containing numbers whose variance is desired. If `a` is not an
array, a conversion is attempted.
axis : int, optional
Axis along which the variance is computed. The default is to compute
the variance of the flattened array.
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 : ndarray, optional
Alternative output array in which to place the result. It must have
the same shape as the expected output but the type is cast if
necessary.
ddof : positive int,optional
"Delta Degrees of Freedom": the divisor used in calculation is
N - ddof.
Returns
-------
variance : ndarray, see dtype parameter above
If out=None, returns a new array containing the variance; otherwise
a reference to the output array is returned.
See Also
--------
std : Standard deviation
mean : Average
Notes
-----
The variance is the average of the squared deviations from the mean,
i.e., var = mean(abs(x - x.mean())**2). The computed variance is biased,
i.e., the mean is computed by dividing by the number of elements, N,
rather than by N-1. Note that for complex numbers the absolute value is
taken before squaring, so that the result is always real and nonnegative.
Examples
--------
>>> a = np.array([[1,2],[3,4]])
>>> np.var(a)
1.25
>>> np.var(a,0)
array([ 1., 1.])
>>> np.var(a,1)
array([ 0.25, 0.25])
ndarray.var(...)
a.var(axis=None, dtype=None, out=None, ddof=0)
Returns the variance of the array elements, along given axis.
Refer to `numpy.var` for full documentation.
See Also
--------
numpy.var : equivalent function
>>> from numpy import *
>>> a = array([1,2,7])
>>> a.var()
6.8888888888888875
>>> a = array([[1,2,7],[4,9,6]])
>>> a.var()
7.8055555555555571
>>> a.var(axis=0)
array([ 2.25, 12.25, 0.25])
>>> a.var(axis=1)
array([ 6.88888889, 4.22222222])
See also: cov, std, mean
vdot()
numpy.vdot(...)
vdot(a,b)
Returns the dot product of a and b for scalars and vectors
of floating point and complex types. The first argument, a, is conjugated.
>>> from numpy import *
>>> x = array([1+2j,3+4j])
>>> y = array([5+6j,7+8j])
>>> vdot(x,y)
(70-8j)
See also: dot, inner, cross, outer
vectorize()
numpy.vectorize(...)
vectorize(somefunction, otypes=None, doc=None)
Generalized function class.
Define a vectorized function which takes nested sequence
of objects or numpy arrays as inputs and returns a
numpy array as output, evaluating the function over successive
tuples of the input arrays like the python map function except it uses
the broadcasting rules of numpy.
Data-type of output of vectorized is determined by calling the function
with the first element of the input. This can be avoided by specifying
the otypes argument as either a string of typecode characters or a list
of data-types specifiers. There should be one data-type specifier for
each output.
Parameters
----------
f : callable
A Python function or method.
Examples
--------
>>> def myfunc(a, b):
... if a > b:
... return a-b
... else:
... return a+b
>>> vfunc = np.vectorize(myfunc)
>>> vfunc([1, 2, 3, 4], 2)
array([3, 4, 1, 2])
>>> from numpy import *
>>> def myfunc(x):
... if x >= 0: return x**2
... else: return -x
...
>>> myfunc(2.)
4.0
>>> myfunc(array([-2,2]))
<snip>
>>> vecfunc = vectorize(myfunc, otypes=[float])
>>> vecfunc(array([-2,2]))
array([ 2., 4.])
See also: apply_along_axis, apply_over_axes
view()
ndarray.view(...)
a.view(dtype=None, type=None)
New view of array with the same data.
Parameters
----------
dtype : data-type
Data-type descriptor of the returned view, e.g. float32 or int16.
type : python type
Type of the returned view, e.g. ndarray or matrix.
Examples
--------
>>> x = np.array([(1, 2)], dtype=[('a', np.int8), ('b', np.int8)])
Viewing array data using a different type and dtype:
>>> y = x.view(dtype=np.int16, type=np.matrix)
>>> print y.dtype
int16
>>> print type(y)
<class 'numpy.core.defmatrix.matrix'>
Using a view to convert an array to a record array:
>>> z = x.view(np.recarray)
>>> z.a
array([1], dtype=int8)
Views share data:
>>> x[0] = (9, 10)
>>> z[0]
(9, 10)
>>> from numpy import *
>>> a = array([1., 2.])
>>> a.view()
array([ 1., 2.])
>>> a.view(complex)
array([ 1.+2.j])
>>> a.view(int)
array([ 0, 1072693248, 0, 1073741824])
>>>
>>> mydescr = dtype({'names': ['gender','age'], 'formats': ['S1', 'i2']})
>>> a = array([('M',25),('F',30)], dtype = mydescr)
>>> b = a.view(recarray)
>>> >>> a['age']
array([25, 30], dtype=int16)
>>> b.age
array([25, 30], dtype=int16)
See also: copy
vonmises()
numpy.random.vonmises(...)
vonmises(mu=0.0, kappa=1.0, size=None)
Draw samples from a von Mises distribution.
Samples are drawn from a von Mises distribution with specified mode (mu)
and dispersion (kappa), on the interval [-pi, pi].
The von Mises distribution (also known as the circular normal
distribution) is a continuous probability distribution on the circle. It
may be thought of as the circular analogue of the normal distribution.
Parameters
----------
mu : float
Mode ("center") of the distribution.
kappa : float, >= 0.
Dispersion of the distribution.
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}
The returned samples live on the unit circle [-\pi, \pi].
See Also
--------
scipy.stats.distributions.vonmises : probability density function,
distribution or cumulative density function, etc.
Notes
-----
The probability density for the von Mises distribution is
.. math:: p(x) = \frac{e^{\kappa cos(x-\mu)}}{2\pi I_0(\kappa)},
where :math:`\mu` is the mode and :math:`\kappa` the dispersion,
and :math:`I_0(\kappa)` is the modified Bessel function of order 0.
The von Mises, named for Richard Edler von Mises, born in
Austria-Hungary, in what is now the Ukraine. He fled to the United
States in 1939 and became a professor at Harvard. He worked in
probability theory, aerodynamics, fluid mechanics, and philosophy of
science.
References
----------
.. [1] Abramowitz, M. and Stegun, I. A. (ed.), Handbook of Mathematical
Functions, National Bureau of Standards, 1964; reprinted Dover
Publications, 1965.
.. [2] von Mises, Richard, 1964, Mathematical Theory of Probability
and Statistics (New York: Academic Press).
.. [3] Wikipedia, "Von Mises distribution",
http://en.wikipedia.org/wiki/Von_Mises_distribution
Examples
--------
Draw samples from the distribution:
>>> mu, kappa = 0.0, 4.0 # mean and dispersion
>>> s = np.random.vonmises(mu, kappa, 1000)
Display the histogram of the samples, along with
the probability density function:
>>> import matplotlib.pyplot as plt
>>> import scipy.special as sps
>>> count, bins, ignored = plt.hist(s, 50, normed=True)
>>> x = arange(-pi, pi, 2*pi/50.)
>>> y = -np.exp(kappa*np.cos(x-mu))/(2*pi*sps.jn(0,kappa))
>>> plt.plot(x, y/max(y), linewidth=2, color='r')
>>> plt.show()
>>> from numpy import *
>>> from numpy.random import *
>>> vonmises(mu=1,kappa=1,size=(2,3))
array([[ 0.81960554, 1.37470839, -0.15700173],
[ 1.2974554 , 2.94229797, 0.32462307]])
>>> from pylab import *
>>> hist(vonmises(1,1,(10000)), 50)
See also: random_sample, uniform, standard_normal, seed
vsplit()
numpy.vsplit(ary, indices_or_sections)
Split array into multiple sub-arrays vertically.
Please refer to the `numpy.split` documentation.
See Also
--------
numpy.split : The default behaviour of this function implements
`vsplit`.
>>> from numpy import *
>>> a = array([[1,2],[3,4],[5,6],[7,8]])
>>> vsplit(a,2)
[array([[1, 2],
[3, 4]]), array([[5, 6],
[7, 8]])]
>>> vsplit(a,[1,2])
[array([[1, 2]]), array([[3, 4]]), array([[5, 6],
[7, 8]])]
See also: split, array_split, dsplit, hsplit, vstack
vstack()
numpy.vstack(tup)
Stack arrays vertically.
`vstack` can be used to rebuild arrays divided by `vsplit`.
Parameters
----------
tup : sequence of arrays
Tuple containing arrays to be stacked. The arrays must have the same
shape along all but the first axis.
See Also
--------
array_split : Split an array into a list of multiple sub-arrays of
near-equal size.
split : Split array into a list of multiple sub-arrays of equal size.
vsplit : Split array into a list of multiple sub-arrays vertically.
dsplit : Split array into a list of multiple sub-arrays along the 3rd axis
(depth).
concatenate : Join arrays together.
hstack : Stack arrays in sequence horizontally (column wise).
dstack : Stack arrays in sequence depth wise (along third dimension).
Examples
--------
>>> a = np.array([1, 2, 3])
>>> b = np.array([2, 3, 4])
>>> np.vstack((a,b))
array([[1, 2, 3],
[2, 3, 4]])
>>> a = np.array([[1], [2], [3]])
>>> b = np.array([[2], [3], [4]])
>>> np.vstack((a,b))
array([[1],
[2],
[3],
[2],
[3],
[4]])
>>> from numpy import *
>>> a =array([1,2])
>>> b = array([[3,4],[5,6]])
>>> vstack((a,b,a))
array([[1, 2],
[3, 4],
[5, 6],
[1, 2]])
See also: hstack, column_stack, concatenate, dstack, vsplit
weibull()
numpy.random.weibull(...)
weibull(a, size=None)
Weibull distribution.
Draw samples from a 1-parameter Weibull distribution with the given
shape parameter.
.. math:: X = (-ln(U))^{1/a}
Here, U is drawn from the uniform distribution over (0,1].
The more common 2-parameter Weibull, including a scale parameter
:math:`\lambda` is just :math:`X = \lambda(-ln(U))^{1/a}`.
The Weibull (or Type III asymptotic extreme value distribution for smallest
values, SEV Type III, or Rosin-Rammler distribution) is one of a class of
Generalized Extreme Value (GEV) distributions used in modeling extreme
value problems. This class includes the Gumbel and Frechet distributions.
Parameters
----------
a : float
Shape of the distribution.
size : tuple of ints
Output shape. If the given shape is, e.g., ``(m, n, k)``, then
``m * n * k`` samples are drawn.
See Also
--------
scipy.stats.distributions.weibull : probability density function,
distribution or cumulative density function, etc.
gumbel, scipy.stats.distributions.genextreme
Notes
-----
The probability density for the Weibull distribution is
.. math:: p(x) = \frac{a}
{\lambda}(\frac{x}{\lambda})^{a-1}e^{-(x/\lambda)^a},
where :math:`a` is the shape and :math:`\lambda` the scale.
The function has its peak (the mode) at
:math:`\lambda(\frac{a-1}{a})^{1/a}`.
When ``a = 1``, the Weibull distribution reduces to the exponential
distribution.
References
----------
.. [1] Waloddi Weibull, Professor, Royal Technical University, Stockholm,
1939 "A Statistical Theory Of The Strength Of Materials",
Ingeniorsvetenskapsakademiens Handlingar Nr 151, 1939,
Generalstabens Litografiska Anstalts Forlag, Stockholm.
.. [2] Waloddi Weibull, 1951 "A Statistical Distribution Function of Wide
Applicability", Journal Of Applied Mechanics ASME Paper.
.. [3] Wikipedia, "Weibull distribution",
http://en.wikipedia.org/wiki/Weibull_distribution
Examples
--------
Draw samples from the distribution:
>>> a = 5. # shape
>>> s = np.random.weibull(a, 1000)
Display the histogram of the samples, along with
the probability density function:
>>> import matplotlib.pyplot as plt
>>> def weib(x,n,a):
... return (a/n)*(x/n)**(a-1)*exp(-(x/n)**a)
>>> count, bins, ignored = plt.hist(numpy.random.weibull(5.,1000))
>>> scale = count.max()/weib(x, 1., 5.).max()
>>> x = arange(1,100.)/50.
>>> plt.plot(x, weib(x, 1., 5.)*scale)
>>> plt.show()
>>> from numpy import *
>>> from numpy.random import *
>>> weibull(a=1,size=(2,3))
array([[ 0.08303065, 3.41486412, 0.67430149],
[ 0.41383893, 0.93577601, 0.45431195]])
>>> from pylab import *
>>> hist(weibull(5, (1000)), 50)
See also: random_sample, uniform, standard_normal, seed
where()
numpy.where(...)
where(condition, [x, y])
Return elements, either from `x` or `y`, depending on `condition`.
If only `condition` is given, return ``condition.nonzero()``.
Parameters
----------
condition : array_like, bool
When True, yield `x`, otherwise yield `y`.
x, y : array_like, optional
Values from which to choose.
Returns
-------
out : ndarray or tuple of ndarrays
If both `x` and `y` are specified, the output array, shaped like
`condition`, contains elements of `x` where `condition` is True,
and elements from `y` elsewhere.
If only `condition` is given, return the tuple
``condition.nonzero()``, the indices where `condition` is True.
See Also
--------
nonzero, choose
Notes
-----
If `x` and `y` are given and input arrays are 1-D, `where` is
equivalent to::
[xv if c else yv for (c,xv,yv) in zip(condition,x,y)]
Examples
--------
>>> x = np.arange(9.).reshape(3, 3)
>>> np.where( x > 5 )
(array([2, 2, 2]), array([0, 1, 2]))
>>> x[np.where( x > 3.0 )] # Note: result is 1D.
array([ 4., 5., 6., 7., 8.])
>>> np.where(x < 5, x, -1) # Note: broadcasting.
array([[ 0., 1., 2.],
[ 3., 4., -1.],
[-1., -1., -1.]])
>>> np.where([[True, False], [True, True]],
... [[1, 2], [3, 4]],
... [[9, 8], [7, 6]])
array([[1, 8],
[3, 4]])
>>> np.where([[0, 1], [1, 0]])
(array([0, 1]), array([1, 0]))
>>> from numpy import *
>>> a = array([3,5,7,9])
>>> b = array([10,20,30,40])
>>> c = array([2,4,6,8])
>>> where(a <= 6, b, c)
array([10, 20, 6, 8])
>>> where(a <= 6, b, -1)
array([10, 20, -1, -1])
>>> indices = where(a <= 6)
>>> indices
(array([0, 1]),)
>>> b[indices]
array([10, 20])
>>> b[a <= 6]
array([10, 20])
>>> d = array([[3,5,7,9],[2,4,6,8]])
>>> where(d <= 6)
(array([0, 0, 1, 1, 1]), array([0, 1, 0, 1, 2]))
Be aware of the difference between x[list of bools] and x[list of integers]!
>>> from numpy import *
>>> x = arange(5,0,-1)
>>> print x
[5 4 3 2 1]
>>> criterion = (x <= 2) | (x >= 5)
>>> criterion
array([True, False, False, True, True], dtype=bool)
>>> indices = where(criterion, 1, 0)
>>> print indices
[1 0 0 1 1]
>>> x[indices]
array([4, 5, 5, 4, 4])
>>> x[criterion]
array([5, 2, 1])
>>> indices = where(criterion)
>>> print indices
(array([0, 3, 4]),)
>>> x[indices]
array([5, 2, 1])
See also: [], nonzero, clip
who()
numpy.who(vardict=None)
Print the Numpy arrays in the given dictionary.
If there is no dictionary passed in or `vardict` is None then returns
Numpy arrays in the globals() dictionary (all Numpy arrays in the
namespace).
Parameters
----------
vardict : dict, optional
A dictionary possibly containing ndarrays. Default is globals().
Returns
-------
out : None
Returns 'None'.
Notes
-----
Prints out the name, shape, bytes and type of all of the ndarrays present
in `vardict`.
Examples
--------
>>> d = {'x': arange(2.0), 'y': arange(3.0), 'txt': 'Some str', 'idx': 5}
>>> np.whos(d)
Name Shape Bytes Type
===========================================================
<BLANKLINE>
y 3 24 float64
x 2 16 float64
<BLANKLINE>
Upper bound on total bytes = 40
zeros()
numpy.zeros(...)
zeros(shape, dtype=float, order='C')
Return a new array of given shape and type, filled with zeros.
Parameters
----------
shape : {tuple of ints, int}
Shape of the new array, e.g., ``(2, 3)`` or ``2``.
dtype : data-type, optional
The desired data-type for the array, e.g., `numpy.int8`. Default is
`numpy.float64`.
order : {'C', 'F'}, optional
Whether to store multidimensional data in C- or Fortran-contiguous
(row- or column-wise) order in memory.
Returns
-------
out : ndarray
Array of zeros with the given shape, dtype, and order.
See Also
--------
numpy.zeros_like : Return an array of zeros with shape and type of input.
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.ones : Return a new array setting values to one.
numpy.empty : Return a new uninitialized array.
Examples
--------
>>> np.zeros(5)
array([ 0., 0., 0., 0., 0.])
>>> np.zeros((5,), dtype=numpy.int)
array([0, 0, 0, 0, 0])
>>> np.zeros((2, 1))
array([[ 0.],
[ 0.]])
>>> s = (2,2)
>>> np.zeros(s)
array([[ 0., 0.],
[ 0., 0.]])
>>> np.zeros((2,), dtype=[('x', 'i4'), ('y', 'i4')])
array([(0, 0), (0, 0)],
dtype=[('x', '<i4'), ('y', '<i4')])
>>> from numpy import *
>>> zeros(5)
array([ 0., 0., 0., 0., 0.])
>>> zeros((2,3), int)
array([[0, 0, 0],
[0, 0, 0]])
See also: zeros_like, ones, empty, eye, identity
zeros_like()
numpy.zeros_like(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]])
>>> from numpy import *
>>> a = array([[1,2,3],[4,5,6]])
>>> zeros_like(a)
array([[0, 0, 0],
[0, 0, 0]])
See also: ones_like, zeros