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.
Contents
- ...
- []
- T
- abs()
- absolute()
- accumulate
- add()
- alen()
- all()
- allclose()
- alltrue()
- alterdot()
- amax()
- amin()
- angle()
- any()
- append()
- apply_along_axis()
- apply_over_axes()
- arange()
- arccos()
- arccosh()
- arcsin()
- arcsinh()
- arctan()
- arctan2()
- arctanh()
- argmax()
- argmin()
- argsort()
- argwhere()
- around()
- array()
- array2string()
- array_equal()
- array_equiv()
- array_repr()
- array_split()
- array_str()
- arrayrange
- asanyarray()
- asarray()
- asarray_chkfinite()
- ascontiguousarray()
- asfarray()
- asfortranarray()
- asmatrix()
- asscalar()
- astype()
- atleast_1d()
- atleast_2d()
- atleast_3d()
- average()
- bartlett()
- base_repr()
- bench()
- beta()
- binary_repr()
- bincount()
- binomial()
- bitwise_and()
- bitwise_not()
- bitwise_or()
- bitwise_xor()
- blackman()
- bmat()
- broadcast()
- broadcast_arrays()
- byte_bounds()
- bytes()
- byteswap()
- c_
- cast[]()
- can_cast()
- ceil()
- choose()
- clip()
- column_stack()
- common_type()
- compare_chararrays()
- compress()
- concatenate()
- conj()
- conjugate()
- convolve()
- copy()
- corrcoef()
- correlate()
- cos()
- cosh()
- cov()
- cross()
- cumprod()
- cumproduct()
- cumsum()
- degrees()
- delete()
- deprecate()
- deprecate_with_doc()
- diag()
- diagflat()
- diagonal()
- diff()
- digitize()
- disp()
- divide()
- dot()
- dsplit()
- dstack()
- dtype() or .dtype
- dump()
- dumps()
- ediff1d()
- empty()
- empty_like()
- equal()
- exp()
- expand_dims()
- expm1()
- extract()
- eye()
- fabs()
- fastCopyAndTranspose()
- fft
- fftfreq
- fftshift
- fill()
- find_common_type()
- finfo()
- fix()
- flat
- flatnonzero()
- flatten()
- fliplr()
- flipud()
- floor()
- floor_divide()
- fmod()
- frexp()
- fromarrays()
- frombuffer()
- fromfile()
- fromfunction()
- fromiter()
- frompyfunc()
- fromregex()
- fromstring()
- fv()
- generic()
- get_array_wrap()
- get_include()
- get_numarray_include()
- get_numpy_include()
- get_printoptions()
- getbuffer()
- getbufsize()
- geterr()
- geterrcall()
- geterrobj()
- getfield()
- gradient()
- greater()
- greater_equal()
- gumbel()
- hamming()
- hanning()
- histogram()
- histogram2d()
- histogramdd()
- hsplit()
- hstack()
- hypot()
- i0()
- identity()
- ifft
- imag() or .imag
- index_exp
- indices()
- inf
- info() or .info
- inner()
- insert()
- int_asbuffer()
- interp()
- intersect1d()
- intersect1d_nu()
- inv()
- invert()
- ipmt()
- irr()
- iscomplex()
- iscomplexobj()
- isfinite()
- isfortran()
- isinf()
- isnan()
- isneginf()
- isposinf()
- isreal()
- isrealobj()
- isscalar()
- issctype()
- issubclass_()
- issubdtype()
- issubsctype()
- item()
- itemset()
- iterable()
- ix_()
- kaiser()
- kron()
- ldexp()
- left_shift()
- less()
- less_equal()
- lexsort()
- linspace()
- load()
- loads()
- loadtxt()
- log()
- log10()
- log1p()
- log2()
- logical_and()
- logical_not()
- logical_or()
- logical_xor()
- logspace()
- lookfor()
- lstsq()
- mat()
- matrix()
- max()
- maximum()
- maximum_sctype()
- may_share_memory()
- mean()
- median()
- meshgrid()
- mgrid
- min()
- minimum()
- mintypecode()
- mirr()
- mod()
- modf()
- msort()
- multiply()
- nan
- nan_to_num()
- nanargmax()
- nanargmin()
- nanmax()
- nanmin()
- nansum()
- ndenumerate()
- ndim() or .ndim
- ndindex()
- negative()
- newaxis
- newbuffer()
- newbyteorder()
- nonzero()
- not_equal()
- nper()
- npv()
- obj2sctype()
- ogrid
- ones()
- ones_like()
- outer()
- packbits()
- permutation()
- piecewise()
- pinv()
- pkgload()
- place()
- pmt()
- poisson()
- poly()
- poly1d()
- polyadd()
- polyder()
- polydiv()
- polyfit()
- polyint()
- polymul()
- polysub()
- polyval()
- power()
- ppmt()
- prod()
- product()
- ptp()
- put()
- putmask()
- pv()
- r_
- radians()
- randint()
- random_integers()
- random_sample()
- ranf()
- rank()
- rate()
- ravel()
- real() or .real
- real_if_close()
- recarray()
- reciprocal()
- reduce
- remainder()
- repeat()
- require()
- reshape()
- resize()
- restoredot()
- right_shift()
- rint()
- roll()
- rollaxis()
- roots()
- rot90()
- round()
- round_()
- row_stack()
- s_
- safe_eval()
- sample()
- save()
- savetxt()
- savez()
- sctype2char()
- searchsorted()
- seed()
- select()
- set_numeric_ops()
- set_printoptions()
- set_string_function()
- setbufsize()
- setdiff1d()
- seterr()
- seterrcall()
- seterrobj()
- setfield()
- setflags()
- setmember1d()
- setxor1d()
- shape() or .shape
- show_config()
- shuffle()
- sign()
- signbit()
- sin()
- sinc()
- sinh()
- size() or .size
- slice
- solve()
- sometrue()
- sort()
- sort_complex()
- source()
- split()
- sqrt()
- square()
- squeeze()
- standard_normal()
- std()
- subtract()
- sum()
- svd()
- swapaxes()
- take()
- tan()
- tanh()
- tensordot()
- test()
- tile()
- tofile()
- tolist()
- tostring()
- trace()
- transpose()
- trapz()
- tri()
- tril()
- trim_zeros()
- triu()
- true_divide()
- typeDict
- typename()
- uniform()
- union1d()
- unique()
- unique1d()
- unpackbits()
- unravel_index()
- unwrap()
- vander()
- var()
- vdot()
- vectorize()
- view()
- vonmises()
- vsplit()
- vstack()
- weibull()
- where()
- who()
- zeros()
- zeros_like()
...
>>> from numpy import *
>>> a = arange(12)
>>> a = a.reshape(3,2,2)
>>> print a
[[[ 0 1]
[ 2 3]]
[[ 4 5]
[ 6 7]]
[[ 8 9]
[10 11]]]
>>> a[...,0] # same as a[:,:,0]
array([[ 0, 2],
[ 4, 6],
[ 8, 10]])
>>> a[1:,...] # same as a[1:,:,:] or just a[1:]
array([[[ 4, 5],
[ 6, 7]],
[[ 8, 9],
[10, 11]]])
[]
>>> from numpy import *
>>> a = array([ [ 0, 1, 2, 3, 4],
... [10,11,12,13,14],
... [20,21,22,23,24],
... [30,31,32,33,34] ])
>>>
>>> a[0,0] # indices start by zero
0
>>> a[-1] # last row
array([30, 31, 32, 33, 34])
>>> a[1:3,1:4] # subarray
array([[11, 12, 13],
[21, 22, 23]])
>>>
>>> i = array([0,1,2,1]) # array of indices for the first axis
>>> j = array([1,2,3,4]) # array of indices for the second axis
>>> a[i,j]
array([ 1, 12, 23, 14])
>>>
>>> a[a<13] # boolean indexing
array([ 0, 1, 2, 3, 4, 10, 11, 12])
>>>
>>> b1 = array( [True,False,True,False] ) # boolean row selector
>>> a[b1,:]
array([[ 0, 1, 2, 3, 4],
[20, 21, 22, 23, 24]])
>>>
>>> b2 = array( [False,True,True,False,True] ) # boolean column selector
>>> a[:,b2]
array([[ 1, 2, 4],
[11, 12, 14],
[21, 22, 24],
[31, 32, 34]])
See also: ..., newaxis, ix_, indices, nonzero, where, slice
T
ndarray.T
Same as self.transpose() except self is returned for self.ndim < 2.
Examples
--------
>>> x = np.array([[1.,2.],[3.,4.]])
>>> x.T
array([[ 1., 3.],
[ 2., 4.]])
>>> from numpy import *
>>> x = array([[1.,2.],[3.,4.]])
>>> x
array([[ 1., 2.],
[ 3., 4.]])
>>> x.T # shortcut for transpose()
array([[ 1., 3.],
[ 2., 4.]])
See also: transpose
abs()
numpy.abs(...)
y = absolute(x)
Calculate the absolute value element-wise.
Parameters
----------
x : array_like
Input array.
Returns
-------
res : ndarray
An ndarray containing the absolute value of
each element in `x`. For complex input, ``a + ib``, the
absolute value is :math:`\sqrt{ a^2 + b^2 }`.
Examples
--------
>>> x = np.array([-1.2, 1.2])
>>> np.absolute(x)
array([ 1.2, 1.2])
>>> np.absolute(1.2 + 1j)
1.5620499351813308
Plot the function over ``[-10, 10]``:
>>> import matplotlib.pyplot as plt
>>> x = np.linspace(-10, 10, 101)
>>> plt.plot(x, np.absolute(x))
>>> plt.show()
Plot the function over the complex plane:
>>> xx = x + 1j * x[:, np.newaxis]
>>> plt.imshow(np.abs(xx), extent=[-10, 10, -10, 10])
>>> plt.show()
>>> from numpy import *
>>> abs(-1)
1
>>> abs(array([-1.2, 1.2]))
array([ 1.2, 1.2])
>>> abs(1.2+1j)
1.5620499351813308
absolute()
numpy.absolute(...)
y = absolute(x)
Calculate the absolute value element-wise.
Parameters
----------
x : array_like
Input array.
Returns
-------
res : ndarray
An ndarray containing the absolute value of
each element in `x`. For complex input, ``a + ib``, the
absolute value is :math:`\sqrt{ a^2 + b^2 }`.
Examples
--------
>>> x = np.array([-1.2, 1.2])
>>> np.absolute(x)
array([ 1.2, 1.2])
>>> np.absolute(1.2 + 1j)
1.5620499351813308
Plot the function over ``[-10, 10]``:
>>> import matplotlib.pyplot as plt
>>> x = np.linspace(-10, 10, 101)
>>> plt.plot(x, np.absolute(x))
>>> plt.show()
Plot the function over the complex plane:
>>> xx = x + 1j * x[:, np.newaxis]
>>> plt.imshow(np.abs(xx), extent=[-10, 10, -10, 10])
>>> plt.show()
Synonym for abs()
See abs
accumulate
>>> from numpy import *
>>> add.accumulate(array([1.,2.,3.,4.])) # like reduce() but also gives intermediate results
array([ 1., 3., 6., 10.])
>>> array([1., 1.+2., (1.+2.)+3., ((1.+2.)+3.)+4.]) # this is what it computed
array([ 1., 3., 6., 10.])
>>> multiply.accumulate(array([1.,2.,3.,4.])) # works also with other operands
array([ 1., 2., 6., 24.])
>>> array([1., 1.*2., (1.*2.)*3., ((1.*2.)*3.)*4.]) # this is what it computed
array([ 1., 2., 6., 24.])
>>> add.accumulate(array([[1,2,3],[4,5,6]]), axis = 0) # accumulate every column separately
array([[1, 2, 3],
[5, 7, 9]])
>>> add.accumulate(array([[1,2,3],[4,5,6]]), axis = 1) # accumulate every row separately
array([[ 1, 3, 6],
[ 4, 9, 15]])
See also: reduce, cumprod, cumsum
add()
numpy.add(...)
y = add(x1,x2)
Add arguments element-wise.
Parameters
----------
x1, x2 : array_like
The arrays to be added.
Returns
-------
y : {ndarray, scalar}
The sum of `x1` and `x2`, element-wise. Returns scalar if
both `x1` and `x2` are scalars.
Notes
-----
Equivalent to `x1` + `x2` in terms of array broadcasting.
Examples
--------
>>> np.add(1.0, 4.0)
5.0
>>> x1 = np.arange(9.0).reshape((3, 3))
>>> x2 = np.arange(3.0)
>>> np.add(x1, x2)
array([[ 0., 2., 4.],
[ 3., 5., 7.],
[ 6., 8., 10.]])
>>> from numpy import *
>>> add(array([-1.2, 1.2]), array([1,3]))
array([-0.2, 4.2])
>>> array([-1.2, 1.2]) + array([1,3])
array([-0.2, 4.2])
alen()
numpy.alen(a)
Return the length of the first dimension of the input array. Parameters ---------- a : array_like Input array. Returns ------- alen : int Length of the first dimension of `a`. See Also -------- shape Examples -------- >>> a = np.zeros((7,4,5)) >>> a.shape[0] 7 >>> np.alen(a) 7
all()
numpy.all(a, axis=None, out=None)
Returns True if all elements evaluate to True.
Parameters
----------
a : array_like
Input array.
axis : int, optional
Axis over which to perform the operation.
If None, use a flattened input array and return a bool.
out : ndarray, optional
Array into which the result is placed. Its type is preserved
and it must be of the right shape to hold the output.
Returns
-------
out : ndarray, bool
A logical AND is performed along `axis`, and the result placed
in `out`. If `out` was not specified, a new output array is created.
See Also
--------
ndarray.all : equivalent method
Notes
-----
Since NaN is not equal to zero, NaN evaluates to True.
Examples
--------
>>> np.all([[True,False],[True,True]])
False
>>> np.all([[True,False],[True,True]], axis=0)
array([ True, False], dtype=bool)
>>> np.all([-1, 4, 5])
True
>>> np.all([1.0, np.nan])
True
ndarray.all(...)
a.all(axis=None, out=None) Returns True if all elements evaluate to True. Refer to `numpy.all` for full documentation. See Also -------- numpy.all : equivalent function
>>> from numpy import *
>>> a = array([True, False, True])
>>> a.all() # if all elements of a are True: return True; otherwise False
False
>>> all(a) # this form also exists
False
>>> a = array([1,2,3])
>>> all(a > 0) # equivalent to (a > 0).all()
True
See also: any, alltrue, sometrue
allclose()
numpy.allclose(a, b, rtol=1.0000000000000001e-005, atol=1e-008)
Returns True if two arrays are element-wise equal within a tolerance.
The tolerance values are positive, typically very small numbers. The
relative difference (`rtol` * `b`) and the absolute difference (`atol`)
are added together to compare against the absolute difference between `a`
and `b`.
Parameters
----------
a, b : array_like
Input arrays to compare.
rtol : Relative tolerance
The relative difference is equal to `rtol` * `b`.
atol : Absolute tolerance
The absolute difference is equal to `atol`.
Returns
-------
y : bool
Returns True if the two arrays are equal within the given
tolerance; False otherwise. If either array contains NaN, then
False is returned.
See Also
--------
all, any, alltrue, sometrue
Notes
-----
If the following equation is element-wise True, then allclose returns
True.
absolute(`a` - `b`) <= (`atol` + `rtol` * absolute(`b`))
Examples
--------
>>> np.allclose([1e10,1e-7], [1.00001e10,1e-8])
False
>>> np.allclose([1e10,1e-8], [1.00001e10,1e-9])
True
>>> np.allclose([1e10,1e-8], [1.0001e10,1e-9])
False
>>> np.allclose([1.0, np.nan], [1.0, np.nan])
False
>>> allclose(array([1e10,1e-7]), array([1.00001e10,1e-8]))
False
>>> allclose(array([1e10,1e-8]), array([1.00001e10,1e-9]))
True
>>> allclose(array([1e10,1e-8]), array([1.0001e10,1e-9]))
False
alltrue()
numpy.alltrue(a, axis=None, out=None)
Check if all elements of input array are true. See Also -------- numpy.all : Equivalent function; see for details.
>>> from numpy import *
>>> b = array([True, False, True, True])
>>> alltrue(b)
False
>>> a = array([1, 5, 2, 7])
>>> alltrue(a >= 5)
False
alterdot()
numpy.alterdot(...)
alterdot() changes all dot functions to use blas.
amax()
numpy.amax(a, axis=None, out=None)
Return the maximum along an axis.
Parameters
----------
a : array_like
Input data.
axis : int, optional
Axis along which to operate. By default flattened input is used.
out : ndarray, optional
Alternative output array in which to place the result. Must
be of the same shape and buffer length as the expected output.
Returns
-------
amax : ndarray
A new array or a scalar with the result, or a reference to `out`
if it was specified.
Examples
--------
>>> a = np.arange(4).reshape((2,2))
>>> a
array([[0, 1],
[2, 3]])
>>> np.amax(a, axis=0)
array([2, 3])
>>> np.amax(a, axis=1)
array([1, 3])
amin()
numpy.amin(a, axis=None, out=None)
Return the minimum along an axis.
Parameters
----------
a : array_like
Input data.
axis : int, optional
Axis along which to operate. By default a flattened input is used.
out : ndarray, optional
Alternative output array in which to place the result. Must
be of the same shape and buffer length as the expected output.
Returns
-------
amin : ndarray
A new array or a scalar with the result, or a reference to `out` if it
was specified.
Examples
--------
>>> a = np.arange(4).reshape((2,2))
>>> a
array([[0, 1],
[2, 3]])
>>> np.amin(a) # Minimum of the flattened array
0
>>> np.amin(a, axis=0) # Minima along the first axis
array([0, 1])
>>> np.amin(a, axis=1) # Minima along the second axis
array([0, 2])
angle()
numpy.angle(z, deg=0)
Return the angle of the complex argument.
Parameters
----------
z : array_like
A complex number or sequence of complex numbers.
deg : bool, optional
Return angle in degrees if True, radians if False (default).
Returns
-------
angle : {ndarray, scalar}
The counterclockwise angle from the positive real axis on
the complex plane, with dtype as numpy.float64.
See Also
--------
arctan2
Examples
--------
>>> np.angle([1.0, 1.0j, 1+1j]) # in radians
array([ 0. , 1.57079633, 0.78539816])
>>> np.angle(1+1j, deg=True) # in degrees
45.0
>>> from numpy import *
>>> angle(1+1j) # in radians
0.78539816339744828
>>> angle(1+1j,deg=True) # in degrees
45.0
any()
numpy.any(a, axis=None, out=None)
Test whether any elements of an array evaluate to True along an axis.
Parameters
----------
a : array_like
Input array.
axis : int, optional
Axis over which to perform the operation.
If None, use a flattened input array and return a bool.
out : ndarray, optional
Array into which the result is placed. Its type is preserved
and it must be of the right shape to hold the output.
Returns
-------
out : ndarray
A logical OR is performed along `axis`, and the result placed
in `out`. If `out` was not specified, a new output array is created.
See Also
--------
ndarray.any : equivalent method
Notes
-----
Since NaN is not equal to zero, NaN evaluates to True.
Examples
--------
>>> np.any([[True, False], [True, True]])
True
>>> np.any([[True, False], [False, False]], axis=0)
array([ True, False], dtype=bool)
>>> np.any([-1, 0, 5])
True
>>> np.any(np.nan)
True
ndarray.any(...)
a.any(axis=None, out=None) Check if any of the elements of `a` are true. Refer to `numpy.any` for full documentation. See Also -------- numpy.any : equivalent function
>>> from numpy import *
>>> a = array([True, False, True])
>>> a.any() # gives True if at least 1 element of a is True, otherwise False
True
>>> any(a) # this form also exists
True
>>> a = array([1,2,3])
>>> (a >= 1).any() # equivalent to any(a >= 1)
True
See also: all, alltrue, sometrue
append()
numpy.append(arr, values, axis=None)
Append values to the end of an array.
Parameters
----------
arr : array_like
Values are appended to a copy of this array.
values : array_like
These values are appended to a copy of `arr`. It must be of the
correct shape (the same shape as `arr`, excluding `axis`). If `axis`
is not specified, `values` can be any shape and will be flattened
before use.
axis : int, optional
The axis along which `values` are appended. If `axis` is not given,
both `arr` and `values` are flattened before use.
Returns
-------
out : ndarray
A copy of `arr` with `values` appended to `axis`. Note that `append`
does not occur in-place: a new array is allocated and filled.
Examples
--------
>>> np.append([1, 2, 3], [[4, 5, 6], [7, 8, 9]])
array([1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> np.append([[1, 2, 3], [4, 5, 6]], [[7, 8, 9]], axis=0)
array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
>>> from numpy import *
>>> a = array([10,20,30,40])
>>> append(a,50)
array([10, 20, 30, 40, 50])
>>> append(a,[50,60])
array([10, 20, 30, 40, 50, 60])
>>> a = array([[10,20,30],[40,50,60],[70,80,90]])
>>> append(a,[[15,15,15]],axis=0)
array([[10, 20, 30],
[40, 50, 60],
[70, 80, 90],
[15, 15, 15]])
>>> append(a,[[15],[15],[15]],axis=1)
array([[10, 20, 30, 15],
[40, 50, 60, 15],
[70, 80, 90, 15]])
See also: insert, delete, concatenate
apply_along_axis()
numpy.apply_along_axis(func1d, axis, arr, *args)
Apply function to 1-D slices along the given axis.
Execute `func1d(a[i],*args)` where `func1d` takes 1-D arrays, `a` is
the input array, and `i` is an integer that varies in order to apply the
function along the given axis for each 1-D subarray in `a`.
Parameters
----------
func1d : function
This function should be able to take 1-D arrays. It is applied to 1-D
slices of `a` along the specified axis.
axis : integer
Axis along which `func1d` is applied.
a : ndarray
Input array.
args : any
Additional arguments to `func1d`.
Returns
-------
out : ndarray
The output array. The shape of `out` is identical to the shape of `a`,
except along the `axis` dimension, whose length is equal to the size
of the return value of `func1d`.
See Also
--------
apply_over_axes : Apply a function repeatedly over multiple axes.
Examples
--------
>>> def my_func(a):
... """Average first and last element of a 1-D array"""
... return (a[0] + a[-1]) * 0.5
>>> b = np.array([[1,2,3], [4,5,6], [7,8,9]])
>>> np.apply_along_axis(my_func, 0, b)
array([4., 5., 6.])
>>> np.apply_along_axis(my_func, 1, b)
array([2., 5., 8.])
>>> from numpy import *
>>> def myfunc(a): # function works on a 1d arrays, takes the average of the 1st an last element
... return (a[0]+a[-1])/2
...
>>> b = array([[1,2,3],[4,5,6],[7,8,9]])
>>> apply_along_axis(myfunc,0,b) # apply myfunc to each column (axis=0) of b
array([4, 5, 6])
>>> apply_along_axis(myfunc,1,b) # apply myfunc to each row (axis=1) of b
array([2, 5, 8])
See also: apply_over_axes, vectorize
apply_over_axes()
numpy.apply_over_axes(func, a, axes)
Apply a function repeatedly over multiple axes.
`func` is called as `res = func(a, axis)`, where `axis` is the first
element of `axes`. The result `res` of the function call must have
either the same dimensions as `a` or one less dimension. If `res` has one
less dimension than `a`, a dimension is inserted before `axis`.
The call to `func` is then repeated for each axis in `axes`,
with `res` as the first argument.
Parameters
----------
func : function
This function must take two arguments, `func(a, axis)`.
a : ndarray
Input array.
axes : array_like
Axes over which `func` is applied, the elements must be
integers.
Returns
-------
val : ndarray
The output array. The number of dimensions is the same as `a`, but
the shape can be different. This depends on whether `func` changes
the shape of its output with respect to its input.
See Also
--------
apply_along_axis :
Apply a function to 1-D slices of an array along the given axis.
Examples
--------
>>> a = np.arange(24).reshape(2,3,4)
>>> a
array([[[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]],
<BLANKLINE>
[[12, 13, 14, 15],
[16, 17, 18, 19],
[20, 21, 22, 23]]])
Sum over axes 0 and 2. The result has same number of dimensions
as the original array:
>>> np.apply_over_axes(np.sum, a, [0,2])
array([[[ 60],
[ 92],
[124]]])
>>> from numpy import *
>>> a = arange(24).reshape(2,3,4) # a has 3 axes: 0,1 and 2
>>> a
array([[[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]],
[[12, 13, 14, 15],
[16, 17, 18, 19],
[20, 21, 22, 23]]])
>>> apply_over_axes(sum, a, [0,2]) # sum over all axes except axis=1, result has same shape as original
array([[[ 60],
[ 92],
[124]]])
See also: apply_along_axis, vectorize
arange()
numpy.arange(...)
arange([start,] stop[, step,], dtype=None)
Return evenly spaced values within a given interval.
Values are generated within the half-open interval ``[start, stop)``
(in other words, the interval including `start` but excluding `stop`).
For integer arguments the function is equivalent to the Python built-in
`range <http://docs.python.org/lib/built-in-funcs.html>`_ function,
but returns a ndarray rather than a list.
Parameters
----------
start : number, optional
Start of interval. The interval includes this value. The default
start value is 0.
stop : number
End of interval. The interval does not include this value.
step : number, optional
Spacing between values. For any output `out`, this is the distance
between two adjacent values, ``out[i+1] - out[i]``. The default
step size is 1. If `step` is specified, `start` must also be given.
dtype : dtype
The type of the output array. If `dtype` is not given, infer the data
type from the other input arguments.
Returns
-------
out : ndarray
Array of evenly spaced values.
For floating point arguments, the length of the result is
``ceil((stop - start)/step)``. Because of floating point overflow,
this rule may result in the last element of `out` being greater
than `stop`.
See Also
--------
linspace : Evenly spaced numbers with careful handling of endpoints.
ogrid: Arrays of evenly spaced numbers in N-dimensions
mgrid: Grid-shaped arrays of evenly spaced numbers in N-dimensions
Examples
--------
>>> np.arange(3)
array([0, 1, 2])
>>> np.arange(3.0)
array([ 0., 1., 2.])
>>> np.arange(3,7)
array([3, 4, 5, 6])
>>> np.arange(3,7,2)
array([3, 5])
>>> from numpy import *
>>> arange(3)
array([0, 1, 2])
>>> arange(3.0)
array([ 0., 1., 2.])
>>> arange(3, dtype=float)
array([ 0., 1., 2.])
>>> arange(3,10) # start,stop
array([3, 4, 5, 6, 7, 8, 9])
>>> arange(3,10,2) # start,stop,step
array([3, 5, 7, 9])
See also: r_, linspace, logspace, mgrid, ogrid
arccos()
numpy.arccos(...)
y = arccos(x)
Trigonometric inverse cosine, element-wise.
The inverse of `cos` so that, if ``y = cos(x)``, then ``x = arccos(y)``.
Parameters
----------
x : array_like
`x`-coordinate on the unit circle.
For real arguments, the domain is [-1, 1].
Returns
-------
angle : ndarray
The angle of the ray intersecting the unit circle at the given
`x`-coordinate in radians [0, pi]. If `x` is a scalar then a
scalar is returned, otherwise an array of the same shape as `x`
is returned.
See Also
--------
cos, arctan, arcsin
Notes
-----
`arccos` is a multivalued function: for each `x` there are infinitely
many numbers `z` such that `cos(z) = x`. The convention is to return the
angle `z` whose real part lies in `[0, pi]`.
For real-valued input data types, `arccos` always returns real output.
For each value that cannot be expressed as a real number or infinity, it
yields ``nan`` and sets the `invalid` floating point error flag.
For complex-valued input, `arccos` is a complex analytical function that
has branch cuts `[-inf, -1]` and `[1, inf]` and is continuous from above
on the former and from below on the latter.
The inverse `cos` is also known as `acos` or cos^-1.
References
----------
.. [1] M. Abramowitz and I.A. Stegun, "Handbook of Mathematical Functions",
10th printing, 1964, pp. 79. http://www.math.sfu.ca/~cbm/aands/
.. [2] Wikipedia, "Inverse trigonometric function",
http://en.wikipedia.org/wiki/Arccos
Examples
--------
We expect the arccos of 1 to be 0, and of -1 to be pi:
>>> np.arccos([1, -1])
array([ 0. , 3.14159265])
Plot arccos:
>>> import matplotlib.pyplot as plt
>>> x = np.linspace(-1, 1, num=100)
>>> plt.plot(x, np.arccos(x))
>>> plt.axis('tight')
>>> plt.show()
>>> from numpy import *
>>> arccos(array([0, 1]))
array([ 1.57079633, 0. ])
See also: arcsin, arccosh, arctan, arctan2
arccosh()
numpy.arccosh(...)
y = arccosh(x)
Inverse hyperbolic cosine, elementwise.
Parameters
----------
x : array_like
Input array.
Returns
-------
out : ndarray
Array of the same shape and dtype as `x`.
Notes
-----
`arccosh` is a multivalued function: for each `x` there are infinitely
many numbers `z` such that `cosh(z) = x`. The convention is to return the
`z` whose imaginary part lies in `[-pi, pi]` and the real part in
``[0, inf]``.
For real-valued input data types, `arccosh` always returns real output.
For each value that cannot be expressed as a real number or infinity, it
yields ``nan`` and sets the `invalid` floating point error flag.
For complex-valued input, `arccosh` is a complex analytical function that
has a branch cut `[-inf, 1]` and is continuous from above on it.
References
----------
.. [1] M. Abramowitz and I.A. Stegun, "Handbook of Mathematical Functions",
10th printing, 1964, pp. 86. http://www.math.sfu.ca/~cbm/aands/
.. [2] Wikipedia, "Inverse hyperbolic function",
http://en.wikipedia.org/wiki/Arccosh
Examples
--------
>>> np.arccosh([np.e, 10.0])
array([ 1.65745445, 2.99322285])
>>> from numpy import *
>>> arccosh(array([e, 10.0]))
array([ 1.65745445, 2.99322285])
See also: arccos, arcsinh, arctanh
arcsin()
numpy.arcsin(...)
y = arcsin(x)
Inverse sine elementwise.
Parameters
----------
x : array_like
`y`-coordinate on the unit circle.
Returns
-------
angle : ndarray
The angle of the ray intersecting the unit circle at the given
`y`-coordinate in radians ``[-pi, pi]``. If `x` is a scalar then
a scalar is returned, otherwise an array is returned.
See Also
--------
sin, arctan, arctan2
Notes
-----
`arcsin` is a multivalued function: for each `x` there are infinitely
many numbers `z` such that `sin(z) = x`. The convention is to return the
angle `z` whose real part lies in `[-pi/2, pi/2]`.
For real-valued input data types, `arcsin` always returns real output.
For each value that cannot be expressed as a real number or infinity, it
yields ``nan`` and sets the `invalid` floating point error flag.
For complex-valued input, `arcsin` is a complex analytical function that
has branch cuts `[-inf, -1]` and `[1, inf]` and is continuous from above
on the former and from below on the latter.
The inverse sine is also known as `asin` or ``sin^-1``.
References
----------
.. [1] M. Abramowitz and I.A. Stegun, "Handbook of Mathematical Functions",
10th printing, 1964, pp. 79. http://www.math.sfu.ca/~cbm/aands/
.. [2] Wikipedia, "Inverse trigonometric function",
http://en.wikipedia.org/wiki/Arcsin
Examples
--------
>>> np.arcsin(1) # pi/2
1.5707963267948966
>>> np.arcsin(-1) # -pi/2
-1.5707963267948966
>>> np.arcsin(0)
0.0
>>> from numpy import *
>>> arcsin(array([0, 1]))
array([ 0. , 1.57079633])
See also: arccos, arctan, arcsinh
arcsinh()
numpy.arcsinh(...)
y = arcsinh(x)
Inverse hyperbolic sine elementwise.
Parameters
----------
x : array_like
Input array.
Returns
-------
out : ndarray
Array of of the same shape as `x`.
Notes
-----
`arcsinh` is a multivalued function: for each `x` there are infinitely
many numbers `z` such that `sinh(z) = x`. The convention is to return the
`z` whose imaginary part lies in `[-pi/2, pi/2]`.
For real-valued input data types, `arcsinh` always returns real output.
For each value that cannot be expressed as a real number or infinity, it
returns ``nan`` and sets the `invalid` floating point error flag.
For complex-valued input, `arccos` is a complex analytical function that
has branch cuts `[1j, infj]` and `[-1j, -infj]` and is continuous from
the right on the former and from the left on the latter.
The inverse hyperbolic sine is also known as `asinh` or ``sinh^-1``.
References
----------
.. [1] M. Abramowitz and I.A. Stegun, "Handbook of Mathematical Functions",
10th printing, 1964, pp. 86. http://www.math.sfu.ca/~cbm/aands/
.. [2] Wikipedia, "Inverse hyperbolic function",
http://en.wikipedia.org/wiki/Arcsinh
Examples
--------
>>> np.arcsinh(np.array([np.e, 10.0]))
array([ 1.72538256, 2.99822295])
>>> from numpy import *
>>> arcsinh(array([e, 10.0]))
array([ 1.72538256, 2.99822295])
See also: arccosh, arcsin, arctanh
arctan()
numpy.arctan(...)
y = arctan(x)
Trigonometric inverse tangent, element-wise.
The inverse of tan, so that if ``y = tan(x)`` then
``x = arctan(y)``.
Parameters
----------
x : array_like
Input values. `arctan` is applied to each element of `x`.
Returns
-------
out : ndarray
Out has the same shape as `x`. Its real part is
in ``[-pi/2, pi/2]``. It is a scalar if `x` is a scalar.
See Also
--------
arctan2 : Calculate the arctan of y/x.
Notes
-----
`arctan` is a multivalued function: for each `x` there are infinitely
many numbers `z` such that `tan(z) = x`. The convention is to return the
angle `z` whose real part lies in `[-pi/2, pi/2]`.
For real-valued input data types, `arctan` always returns real output.
For each value that cannot be expressed as a real number or infinity, it
yields ``nan`` and sets the `invalid` floating point error flag.
For complex-valued input, `arctan` is a complex analytical function that
has branch cuts `[1j, infj]` and `[-1j, -infj]` and is continuous from the
left on the former and from the right on the latter.
The inverse tangent is also known as `atan` or ``tan^-1``.
References
----------
.. [1] M. Abramowitz and I.A. Stegun, "Handbook of Mathematical Functions",
10th printing, 1964, pp. 79. http://www.math.sfu.ca/~cbm/aands/
.. [2] Wikipedia, "Inverse trigonometric function",
http://en.wikipedia.org/wiki/Arctan
Examples
--------
We expect the arctan of 0 to be 0, and of 1 to be :math:`\pi/4`:
>>> np.arctan([0, 1])
array([ 0. , 0.78539816])
>>> np.pi/4
0.78539816339744828
Plot arctan:
>>> import matplotlib.pyplot as plt
>>> x = np.linspace(-10, 10)
>>> plt.plot(x, np.arctan(x))
>>> plt.axis('tight')
>>> plt.show()
>>> from numpy import *
>>> arctan(array([0, 1]))
array([ 0. , 0.78539816])
See also: arccos, arcsin, arctanh
arctan2()
numpy.arctan2(...)
y = arctan2(x1,x2)
Elementwise arc tangent of ``x1/x2`` choosing the quadrant correctly.
The quadrant (ie. branch) is chosen so that ``arctan2(x1, x2)``
is the signed angle in radians between the line segments
``(0,0) - (1,0)`` and ``(0,0) - (x2,x1)``. This function is defined
also for `x2` = 0.
`arctan2` is not defined for complex-valued arguments.
Parameters
----------
x1 : array_like, real-valued
y-coordinates.
x2 : array_like, real-valued
x-coordinates. `x2` must be broadcastable to match the shape of `x1`,
or vice versa.
Returns
-------
angle : ndarray
Array of angles in radians, in the range ``[-pi, pi]``.
See Also
--------
arctan, tan
Notes
-----
`arctan2` is identical to the `atan2` function of the underlying
C library. The following special values are defined in the C standard [2]:
====== ====== ================
`x1` `x2` `arctan2(x1,x2)`
====== ====== ================
+/- 0 +0 +/- 0
+/- 0 -0 +/- pi
> 0 +/-inf +0 / +pi
< 0 +/-inf -0 / -pi
+/-inf +inf +/- (pi/4)
+/-inf -inf +/- (3*pi/4)
====== ====== ================
Note that +0 and -0 are distinct floating point numbers.
References
----------
.. [1] Wikipedia, "atan2",
http://en.wikipedia.org/wiki/Atan2
.. [2] ISO/IEC standard 9899:1999, "Programming language C", 1999.
Examples
--------
Consider four points in different quadrants:
>>> x = np.array([-1, +1, +1, -1])
>>> y = np.array([-1, -1, +1, +1])
>>> np.arctan2(y, x) * 180 / np.pi
array([-135., -45., 45., 135.])
Note the order of the parameters. `arctan2` is defined also when `x2` = 0
and at several other special points, obtaining values in
the range ``[-pi, pi]``:
>>> np.arctan2([1., -1.], [0., 0.])
array([ 1.57079633, -1.57079633])
>>> np.arctan2([0., 0., np.inf], [+0., -0., np.inf])
array([ 0. , 3.14159265, 0.78539816])
>>> from numpy import *
>>> arctan2(array([0, 1]), array([1, 0]))
array([ 0. , 1.57079633])
See also: arcsin, arccos, arctan, arctanh
arctanh()
numpy.arctanh(...)
y = arctanh(x)
Inverse hyperbolic tangent elementwise.
Parameters
----------
x : array_like
Input array.
Returns
-------
out : ndarray
Array of the same shape as `x`.
Notes
-----
`arctanh` is a multivalued function: for each `x` there are infinitely
many numbers `z` such that `tanh(z) = x`. The convention is to return the
`z` whose imaginary part lies in `[-pi/2, pi/2]`.
For real-valued input data types, `arctanh` always returns real output.
For each value that cannot be expressed as a real number or infinity, it
yields ``nan`` and sets the `invalid` floating point error flag.
For complex-valued input, `arctanh` is a complex analytical function that
has branch cuts `[-1, -inf]` and `[1, inf]` and is continuous from
above on the former and from below on the latter.
The inverse hyperbolic tangent is also known as `atanh` or ``tanh^-1``.
References
----------
.. [1] M. Abramowitz and I.A. Stegun, "Handbook of Mathematical Functions",
10th printing, 1964, pp. 86. http://www.math.sfu.ca/~cbm/aands/
.. [2] Wikipedia, "Inverse hyperbolic function",
http://en.wikipedia.org/wiki/Arctanh
Examples
--------
>>> np.arctanh([0, -0.5])
array([ 0. , -0.54930614])
>>> from numpy import *
>>> arctanh(array([0, -0.5]))
array([ 0. , -0.54930614])
See also: arcsinh, arccosh, arctan, arctan2
argmax()
numpy.argmax(a, axis=None)
Indices of the maximum values along an axis.
Parameters
----------
a : array_like
Input array.
axis : int, optional
By default, the index is into the flattened array, otherwise
along the specified axis.
Returns
-------
index_array : ndarray, int
Array of indices into the array. It has the same shape as `a`,
except with `axis` removed.
See Also
--------
argmin : Indices of the minimum values along an axis.
amax : The maximum value along a given axis.
unravel_index : Convert a flat index into an index tuple.
Examples
--------
>>> a = np.arange(6).reshape(2,3)
>>> np.argmax(a)
5
>>> np.argmax(a, axis=0)
array([1, 1, 1])
>>> np.argmax(a, axis=1)
array([2, 2])
ndarray.argmax(...)
a.argmax(axis=None, out=None)
Return indices of the maximum values along the given axis of `a`.
Parameters
----------
axis : int, optional
Axis along which to operate. By default flattened input is used.
out : ndarray, optional
Alternative output array in which to place the result. Must
be of the same shape and buffer length as the expected output.
Returns
-------
index_array : ndarray
An array of indices or single index value, or a reference to `out`
if it was specified.
Examples
--------
>>> a = np.arange(6).reshape(2,3)
>>> a.argmax()
5
>>> a.argmax(0)
array([1, 1, 1])
>>> a.argmax(1)
array([2, 2])
>>> from numpy import *
>>> a = array([10,20,30])
>>> maxindex = a.argmax()
>>> a[maxindex]
30
>>> a = array([[10,50,30],[60,20,40]])
>>> maxindex = a.argmax()
>>> maxindex
3
>>> a.ravel()[maxindex]
60
>>> a.argmax(axis=0) # for each column: the row index of the maximum value
array([1, 0, 1])
>>> a.argmax(axis=1) # for each row: the column index of the maximum value
array([1, 0])
>>> argmax(a) # also exists, slower, default is axis=-1
array([1, 0])
See also: argmin, nan, min, max, maximum, minimum
argmin()
numpy.argmin(a, axis=None)
Return the indices of the minimum values along an axis.
See Also
--------
argmax : Similar function. Please refer to `numpy.argmax` for detailed
documentation.
ndarray.argmin(...)
a.argmin(axis=None, out=None) Return indices of the minimum values along the given axis of `a`. Refer to `numpy.ndarray.argmax` for detailed documentation.
>>> from numpy import *
>>> a = array([10,20,30])
>>> minindex = a.argmin()
>>> a[minindex]
10
>>> a = array([[10,50,30],[60,20,40]])
>>> minindex = a.argmin()
>>> minindex
0
>>> a.ravel()[minindex]
10
>>> a.argmin(axis=0) # for each column: the row index of the minimum value
array([0, 1, 0])
>>> a.argmin(axis=1) # for each row: the column index of the minimum value
array([0, 1])
>>> argmin(a) # also exists, slower, default is axis=-1
array([0, 1])
See also: argmax, nan, min, max, maximum, minimum
argsort()
numpy.argsort(a, axis=-1, kind='quicksort', order=None)
Returns the indices that would sort an array.
Perform an indirect sort along the given axis using the algorithm specified
by the `kind` keyword. It returns an array of indices of the same shape as
`a` that index data along the given axis in sorted order.
Parameters
----------
a : array_like
Array to sort.
axis : int, optional
Axis along which to sort. If not given, the flattened array is used.
kind : {'quicksort', 'mergesort', 'heapsort'}, optional
Sorting algorithm.
order : list, optional
When `a` is an array with fields defined, this argument specifies
which fields to compare first, second, etc. Not all fields need be
specified.
Returns
-------
index_array : ndarray, int
Array of indices that sort `a` along the specified axis.
In other words, ``a[index_array]`` yields a sorted `a`.
See Also
--------
sort : Describes sorting algorithms used.
lexsort : Indirect stable sort with multiple keys.
ndarray.sort : Inplace sort.
Notes
-----
See `sort` for notes on the different sorting algorithms.
Examples
--------
One dimensional array:
>>> x = np.array([3, 1, 2])
>>> np.argsort(x)
array([1, 2, 0])
Two-dimensional array:
>>> x = np.array([[0, 3], [2, 2]])
>>> x
array([[0, 3],
[2, 2]])
>>> np.argsort(x, axis=0)
array([[0, 1],
[1, 0]])
>>> np.argsort(x, axis=1)
array([[0, 1],
[0, 1]])
Sorting with keys:
>>> x = np.array([(1, 0), (0, 1)], dtype=[('x', '<i4'), ('y', '<i4')])
>>> x
array([(1, 0), (0, 1)],
dtype=[('x', '<i4'), ('y', '<i4')])
>>> np.argsort(x, order=('x','y'))
array([1, 0])
>>> np.argsort(x, order=('y','x'))
array([0, 1])
ndarray.argsort(...)
a.argsort(axis=-1, kind='quicksort', order=None) Returns the indices that would sort this array. Refer to `numpy.argsort` for full documentation. See Also -------- numpy.argsort : equivalent function
argsort(axis=-1, kind="quicksort")
>>> from numpy import *
>>> a = array([2,0,8,4,1])
>>> ind = a.argsort() # indices of sorted array using quicksort (default)
>>> ind
array([1, 4, 0, 3, 2])
>>> a[ind] # same effect as a.sort()
array([0, 1, 2, 4, 8])
>>> ind = a.argsort(kind='merge') # algorithm options are 'quicksort', 'mergesort' and 'heapsort'
>>> a = array([[8,4,1],[2,0,9]])
>>> ind = a.argsort(axis=0) # sorts on columns. NOT the same as a.sort(axis=1)
>>> ind
array([[1, 1, 0],
[0, 0, 1]])
>>> a[ind,[[0,1,2],[0,1,2]]] # 2-D arrays need fancy indexing if you want to sort them.
array([[2, 0, 1],
[8, 4, 9]])
>>> ind = a.argsort(axis=1) # sort along rows. Can use a.argsort(axis=-1) for last axis.
>>> ind
array([[2, 1, 0],
[1, 0, 2]])
>>> a = ones(17)
>>> a.argsort() # quicksort doesn't preserve original order.
array([ 0, 14, 13, 12, 11, 10, 9, 15, 8, 6, 5, 4, 3, 2, 1, 7, 16])
>>> a.argsort(kind="mergesort") # mergesort preserves order when possible. It is a stable sort.
array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16])
>>> ind = argsort(a) # there is a functional form
argwhere()
numpy.argwhere(a)
Find the indices of array elements that are non-zero, grouped by element.
Parameters
----------
a : array_like
Input data.
Returns
-------
index_array : ndarray
Indices of elements that are non-zero. Indices are grouped by element.
See Also
--------
where, nonzero
Notes
-----
``np.argwhere(a)`` is the same as ``np.transpose(np.nonzero(a))``.
The output of ``argwhere`` is not suitable for indexing arrays.
For this purpose use ``where(a)`` instead.
Examples
--------
>>> x = np.arange(6).reshape(2,3)
>>> x
array([[0, 1, 2],
[3, 4, 5]])
>>> np.argwhere(x>1)
array([[0, 2],
[1, 0],
[1, 1],
[1, 2]])
around()
numpy.around(a, decimals=0, out=None)
Evenly round to the given number of decimals.
Parameters
----------
a : array_like
Input data.
decimals : int, optional
Number of decimal places to round to (default: 0). If
decimals is negative, it specifies the number of positions to
the left of the decimal point.
out : ndarray, optional
Alternative output array in which to place the result. It must have
the same shape as the expected output, but the type of the output
values will be cast if necessary.
Returns
-------
rounded_array : ndarray
An array of the same type as `a`, containing the rounded values.
Unless `out` was specified, a new array is created. A reference to
the result is returned.
The real and imaginary parts of complex numbers are rounded
separately. The result of rounding a float is a float.
See Also
--------
ndarray.round : equivalent method
Notes
-----
For values exactly halfway between rounded decimal values, Numpy
rounds to the nearest even value. Thus 1.5 and 2.5 round to 2.0,
-0.5 and 0.5 round to 0.0, etc. Results may also be surprising due
to the inexact representation of decimal fractions in the IEEE
floating point standard [1]_ and errors introduced when scaling
by powers of ten.
References
----------
.. [1] "Lecture Notes on the Status of IEEE 754", William Kahan,
http://www.cs.berkeley.edu/~wkahan/ieee754status/IEEE754.PDF
.. [2] "How Futile are Mindless Assessments of
Roundoff in Floating-Point Computation?", William Kahan,
http://www.cs.berkeley.edu/~wkahan/Mindless.pdf
Examples
--------
>>> np.around([.5, 1.5, 2.5, 3.5, 4.5])
array([ 0., 2., 2., 4., 4.])
>>> np.around([1,2,3,11], decimals=1)
array([ 1, 2, 3, 11])
>>> np.around([1,2,3,11], decimals=-1)
array([ 0, 0, 0, 10])
array()
numpy.array(...)
array(object, dtype=None, copy=True, order=None, subok=True, ndmin=True)
Create an array.
Parameters
----------
object : array_like
An array, any object exposing the array interface, an
object whose __array__ method returns an array, or any
(nested) sequence.
dtype : data-type, optional
The desired data-type for the array. If not given, then
the type will be determined as the minimum type required
to hold the objects in the sequence. This argument can only
be used to 'upcast' the array. For downcasting, use the
.astype(t) method.
copy : bool, optional
If true (default), then the object is copied. Otherwise, a copy
will only be made if __array__ returns a copy, if obj is a
nested sequence, or if a copy is needed to satisfy any of the other
requirements (`dtype`, `order`, etc.).
order : {'C', 'F', 'A'}, optional
Specify the order of the array. If order is 'C' (default), then the
array will be in C-contiguous order (last-index varies the
fastest). If order is 'F', then the returned array
will be in Fortran-contiguous order (first-index varies the
fastest). If order is 'A', then the returned array may
be in any order (either C-, Fortran-contiguous, or even
discontiguous).
subok : bool, optional
If True, then sub-classes will be passed-through, otherwise
the returned array will be forced to be a base-class array.
ndmin : int, optional
Specifies the minimum number of dimensions that the resulting
array should have. Ones will be pre-pended to the shape as
needed to meet this requirement.
Examples
--------
>>> np.array([1, 2, 3])
array([1, 2, 3])
Upcasting:
>>> np.array([1, 2, 3.0])
array([ 1., 2., 3.])
More than one dimension:
>>> np.array([[1, 2], [3, 4]])
array([[1, 2],
[3, 4]])
Minimum dimensions 2:
>>> np.array([1, 2, 3], ndmin=2)
array([[1, 2, 3]])
Type provided:
>>> np.array([1, 2, 3], dtype=complex)
array([ 1.+0.j, 2.+0.j, 3.+0.j])
Data-type consisting of more than one element:
>>> x = np.array([(1,2),(3,4)],dtype=[('a','<i4'),('b','<i4')])
>>> x['a']
array([1, 3])
Creating an array from sub-classes:
>>> np.array(np.mat('1 2; 3 4'))
array([[1, 2],
[3, 4]])
>>> np.array(np.mat('1 2; 3 4'), subok=True)
matrix([[1, 2],
[3, 4]])
numpy.core.records.array(obj, dtype=None, shape=None, offset=0, strides=None, formats=None, names=None, titles=None, aligned=False, byteorder=None, copy=True)
Construct a record array from a wide-variety of objects.
>>> from numpy import *
>>> array([1,2,3]) # conversion from a list to an array
array([1, 2, 3])
>>> array([1,2,3], dtype=complex) # output type is specified
array([ 1.+0.j, 2.+0.j, 3.+0.j])
>>> array(1, copy=0, subok=1, ndmin=1) # basically equivalent to atleast_1d
array([1])
>>> array(1, copy=0, subok=1, ndmin=2) # basically equivalent to atleast_2d
array([[1]])
>>> array(1, subok=1, ndmin=2) # like atleast_2d but always makes a copy
array([[1]])
>>> mydescriptor = {'names': ('gender','age','weight'), 'formats': ('S1', 'f4', 'f4')} # one way of specifying the data type
>>> a = array([('M',64.0,75.0),('F',25.0,60.0)], dtype=mydescriptor) # recarray
>>> print a
[('M', 64.0, 75.0) ('F', 25.0, 60.0)]
>>> a['weight']
array([ 75., 60.], dtype=float32)
>>> a.dtype.names # Access to the ordered field names
('gender','age','weight')
>>> mydescriptor = [('age',int16),('Nchildren',int8),('weight',float32)] # another way of specifying the data type
>>> a = array([(64,2,75.0),(25,0,60.0)], dtype=mydescriptor)
>>> a['Nchildren']
array([2, 0], dtype=int8)
>>> mydescriptor = dtype([('x', 'f4'),('y', 'f4'), # nested recarray
... ('nested', [('i', 'i2'),('j','i2')])])
>>> array([(1.0, 2.0, (1,2))], dtype=mydescriptor) # input one row
array([(1.0, 2.0, (1, 2))],
dtype=[('x', '<f4'), ('y', '<f4'), ('nested', [('i', '<i2'), ('j', '<i2')])])
>>> array([(1.0, 2.0, (1,2)), (2.1, 3.2, (3,2))], dtype=mydescriptor) # input two rows
array([(1.0, 2.0, (1, 2)), (2.0999999046325684, 3.2000000476837158, (3, 2))],
dtype=[('x', '<f4'), ('y', '<f4'), ('nested', [('i', '<i2'), ('j', '<i2')])])
>>> a=array([(1.0, 2.0, (1,2)), (2.1, 3.2, (3,2))], dtype=mydescriptor) # getting some columns
>>> a['x'] # a plain column
array([ 1. , 2.0999999], dtype=float32)
>>> a['nested'] # a nested column
array([(1, 2), (3, 2)],
dtype=[('i', '<i2'), ('j', '<i2')])
>>> a['nested']['i'] # a plain column inside a nested column
>>> mydescriptor = dtype([('x', 'f4'),('y', 'f4'), # nested recarray
... ('nested', [('i', 'i2'),('j','i2')])])
>>> array([(1.0, 2.0, (1,2))], dtype=mydescriptor) # input one row
array([(1.0, 2.0, (1, 2))],
dtype=[('x', '<f4'), ('y', '<f4'), ('nested', [('i', '<i2'), ('j', '<i2')])])
>>> array([(1.0, 2.0, (1,2)), (2.1, 3.2, (3,2))], dtype=mydescriptor) # input two rows
array([(1.0, 2.0, (1, 2)), (2.0999999046325684, 3.2000000476837158, (3, 2))],
dtype=[('x', '<f4'), ('y', '<f4'), ('nested', [('i', '<i2'), ('j', '<i2')])])
>>> a=array([(1.0, 2.0, (1,2)), (2.1, 3.2, (3,2))], dtype=mydescriptor) # getting some columns
>>> a['x'] # a plain column
array([ 1. , 2.0999999], dtype=float32)
>>> a['nested'] # a nested column
array([(1, 2), (3, 2)],
dtype=[('i', '<i2'), ('j', '<i2')])
>>> a['nested']['i'] # a plain column inside a nested column
array([1, 3], dtype=int16)
array2string()
numpy.array2string(a, max_line_width=None, precision=None, suppress_small=None, separator=' ', prefix="", style=<built-in function repr>)
Return a string representation of an array.
Parameters
----------
a : ndarray
Input array.
max_line_width : int, optional
The maximum number of columns the string should span. Newline
characters splits the string appropriately after array elements.
precision : int, optional
Floating point precision. Default is the current printing
precision (usually 8), which can be altered using `set_printoptions`.
suppress_small : bool, optional
Represent very small numbers as zero.
separator : string, optional
Inserted between elements.
prefix : string, optional
An array is typically printed as::
'prefix(' + array2string(a) + ')'
The length of the prefix string is used to align the
output correctly.
style : function, optional
Callable.
See Also
--------
array_str, array_repr, set_printoptions
Examples
--------
>>> x = np.array([1e-16,1,2,3])
>>> print np.array2string(x, precision=2, separator=',',
... suppress_small=True)
[ 0., 1., 2., 3.]
array_equal()
numpy.array_equal(a1, a2)
True if two arrays have the same shape and elements, False otherwise.
Parameters
----------
a1 : array_like
First input array.
a2 : array_like
Second input array.
Returns
-------
b : {True, False}
Returns True if the arrays are equal.
Examples
--------
>>> np.array_equal([1,2],[1,2])
True
>>> np.array_equal(np.array([1,2]),np.array([1,2]))
True
>>> np.array_equal([1,2],[1,2,3])
False
>>> np.array_equal([1,2],[1,4])
False
array_equiv()
numpy.array_equiv(a1, a2)
Returns True if input arrays are shape consistent and all elements equal.
Parameters
----------
a1 : array_like
Input array.
a2 : array_like
Input array.
Returns
-------
out : bool
True if equivalent, False otherwise.
Examples
--------
>>> np.array_equiv([1,2],[1,2])
>>> True
>>> np.array_equiv([1,2],[1,3])
>>> False
>>> np.array_equiv([1,2], [[1,2],[1,2]])
>>> True
>>> np.array_equiv([1,2], [[1,2],[1,3]])
>>> False
array_repr()
numpy.array_repr(arr, max_line_width=None, precision=None, suppress_small=None)
Return the string representation of an array. Parameters ---------- arr : ndarray Input array. max_line_width : int The maximum number of columns the string should span. Newline characters splits the string appropriately after array elements. precision : int Floating point precision. suppress_small : bool Represent very small numbers as zero. Returns ------- string : str The string representation of an array. Examples -------- >>> np.array_repr(np.array([1,2])) 'array([1, 2])' >>> np.array_repr(np.ma.array([0.])) 'MaskedArray([ 0.])' >>> np.array_repr(np.array([], np.int32)) 'array([], dtype=int32)'
array_split()
numpy.array_split(ary, indices_or_sections, axis=0)
Split an array into multiple sub-arrays of equal or near-equal size.
Please refer to the `numpy.split` documentation. The only difference
between these functions is that `array_split` allows `indices_or_sections`
to be an integer that does *not* equally divide the axis.
See Also
--------
numpy.split : Split array into multiple sub-arrays.
Examples
--------
>>> x = np.arange(8.0)
>>> np.array_split(x, 3)
[array([ 0., 1., 2.]), array([ 3., 4., 5.]), array([ 6., 7.])]
>>> from numpy import *
>>> a = array([[1,2,3,4],[5,6,7,8]])
>>> array_split(a,2,axis=0) # split a in 2 parts. row-wise
[array([[1, 2, 3, 4]]), array([[5, 6, 7, 8]])]
>>> array_split(a,4,axis=1) # split a in 4 parts, column-wise
[array([[1],
[5]]), array([[2],
[6]]), array([[3],
[7]]), array([[4],
[8]])]
>>> array_split(a,3,axis=1) # impossible to split in 3 equal parts -> first part(s) are bigger
[array([[1, 2],
[5, 6]]), array([[3],
[7]]), array([[4],
[8]])]
>>> array_split(a,[2,3],axis=1) # make a split before the 2nd and the 3rd column
[array([[1, 2],
[5, 6]]), array([[3],
[7]]), array([[4],
[8]])]
See also: dsplit, hsplit, vsplit, split, concatenate
array_str()
numpy.array_str(a, max_line_width=None, precision=None, suppress_small=None)
Return a string representation of an array.
Parameters
----------
a : ndarray
Input array.
max_line_width : int, optional
Inserts newlines if text is longer than `max_line_width`.
precision : int, optional
If `a` is float, `precision` sets loating point precision.
suppress_small : boolean, optional
Represent very small numbers as zero.
See Also
--------
array2string, array_repr
Examples
--------
>>> np.array_str(np.arange(3))
>>> '[0 1 2]'
arrayrange
Synonym for arange()
See arange
asanyarray()
numpy.asanyarray(a, dtype=None, order=None)
Convert the input to a ndarray, but pass ndarray subclasses through.
Parameters
----------
a : array_like
Input data, in any form that can be converted to an array. This
includes scalars, lists, lists of tuples, tuples, tuples of tuples,
tuples of lists and ndarrays.
dtype : data-type, optional
By default, the data-type is inferred from the input data.
order : {'C', 'F'}, optional
Whether to use row-major ('C') or column-major ('F') memory
representation. Defaults to 'C'.
Returns
-------
out : ndarray or an ndarray subclass
Array interpretation of `a`. If `a` is an ndarray or a subclass
of ndarray, it is returned as-is and no copy is performed.
See Also
--------
asarray : Similar function which always returns ndarrays.
ascontiguousarray : Convert input to a contiguous array.
asfarray : Convert input to a floating point ndarray.
asfortranarray : Convert input to an ndarray with column-major
memory order.
asarray_chkfinite : Similar function which checks input for NaNs and Infs.
fromiter : Create an array from an iterator.
fromfunction : Construct an array by executing a function on grid
positions.
Examples
--------
Convert a list into an array:
>>> a = [1, 2]
>>> np.asanyarray(a)
array([1, 2])
Instances of `ndarray` subclasses are passed through as-is:
>>> a = np.matrix([1, 2])
>>> np.asanyarray(a) is a
True
>>> from numpy import *
>>> a = array([[1,2],[5,8]])
>>> a
array([[1, 2],
[5, 8]])
>>> m = matrix('1 2; 5 8')
>>> m
matrix([[1, 2],
[5, 8]])
>>> asanyarray(a) # the array a is returned unmodified
array([[1, 2],
[5, 8]])
>>> asanyarray(m) # the matrix m is returned unmodified
matrix([[1, 2],
[5, 8]])
>>> asanyarray([1,2,3]) # a new array is constructed from the list
array([1, 2, 3])
See also: asmatrix, asarray, array, mat
asarray()
numpy.asarray(a, dtype=None, order=None)
Convert the input to an array.
Parameters
----------
a : array_like
Input data, in any form that can be converted to an array. This
includes lists, lists of tuples, tuples, tuples of tuples, tuples
of lists and ndarrays.
dtype : data-type, optional
By default, the data-type is inferred from the input data.
order : {'C', 'F'}, optional
Whether to use row-major ('C') or column-major ('FORTRAN') memory
representation. Defaults to 'C'.
Returns
-------
out : ndarray
Array interpretation of `a`. No copy is performed if the input
is already an ndarray. If `a` is a subclass of ndarray, a base
class ndarray is returned.
See Also
--------
asanyarray : Similar function which passes through subclasses.
ascontiguousarray : Convert input to a contiguous array.
asfarray : Convert input to a floating point ndarray.
asfortranarray : Convert input to an ndarray with column-major
memory order.
asarray_chkfinite : Similar function which checks input for NaNs and Infs.
fromiter : Create an array from an iterator.
fromfunction : Construct an array by executing a function on grid
positions.
Examples
--------
Convert a list into an array:
>>> a = [1, 2]
>>> np.asarray(a)
array([1, 2])
Existing arrays are not copied:
>>> a = np.array([1, 2])
>>> np.asarray(a) is a
True
>>> from numpy import *
>>> m = matrix('1 2; 5 8')
>>> m
matrix([[1, 2],
[5, 8]])
>>> a = asarray(m) # a is array type with same contents as m -- data is not copied
>>> a
array([[1, 2],
[5, 8]])
>>> m[0,0] = -99
>>> m
matrix([[-99, 2],
[ 5, 8]])
>>> a # no copy was made, so modifying m modifies a, and vice versa
array([[-99, 2],
[ 5, 8]])
See also: asmatrix, array, matrix, mat
asarray_chkfinite()
numpy.asarray_chkfinite(a)
Convert the input to an array, checking for NaNs or Infs.
Parameters
----------
a : array_like
Input data, in any form that can be converted to an array. This
includes lists, lists of tuples, tuples, tuples of tuples, tuples
of lists and ndarrays. Success requires no NaNs or Infs.
dtype : data-type, optional
By default, the data-type is inferred from the input data.
order : {'C', 'F'}, optional
Whether to use row-major ('C') or column-major ('FORTRAN') memory
representation. Defaults to 'C'.
Returns
-------
out : ndarray
Array interpretation of `a`. No copy is performed if the input
is already an ndarray. If `a` is a subclass of ndarray, a base
class ndarray is returned.
Raises
------
ValueError
Raises ValueError if `a` contains NaN (Not a Number) or Inf (Infinity).
See Also
--------
asarray : Create and array.
asanyarray : Similar function which passes through subclasses.
ascontiguousarray : Convert input to a contiguous array.
asfarray : Convert input to a floating point ndarray.
asfortranarray : Convert input to an ndarray with column-major
memory order.
fromiter : Create an array from an iterator.
fromfunction : Construct an array by executing a function on grid
positions.
Examples
--------
Convert a list into an array. If all elements are finite
``asarray_chkfinite`` is identical to ``asarray``.
>>> a = [1, 2]
>>> np.asarray_chkfinite(a)
array([1, 2])
Raises ValueError if array_like contains Nans or Infs.
>>> a = [1, 2, np.inf]
>>> try:
... np.asarray_chkfinite(a)
... except ValueError:
... print 'ValueError'
...
ValueError
ascontiguousarray()
numpy.ascontiguousarray(a, dtype=None)
Return a contiguous array in memory (C order).
Parameters
----------
a : array_like
Input array.
dtype : string
Type code of returned array.
Returns
-------
out : ndarray
Contiguous array of same shape and content as `a` with type `dtype`.
asfarray()
numpy.asfarray(a, dtype=<type 'numpy.float64'>)
Return an array converted to float type.
Parameters
----------
a : array_like
Input array.
dtype : string or dtype object, optional
Float type code to coerce input array `a`. If one of the 'int' dtype,
it is replaced with float64.
Returns
-------
out : ndarray, float
Input `a` as a float ndarray.
Examples
--------
>>> np.asfarray([2, 3])
array([ 2., 3.])
>>> np.asfarray([2, 3], dtype='float')
array([ 2., 3.])
>>> np.asfarray([2, 3], dtype='int8')
array([ 2., 3.])
asfortranarray()
numpy.asfortranarray(a, dtype=None)
Return an array laid out in Fortran-order in memory.
Parameters
----------
a : array_like
Input array.
dtype : data-type, optional
By default, the data-type is inferred from the input data.
Returns
-------
out : ndarray
Array interpretation of `a` in Fortran (column-order).
See Also
--------
asarray : Similar function which always returns ndarrays.
ascontiguousarray : Convert input to a contiguous array.
asfarray : Convert input to a floating point ndarray.
asanyarray : Convert input to an ndarray with either row or
column-major memory order.
asarray_chkfinite : Similar function which checks input for NaNs and Infs.
fromiter : Create an array from an iterator.
fromfunction : Construct an array by executing a function on grid
positions.
asmatrix()
numpy.asmatrix(data, dtype=None)
Interpret the input as a matrix.
Unlike `matrix`, `asmatrix` does not make a copy if the input is already
a matrix or an ndarray. Equivalent to ``matrix(data, copy=False)``.
Parameters
----------
data : array_like
Input data.
Returns
-------
mat : matrix
`data` interpreted as a matrix.
Examples
--------
>>> x = np.array([[1, 2], [3, 4]])
>>> m = np.asmatrix(x)
>>> x[0,0] = 5
>>> m
matrix([[5, 2],
[3, 4]])
>>> from numpy import *
>>> a = array([[1,2],[5,8]])
>>> a
array([[1, 2],
[5, 8]])
>>> m = asmatrix(a) # m is matrix type with same contents as a -- data is not copied
>>> m
matrix([[1, 2],
[5, 8]])
>>> a[0,0] = -99
>>> a
array([[-99, 2],
[ 5, 8]])
>>> m # no copy was made so modifying a modifies m, and vice versa
matrix([[-99, 2],
[ 5, 8]])
See also: asarray, array, matrix, mat
asscalar()
numpy.asscalar(a)
Convert an array of size 1 to its scalar equivalent.
Parameters
----------
a : ndarray
Input array.
Returns
-------
out : scalar
Scalar of size 1 array.
Examples
--------
>>> np.asscalar(np.array([24]))
>>> 24
astype()
ndarray.astype(...)
a.astype(t)
Copy of the array, cast to a specified type.
Parameters
----------
t : string or dtype
Typecode or data-type to which the array is cast.
Examples
--------
>>> x = np.array([1, 2, 2.5])
>>> x
array([ 1. , 2. , 2.5])
>>> x.astype(int)
array([1, 2, 2])
>>> from numpy import *
>>> x = array([1,2,3])
>>> y = x.astype(float64) # convert from int32 to float64
>>> type(y[0])
<type 'numpy.float64'>
>>> x.astype(None) # None implies converting to the default (float64)
array([1., 2., 3.])
See also: cast, dtype, ceil, floor, round_, fix
atleast_1d()
numpy.atleast_1d(*arys)
Convert inputs to arrays with at least one dimension.
Scalar inputs are converted to 1-dimensional arrays, whilst
higher-dimensional inputs are preserved.
Parameters
----------
array1, array2, ... : array_like
One or more input arrays.
Returns
-------
ret : ndarray
An array, or sequence of arrays, each with ``a.ndim >= 1``.
Copies are made only if necessary.
See Also
--------
atleast_2d, atleast_3d
Examples
--------
>>> np.atleast_1d(1.0)
array([ 1.])
>>> x = np.arange(9.0).reshape(3,3)
>>> np.atleast_1d(x)
array([[ 0., 1., 2.],
[ 3., 4., 5.],
[ 6., 7., 8.]])
>>> np.atleast_1d(x) is x
True
>>> np.atleast_1d(1, [3, 4])
[array([1]), array([3, 4])]
>>> from numpy import *
>>> a = 1 # 0-d array
>>> b = array([2,3]) # 1-d array
>>> c = array([[4,5],[6,7]]) # 2-d array
>>> d = arange(8).reshape(2,2,2) # 3-d array
>>> d
array([[[0, 1],
[2, 3]],
[[4, 5],
[6, 7]]])
>>> atleast_1d(a,b,c,d) # all output arrays have dim >= 1
[array([1]), array([2, 3]), array([[4, 5],
[6, 7]]), array([[[0, 1],
[2, 3]],
[[4, 5],
[6, 7]]])]
See also: atleast_2d, atleast_3d, newaxis, expand_dims
atleast_2d()
numpy.atleast_2d(*arys)
View inputs as arrays with at least two dimensions.
Parameters
----------
array1, array2, ... : array_like
One or more array-like sequences. Non-array inputs are converted
to arrays. Arrays that already have two or more dimensions are
preserved.
Returns
-------
res, res2, ... : ndarray
An array, or tuple of arrays, each with ``a.ndim >= 2``.
Copies are avoided where possible, and views with two or more
dimensions are returned.
See Also
--------
atleast_1d, atleast_3d
Examples
--------
>>> numpy.atleast_2d(3.0)
array([[ 3.]])
>>> x = numpy.arange(3.0)
>>> numpy.atleast_2d(x)
array([[ 0., 1., 2.]])
>>> numpy.atleast_2d(x).base is x
True
>>> np.atleast_2d(1, [1, 2], [[1, 2]])
[array([[1]]), array([[1, 2]]), array([[1, 2]])]
>>> from numpy import *
>>> a = 1 # 0-d array
>>> b = array([2,3]) # 1-d array
>>> c = array([[4,5],[6,7]]) # 2-d array
>>> d = arange(8).reshape(2,2,2) # 3-d array
>>> d
array([[[0, 1],
[2, 3]],
[[4, 5],
[6, 7]]])
>>> atleast_2d(a,b,c,d) # all output arrays have dim >= 2
[array([[1]]), array([[2, 3]]), array([[4, 5],
[6, 7]]), array([[[0, 1],
[2, 3]],
[[4, 5],
[6, 7]]])]
See also: atleast_1d, atleast_3d, newaxis, expand_dims
atleast_3d()
numpy.atleast_3d(*arys)
View inputs as arrays with at least three dimensions.
Parameters
----------
array1, array2, ... : array_like
One or more array-like sequences. Non-array inputs are converted
to arrays. Arrays that already have three or more dimensions are
preserved.
Returns
-------
res1, res2, ... : ndarray
An array, or tuple of arrays, each with ``a.ndim >= 3``.
Copies are avoided where possible, and views with three or more
dimensions are returned. For example, a one-dimensional array of
shape ``N`` becomes a view of shape ``(1, N, 1)``. An ``(M, N)``
array becomes a view of shape ``(N, M, 1)``.
See Also
--------
numpy.atleast_1d, numpy.atleast_2d
Examples
--------
>>> numpy.atleast_3d(3.0)
array([[[ 3.]]])
>>> x = numpy.arange(3.0)
>>> numpy.atleast_3d(x).shape
(1, 3, 1)
>>> x = numpy.arange(12.0).reshape(4,3)
>>> numpy.atleast_3d(x).shape
(4, 3, 1)
>>> numpy.atleast_3d(x).base is x
True
>>> for arr in np.atleast_3d(1, [1, 2], [[1, 2]]): print arr, "\n"
...
[[[1]]]
[[[1]
[2]]]
[[[1]
[2]]]
>>> from numpy import *
>>> a = 1 # 0-d array
>>> b = array([2,3]) # 1-d array
>>> c = array([[4,5],[6,7]]) # 2-d array
>>> d = arange(8).reshape(2,2,2) # 3-d array
>>> d
array([[[0, 1],
[2, 3]],
[[4, 5],
[6, 7]]])
>>> atleast_3d(a,b,c,d) # all output arrays have dim >= 3
[array([[[1]]]), array([[[2],
[3]]]), array([[[4],
[5]],
[[6],
[7]]]), array([[[0, 1],
[2, 3]],
[[4, 5],
[6, 7]]])]
See also: atleast_1d, atleast_2d, newaxis, expand_dims
average()
numpy.average(a, axis=None, weights=None, returned=False)
Return the weighted average of array over the specified axis.
Parameters
----------
a : array_like
Data to be averaged.
axis : int, optional
Axis along which to average `a`. If `None`, averaging is done over the
entire array irrespective of its shape.
weights : array_like, optional
The importance that each datum has in the computation of the average.
The weights array can either be 1-D (in which case its length must be
the size of `a` along the given axis) or of the same shape as `a`.
If `weights=None`, then all data in `a` are assumed to have a
weight equal to one.
returned : bool, optional
Default is `False`. If `True`, the tuple (`average`, `sum_of_weights`)
is returned, otherwise only the average is returned. Note that
if `weights=None`, `sum_of_weights` is equivalent to the number of
elements over which the average is taken.
Returns
-------
average, [sum_of_weights] : {array_type, double}
Return the average along the specified axis. When returned is `True`,
return a tuple with the average as the first element and the sum
of the weights as the second element. The return type is `Float`
if `a` is of integer type, otherwise it is of the same type as `a`.
`sum_of_weights` is of the same type as `average`.
Raises
------
ZeroDivisionError
When all weights along axis are zero. See `numpy.ma.average` for a
version robust to this type of error.
TypeError
When the length of 1D `weights` is not the same as the shape of `a`
along axis.
See Also
--------
ma.average : average for masked arrays
Examples
--------
>>> data = range(1,5)
>>> data
[1, 2, 3, 4]
>>> np.average(data)
2.5
>>> np.average(range(1,11), weights=range(10,0,-1))
4.0
>>> from numpy import *
>>> a = array([1,2,3,4,5])
>>> w = array([0.1, 0.2, 0.5, 0.2, 0.2]) # weights, not necessarily normalized
>>> average(a) # plain mean value
3.0
>>> average(a,weights=w) # weighted average
3.1666666666666665
>>> average(a,weights=w,returned=True) # output = weighted average, sum of weights
(3.1666666666666665, 1.2)
bartlett()
numpy.bartlett(M)
Return the Bartlett window.
The Bartlett window is very similar to a triangular window, except
that the end points are at zero. It is often used in signal
processing for tapering a signal, without generating too much
ripple in the frequency domain.
Parameters
----------
M : int
Number of points in the output window. If zero or less, an
empty array is returned.
Returns
-------
out : array
The triangular window, normalized to one (the value one
appears only if the number of samples is odd), with the first
and last samples equal to zero.
See Also
--------
blackman, hamming, hanning, kaiser
Notes
-----
The Bartlett window is defined as
.. math:: w(n) = \frac{2}{M-1} \left(
\frac{M-1}{2} - \left|n - \frac{M-1}{2}\right|
\right)
Most references to the Bartlett window come from the signal
processing literature, where it is used as one of many windowing
functions for smoothing values. Note that convolution with this
window produces linear interpolation. It is also known as an
apodization (which means"removing the foot", i.e. smoothing
discontinuities at the beginning and end of the sampled signal) or
tapering function. The fourier transform of the Bartlett is the product
of two sinc functions.
Note the excellent discussion in Kanasewich.
References
----------
.. [1] M.S. Bartlett, "Periodogram Analysis and Continuous Spectra",
Biometrika 37, 1-16, 1950.
.. [2] E.R. Kanasewich, "Time Sequence Analysis in Geophysics",
The University of Alberta Press, 1975, pp. 109-110.
.. [3] A.V. Oppenheim and R.W. Schafer, "Discrete-Time Signal
Processing", Prentice-Hall, 1999, pp. 468-471.
.. [4] Wikipedia, "Window function",
http://en.wikipedia.org/wiki/Window_function
.. [5] W.H. Press, B.P. Flannery, S.A. Teukolsky, and W.T. Vetterling,
"Numerical Recipes", Cambridge University Press, 1986, page 429.
Examples
--------
>>> np.bartlett(12)
array([ 0. , 0.18181818, 0.36363636, 0.54545455, 0.72727273,
0.90909091, 0.90909091, 0.72727273, 0.54545455, 0.36363636,
0.18181818, 0. ])
Plot the window and its frequency response (requires SciPy and matplotlib):
>>> from numpy import clip, log10, array, bartlett
>>> from numpy.fft import fft
>>> import matplotlib.pyplot as plt
>>> window = bartlett(51)
>>> plt.plot(window)
>>> plt.title("Bartlett window")
>>> plt.ylabel("Amplitude")
>>> plt.xlabel("Sample")
>>> plt.show()
>>> A = fft(window, 2048) / 25.5
>>> mag = abs(fftshift(A))
>>> freq = linspace(-0.5,0.5,len(A))
>>> response = 20*log10(mag)
>>> response = clip(response,-100,100)
>>> plt.plot(freq, response)
>>> plt.title("Frequency response of Bartlett window")
>>> plt.ylabel("Magnitude [dB]")
>>> plt.xlabel("Normalized frequency [cycles per sample]")
>>> plt.axis('tight'); plt.show()
base_repr()
numpy.base_repr(number, base=2, padding=0)
Return a string representation of a number in the given base system.
Parameters
----------
number : scalar
The value to convert. Only positive values are handled.
base : int
Convert `number` to the `base` number system. The valid range is 2-36,
the default value is 2.
padding : int, optional
Number of zeros padded on the left.
Returns
-------
out : str
String representation of `number` in `base` system.
See Also
--------
binary_repr : Faster version of `base_repr` for base 2 that also handles
negative numbers.
Examples
--------
>>> np.base_repr(3, 5)
'3'
>>> np.base_repr(6, 5)
'11'
>>> np.base_repr(7, 5, padding=3)
'00012'
bench()
numpy.bench(self, label='fast', verbose=1, extra_argv=None)
Run benchmarks for module using nose
Parameters
----------
label : {'fast', 'full', '', attribute identifer}
Identifies the benchmarks to run. This can be a string to
pass to the nosetests executable with the '-A' option, or one of
several special values.
Special values are:
'fast' - the default - which corresponds to nosetests -A option
of 'not slow'.
'full' - fast (as above) and slow benchmarks as in the
no -A option to nosetests - same as ''
None or '' - run all benchmarks
attribute_identifier - string passed directly to nosetests as '-A'
verbose : integer
verbosity value for test outputs, 1-10
extra_argv : list
List with any extra args to pass to nosetests
beta()
numpy.random.beta(...)
beta(a, b, size=None)
The Beta distribution over ``[0, 1]``.
The Beta distribution is a special case of the Dirichlet distribution,
and is related to the Gamma distribution. It has the probability
distribution function
.. math:: f(x; a,b) = \frac{1}{B(\alpha, \beta)} x^{\alpha - 1}
(1 - x)^{\beta - 1},
where the normalisation, B, is the beta function,
.. math:: B(\alpha, \beta) = \int_0^1 t^{\alpha - 1}
(1 - t)^{\beta - 1} dt.
It is often seen in Bayesian inference and order statistics.
Parameters
----------
a : float
Alpha, non-negative.
b : float
Beta, non-negative.
size : tuple of ints, optional
The number of samples to draw. The ouput is packed according to
the size given.
Returns
-------
out : ndarray
Array of the given shape, containing values drawn from a
Beta distribution.
>>> from numpy import *
>>> from numpy.random import *
>>> beta(a=1,b=10,size=(2,2)) # Beta distribution alpha=1, beta=10
array([[ 0.02571091, 0.04973536],
[ 0.04887027, 0.02382052]])
See also: seed
binary_repr()
numpy.binary_repr(num, width=None)
Return the binary representation of the input number as a string.
For negative numbers, if width is not given, a minus sign is added to the
front. If width is given, the two's complement of the number is
returned, with respect to that width.
In a two's-complement system negative numbers are represented by the two's
complement of the absolute value. This is the most common method of
representing signed integers on computers [1]_. A N-bit two's-complement
system can represent every integer in the range
:math:`-2^{N-1}` to :math:`+2^{N-1}-1`.
Parameters
----------
num : int
Only an integer decimal number can be used.
width : int, optional
The length of the returned string if `num` is positive, the length of
the two's complement if `num` is negative.
Returns
-------
bin : str
Binary representation of `num` or two's complement of `num`.
See Also
--------
base_repr
Notes
-----
`binary_repr` is equivalent to using `base_repr` with base 2, but about 25x
faster.
References
----------
.. [1] Wikipedia, "Two's complement",
http://en.wikipedia.org/wiki/Two's_complement
Examples
--------
>>> np.binary_repr(3)
'11'
>>> np.binary_repr(-3)
'-11'
>>> np.binary_repr(3, width=4)
'0011'
The two's complement is returned when the input number is negative and
width is specified:
>>> np.binary_repr(-3, width=4)
'1101'
>>> from numpy import *
>>> a = 25
>>> binary_repr(a) # binary representation of 25
'11001'
>>> b = float_(pi) # numpy float has extra functionality ...
>>> b.nbytes # ... like the number of bytes it takes
8
>>> binary_repr(b.view('u8')) # view float number as an 8 byte integer, then get binary bitstring
'1010100010001000010110100011000'
bincount()
numpy.bincount(...)
bincount(x,weights=None) Return the number of occurrences of each value in x. x must be a list of non-negative integers. The output, b[i], represents the number of times that i is found in x. If weights is specified, every occurrence of i at a position p contributes weights[p] instead of 1. See also: histogram, digitize, unique.
>>> from numpy import *
>>> a = array([1,1,1,1,2,2,4,4,5,6,6,6]) # doesn't need to be sorted
>>> bincount(a) # 0 occurs 0 times, 1 occurs 4 times, 2 occurs twice, 3 occurs 0 times, ...
array([0, 4, 2, 0, 2, 1, 3])
>>> a = array([5,4,4,2,2])
>>> w = array([0.1, 0.2, 0.1, 0.3, 0.5])
>>> bincount(a) # 0 & 1 don't occur, 2 occurs twice, 3 doesn't occur, 4 occurs twice, 5 once
array([0, 0, 2, 0, 2, 1])
>>> bincount(a, weights=w)
array([ 0. , 0. , 0.8, 0. , 0.3, 0.1])
>>> # 0 occurs 0 times -> result[0] = 0
>>> # 1 occurs 0 times -> result[1] = 0
>>> # 2 occurs at indices 3 & 4 -> result[2] = w[3] + w[4]
>>> # 3 occurs 0 times -> result[3] = 0
>>> # 4 occurs at indices 1 & 2 -> result[4] = w[1] + w[2]
>>> # 5 occurs at index 0 -> result[5] = w[0]
binomial()
numpy.random.binomial(...)
binomial(n, p, size=None)
Draw samples from a binomial distribution.
Samples are drawn from a Binomial distribution with specified
parameters, n trials and p probability of success where
n an integer > 0 and p is in the interval [0,1]. (n may be
input as a float, but it is truncated to an integer in use)
Parameters
----------
n : float (but truncated to an integer)
parameter, > 0.
p : float
parameter, >= 0 and <=1.
size : {tuple, int}
Output shape. If the given shape is, e.g., ``(m, n, k)``, then
``m * n * k`` samples are drawn.
Returns
-------
samples : {ndarray, scalar}
where the values are all integers in [0, n].
See Also
--------
scipy.stats.distributions.binom : probability density function,
distribution or cumulative density function, etc.
Notes
-----
The probability density for the Binomial distribution is
.. math:: P(N) = \binom{n}{N}p^N(1-p)^{n-N},
where :math:`n` is the number of trials, :math:`p` is the probability
of success, and :math:`N` is the number of successes.
When estimating the standard error of a proportion in a population by
using a random sample, the normal distribution works well unless the
product p*n <=5, where p = population proportion estimate, and n =
number of samples, in which case the binomial distribution is used
instead. For example, a sample of 15 people shows 4 who are left
handed, and 11 who are right handed. Then p = 4/15 = 27%. 0.27*15 = 4,
so the binomial distribution should be used in this case.
References
----------
.. [1] Dalgaard, Peter, "Introductory Statistics with R",
Springer-Verlag, 2002.
.. [2] Glantz, Stanton A. "Primer of Biostatistics.", McGraw-Hill,
Fifth Edition, 2002.
.. [3] Lentner, Marvin, "Elementary Applied Statistics", Bogden
and Quigley, 1972.
.. [4] Weisstein, Eric W. "Binomial Distribution." From MathWorld--A
Wolfram Web Resource.
http://mathworld.wolfram.com/BinomialDistribution.html
.. [5] Wikipedia, "Binomial-distribution",
http://en.wikipedia.org/wiki/Binomial_distribution
Examples
--------
Draw samples from the distribution:
>>> n, p = 10, .5 # number of trials, probability of each trial
>>> s = np.random.binomial(n, p, 1000)
# result of flipping a coin 10 times, tested 1000 times.
A real world example. A company drills 9 wild-cat oil exploration
wells, each with an estimated probability of success of 0.1. All nine
wells fail. What is the probability of that happening?
Let's do 20,000 trials of the model, and count the number that
generate zero positive results.
>>> sum(np.random.binomial(9,0.1,20000)==0)/20000.
answer = 0.38885, or 38%.
>>> from numpy import *
>>> from numpy.random import *
>>> binomial(n=100,p=0.5,size=(2,3)) # binomial distribution n trials, p= success probability
array([[38, 50, 53],
[56, 48, 54]])
>>> from pylab import * # histogram plot example
>>> hist(binomial(100,0.5,(1000)), 20)
See also: random_sample, uniform, standard_normal, seed
bitwise_and()
numpy.bitwise_and(...)
y = bitwise_and(x1,x2)
Compute bit-wise AND of two arrays, element-wise.
When calculating the bit-wise AND between two elements, ``x`` and ``y``,
each element is first converted to its binary representation (which works
just like the decimal system, only now we're using 2 instead of 10):
.. math:: x = \sum_{i=0}^{W-1} a_i \cdot 2^i\\
y = \sum_{i=0}^{W-1} b_i \cdot 2^i,
where ``W`` is the bit-width of the type (i.e., 8 for a byte or uint8),
and each :math:`a_i` and :math:`b_j` is either 0 or 1. For example, 13
is represented as ``00001101``, which translates to
:math:`2^4 + 2^3 + 2`.
The bit-wise operator is the result of
.. math:: z = \sum_{i=0}^{i=W-1} (a_i \wedge b_i) \cdot 2^i,
where :math:`\wedge` is the AND operator, which yields one whenever
both :math:`a_i` and :math:`b_i` are 1.
Parameters
----------
x1, x2 : array_like
Only integer types are handled (including booleans).
Returns
-------
out : array_like
Result.
See Also
--------
bitwise_or, bitwise_xor
logical_and
binary_repr :
Return the binary representation of the input number as a string.
Examples
--------
We've seen that 13 is represented by ``00001101``. Similary, 17 is
represented by ``00010001``. The bit-wise AND of 13 and 17 is
therefore ``000000001``, or 1:
>>> np.bitwise_and(13, 17)
1
>>> np.bitwise_and(14, 13)
12
>>> np.binary_repr(12)
'1100'
>>> np.bitwise_and([14,3], 13)
array([12, 1])
>>> np.bitwise_and([11,7], [4,25])
array([0, 1])
>>> np.bitwise_and(np.array([2,5,255]), np.array([3,14,16]))
array([ 2, 4, 16])
>>> np.bitwise_and([True, True], [False, True])
array([False, True], dtype=bool)
>>> from numpy import *
>>> bitwise_and(array([2,5,255]), array([4,4,4]))
array([0, 4, 4])
>>> bitwise_and(array([2,5,255,2147483647L],dtype=int32), array([4,4,4,2147483647L],dtype=int32))
array([ 0, 4, 4, 2147483647])
See also: bitwise_or, bitwise_xor, logical_and
bitwise_not()
numpy.bitwise_not(...)
y = invert(x)
Compute bit-wise inversion, or bit-wise NOT, element-wise.
When calculating the bit-wise NOT of an element ``x``, each element is
first converted to its binary representation (which works
just like the decimal system, only now we're using 2 instead of 10):
.. math:: x = \sum_{i=0}^{W-1} a_i \cdot 2^i
where ``W`` is the bit-width of the type (i.e., 8 for a byte or uint8),
and each :math:`a_i` is either 0 or 1. For example, 13 is represented
as ``00001101``, which translates to :math:`2^4 + 2^3 + 2`.
The bit-wise operator is the result of
.. math:: z = \sum_{i=0}^{i=W-1} (\lnot a_i) \cdot 2^i,
where :math:`\lnot` is the NOT operator, which yields 1 whenever
:math:`a_i` is 0 and yields 0 whenever :math:`a_i` is 1.
For signed integer inputs, the two's complement is returned.
In a two's-complement system negative numbers are represented by the two's
complement of the absolute value. This is the most common method of
representing signed integers on computers [1]_. A N-bit two's-complement
system can represent every integer in the range
:math:`-2^{N-1}` to :math:`+2^{N-1}-1`.
Parameters
----------
x1 : ndarray
Only integer types are handled (including booleans).
Returns
-------
out : ndarray
Result.
See Also
--------
bitwise_and, bitwise_or, bitwise_xor
logical_not
binary_repr :
Return the binary representation of the input number as a string.
Notes
-----
`bitwise_not` is an alias for `invert`:
>>> np.bitwise_not is np.invert
True
References
----------
.. [1] Wikipedia, "Two's complement",
http://en.wikipedia.org/wiki/Two's_complement
Examples
--------
We've seen that 13 is represented by ``00001101``.
The invert or bit-wise NOT of 13 is then:
>>> np.invert(np.array([13], dtype=uint8))
array([242], dtype=uint8)
>>> np.binary_repr(x, width=8)
'00001101'
>>> np.binary_repr(242, width=8)
'11110010'
The result depends on the bit-width:
>>> np.invert(np.array([13], dtype=uint16))
array([65522], dtype=uint16)
>>> np.binary_repr(x, width=16)
'0000000000001101'
>>> np.binary_repr(65522, width=16)
'1111111111110010'
When using signed integer types the result is the two's complement of
the result for the unsigned type:
>>> np.invert(np.array([13], dtype=int8))
array([-14], dtype=int8)
>>> np.binary_repr(-14, width=8)
'11110010'
Booleans are accepted as well:
>>> np.invert(array([True, False]))
array([False, True], dtype=bool)
bitwise_or()
numpy.bitwise_or(...)
y = bitwise_or(x1,x2)
Compute bit-wise OR of two arrays, element-wise.
When calculating the bit-wise OR between two elements, ``x`` and ``y``,
each element is first converted to its binary representation (which works
just like the decimal system, only now we're using 2 instead of 10):
.. math:: x = \sum_{i=0}^{W-1} a_i \cdot 2^i\\
y = \sum_{i=0}^{W-1} b_i \cdot 2^i,
where ``W`` is the bit-width of the type (i.e., 8 for a byte or uint8),
and each :math:`a_i` and :math:`b_j` is either 0 or 1. For example, 13
is represented as ``00001101``, which translates to
:math:`2^4 + 2^3 + 2`.
The bit-wise operator is the result of
.. math:: z = \sum_{i=0}^{i=W-1} (a_i \vee b_i) \cdot 2^i,
where :math:`\vee` is the OR operator, which yields one whenever
either :math:`a_i` or :math:`b_i` is 1.
Parameters
----------
x1, x2 : array_like
Only integer types are handled (including booleans).
Returns
-------
out : array_like
Result.
See Also
--------
bitwise_and, bitwise_xor
logical_or
binary_repr :
Return the binary representation of the input number as a string.
Examples
--------
We've seen that 13 is represented by ``00001101``. Similary, 16 is
represented by ``00010000``. The bit-wise OR of 13 and 16 is
therefore ``000111011``, or 29:
>>> np.bitwise_or(13, 16)
29
>>> np.binary_repr(29)
'11101'
>>> np.bitwise_or(32, 2)
34
>>> np.bitwise_or([33, 4], 1)
array([33, 5])
>>> np.bitwise_or([33, 4], [1, 2])
array([33, 6])
>>> np.bitwise_or(np.array([2, 5, 255]), np.array([4, 4, 4]))
array([ 6, 5, 255])
>>> np.bitwise_or(np.array([2, 5, 255, 2147483647L], dtype=np.int32),
... np.array([4, 4, 4, 2147483647L], dtype=np.int32))
array([ 6, 5, 255, 2147483647])
>>> np.bitwise_or([True, True], [False, True])
array([ True, True], dtype=bool)
>>> from numpy import *
>>> bitwise_or(array([2,5,255]), array([4,4,4]))
array([ 6, 5, 255])
>>> bitwise_or(array([2,5,255,2147483647L],dtype=int32), array([4,4,4,2147483647L],dtype=int32))
array([ 6, 5, 255, 2147483647])
See also: bitwise_and, bitwise_xor, logical_or
bitwise_xor()
numpy.bitwise_xor(...)
y = bitwise_xor(x1,x2)
Compute bit-wise XOR of two arrays, element-wise.
When calculating the bit-wise XOR between two elements, ``x`` and ``y``,
each element is first converted to its binary representation (which works
just like the decimal system, only now we're using 2 instead of 10):
.. math:: x = \sum_{i=0}^{W-1} a_i \cdot 2^i\\
y = \sum_{i=0}^{W-1} b_i \cdot 2^i,
where ``W`` is the bit-width of the type (i.e., 8 for a byte or uint8),
and each :math:`a_i` and :math:`b_j` is either 0 or 1. For example, 13
is represented as ``00001101``, which translates to
:math:`2^4 + 2^3 + 2`.
The bit-wise operator is the result of
.. math:: z = \sum_{i=0}^{i=W-1} (a_i \oplus b_i) \cdot 2^i,
where :math:`\oplus` is the XOR operator, which yields one whenever
either :math:`a_i` or :math:`b_i` is 1, but not both.
Parameters
----------
x1, x2 : array_like
Only integer types are handled (including booleans).
Returns
-------
out : ndarray
Result.
See Also
--------
bitwise_and, bitwise_or
logical_xor
binary_repr :
Return the binary representation of the input number as a string.
Examples
--------
We've seen that 13 is represented by ``00001101``. Similary, 17 is
represented by ``00010001``. The bit-wise XOR of 13 and 17 is
therefore ``00011100``, or 28:
>>> np.bitwise_xor(13, 17)
28
>>> np.binary_repr(28)
'11100'
>>> np.bitwise_xor(31, 5)
26
>>> np.bitwise_xor([31,3], 5)
array([26, 6])
>>> np.bitwise_xor([31,3], [5,6])
array([26, 5])
>>> np.bitwise_xor([True, True], [False, True])
array([ True, False], dtype=bool)
>>> from numpy import *
>>> bitwise_xor(array([2,5,255]), array([4,4,4]))
array([ 6, 1, 251])
>>> bitwise_xor(array([2,5,255,2147483647L],dtype=int32), array([4,4,4,2147483647L],dtype=int32))
array([ 6, 1, 251, 0])
See also: bitwise_and, bitwise_or, logical_xor
blackman()
numpy.blackman(M)
Return the Blackman window.
The Blackman window is a taper formed by using the the first
three terms of a summation of cosines. It was designed to have close
to the minimal leakage possible.
It is close to optimal, only slightly worse than a Kaiser window.
Parameters
----------
M : int
Number of points in the output window. If zero or less, an
empty array is returned.
Returns
-------
out : array
The window, normalized to one (the value one
appears only if the number of samples is odd).
See Also
--------
bartlett, hamming, hanning, kaiser
Notes
-----
The Blackman window is defined as
.. math:: w(n) = 0.42 - 0.5 \cos(2\pi n/M) + 0.08 \cos(4\pi n/M)
Most references to the Blackman window come from the signal processing
literature, where it is used as one of many windowing functions for
smoothing values. It is also known as an apodization (which means
"removing the foot", i.e. smoothing discontinuities at the beginning
and end of the sampled signal) or tapering function. It is known as a
"near optimal" tapering function, almost as good (by some measures)
as the kaiser window.
References
----------
.. [1] Blackman, R.B. and Tukey, J.W., (1958) The measurement of power
spectra, Dover Publications, New York.
.. [2] Wikipedia, "Window function",
http://en.wikipedia.org/wiki/Window_function
.. [3] Oppenheim, A.V., and R.W. Schafer. Discrete-Time Signal Processing.
Upper Saddle River, NJ: Prentice-Hall, 1999, pp. 468-471.
Examples
--------
>>> from numpy import blackman
>>> blackman(12)
array([ -1.38777878e-17, 3.26064346e-02, 1.59903635e-01,
4.14397981e-01, 7.36045180e-01, 9.67046769e-01,
9.67046769e-01, 7.36045180e-01, 4.14397981e-01,
1.59903635e-01, 3.26064346e-02, -1.38777878e-17])
Plot the window and the frequency response:
>>> from numpy import clip, log10, array, bartlett
>>> from scipy.fftpack import fft, fftshift
>>> import matplotlib.pyplot as plt
>>> window = blackman(51)
>>> plt.plot(window)
>>> plt.title("Blackman window")
>>> plt.ylabel("Amplitude")
>>> plt.xlabel("Sample")
>>> plt.show()
>>> A = fft(window, 2048) / 25.5
>>> mag = abs(fftshift(A))
>>> freq = linspace(-0.5,0.5,len(A))
>>> response = 20*log10(mag)
>>> response = clip(response,-100,100)
>>> plt.plot(freq, response)
>>> plt.title("Frequency response of Bartlett window")
>>> plt.ylabel("Magnitude [dB]")
>>> plt.xlabel("Normalized frequency [cycles per sample]")
>>> plt.axis('tight'); plt.show()
bmat()
numpy.bmat(obj, ldict=None, gdict=None)
Build a matrix object from a string, nested sequence, or array.
Parameters
----------
obj : string, sequence or array
Input data. Variables names in the current scope may
be referenced, even if `obj` is a string.
Returns
-------
out : matrix
Returns a matrix object, which is a specialized 2-D array.
See Also
--------
matrix
Examples
--------
>>> A = np.mat('1 1; 1 1')
>>> B = np.mat('2 2; 2 2')
>>> C = np.mat('3 4; 5 6')
>>> D = np.mat('7 8; 9 0')
All the following expressions construct the same block matrix:
>>> np.bmat([[A, B], [C, D]])
matrix([[1, 1, 2, 2],
[1, 1, 2, 2],
[3, 4, 7, 8],
[5, 6, 9, 0]])
>>> np.bmat(np.r_[np.c_[A, B], np.c_[C, D]])
matrix([[1, 1, 2, 2],
[1, 1, 2, 2],
[3, 4, 7, 8],
[5, 6, 9, 0]])
>>> np.bmat('A,B; C,D')
matrix([[1, 1, 2, 2],
[1, 1, 2, 2],
[3, 4, 7, 8],
[5, 6, 9, 0]])
>>> from numpy import *
>>> a = mat('1 2; 3 4')
>>> b = mat('5 6; 7 8')
>>> bmat('a b; b a') # all elements must be existing symbols
matrix([[1, 2, 5, 6],
[3, 4, 7, 8],
[5, 6, 1, 2],
[7, 8, 3, 4]])
See also: mat
broadcast()
numpy.broadcast(...)
>>> from numpy import *
>>> a = array([[1,2],[3,4]])
>>> b = array([5,6])
>>> c = broadcast(a,b)
>>> c.nd # the number of dimensions in the broadcasted result
2
>>> c.shape # the shape of the broadcasted result
(2, 2)
>>> c.size # total size of the broadcasted result
4
>>> for value in c: print value
...
(1, 5)
(2, 6)
(3, 5)
(4, 6)
>>> c.reset() # reset the iterator to the beginning
>>> c.next() # next element
(1, 5)
See also: ndenumerate, ndindex, flat
broadcast_arrays()
numpy.broadcast_arrays(*args)
Broadcast any number of arrays against each other.
Parameters
----------
`*args` : arrays
The arrays to broadcast.
Returns
-------
broadcasted : list of arrays
These arrays are views on the original arrays. They are typically not
contiguous. Furthermore, more than one element of a broadcasted array
may refer to a single memory location. If you need to write to the
arrays, make copies first.
Examples
--------
>>> x = np.array([[1,2,3]])
>>> y = np.array([[1],[2],[3]])
>>> np.broadcast_arrays(x, y)
[array([[1, 2, 3],
[1, 2, 3],
[1, 2, 3]]), array([[1, 1, 1],
[2, 2, 2],
[3, 3, 3]])]
Here is a useful idiom for getting contiguous copies instead of
non-contiguous views.
>>> map(np.array, np.broadcast_arrays(x, y))
[array([[1, 2, 3],
[1, 2, 3],
[1, 2, 3]]), array([[1, 1, 1],
[2, 2, 2],
[3, 3, 3]])]
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)) # string of 5 random bytes
'o\x07\x9f\xdf\xdf'
>>> print repr(bytes(5)) # another string of 5 random bytes
'\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] # for single ranges, c_ works like r_
array([1, 2, 3, 4])
>>> c_[1:5,2:6] # for comma separated values, c_ stacks column-wise
array([[1, 2],
[2, 3],
[3, 4],
[4, 5]])
>>> a = array([[1,2,3],[4,5,6]])
>>> c_[a,a] # concatenation along last (default) axis (column-wise, that's why it's called c_)
array([[1, 2, 3, 1, 2, 3],
[4, 5, 6, 4, 5, 6]])
>>> c_['0',a,a] # concatenation along 1st axis, equivalent to r_[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() # list dtype cast possibilities
<snip>
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) # nearest integers greater-than or equal to 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]) # selector and choice arrays must be equally sized
>>> choice1 =array([20,22,24,26])
>>> choice2 =array([30,32,34,36])
>>> selector = array([0,0,2,1]) # selector can only contain integers in range(number_of_choice_arrays)
>>> selector.choose(choice0,choice1,choice2)
array([10, 12, 34, 26])
>>> a = arange(4)
>>> choose(a >= 2, (choice0, choice1)) # separate function also exists
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) # this syntax also exists
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)) # a,b,c are 1-d arrays with equal length
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] # same effect
array([20, 30])
>>> compress(a >= 30, a) # this form also exists
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) # illustrates the use of the axis keyword
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)) # default is axis=0
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() # .conj() and .conjugate() are the same
array([ 1.-2.j, 3.+4.j])
>>> a.conjugate()
array([ 1.-2.j, 3.+4.j])
>>> conj(a) # is also possible
>>> conjugate(a) # is also possible
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 is a reference to a
>>> b[1] = 4
>>> a
array([1, 4, 3])
>>> a = array([1,2,3])
>>> b = a.copy() # b is now an independent copy of a
>>> 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]) # temperature measurements
>>> P = array([2.7, 8.7, 4.7, 8.2]) # corresponding pressure measurements
>>> print corrcoef([T,P]) # correlation matrix of temperature and pressure
[[ 1. 0.98062258]
[ 0.98062258 1. ]]
>>> rho = array([8.5, 5.2, 6.9, 6.5]) # corresponding density measurements
>>> data = column_stack([T,P,rho])
>>> print corrcoef([T,P,rho]) # correlation matrix of T,P and rho
[[ 1. 0.98062258 -0.97090288]
[ 0.98062258 1. -0.91538464]
[-0.97090288 -0.91538464 1. ]]
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) # normalized by N-1
>>> variance = cov(x, bias=1) # normalized by N
>>> T = array([1.3, 4.5, 2.8, 3.9]) # temperature measurements
>>> P = array([2.7, 8.7, 4.7, 8.2]) # corresponding pressure measurements
>>> cov(T,P) # covariance between temperature and pressure
3.9541666666666657
>>> rho = array([8.5, 5.2, 6.9, 6.5]) # corresponding density measurements
>>> data = column_stack([T,P,rho])
>>> print cov(data) # covariance matrix of T,P and rho
[[ 1.97583333 3.95416667 -1.85583333]
[ 3.95416667 8.22916667 -3.57083333]
[-1.85583333 -3.57083333 1.84916667]]
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) # vector cross-product
array([-3, 6, -3])
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() # total product 1*2*3 = 6, and intermediate results 1, 1*2
array([1, 2, 6])
>>> cumprod(a) # also exists
array([1, 2, 6])
>>> a = array([[1,2,3],[4,5,6]])
>>> a.cumprod(dtype=float) # specify type of output
array([1., 2., 6., 24., 120., 720.])
>>> a.cumprod(axis=0) # for each of the 3 columns: product and intermediate results
array([[ 1, 2, 3],
[ 4, 10, 18]])
>>> a.cumprod(axis=1) # for each of the two rows: product and intermediate results
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]) # cumulative sum = intermediate summing results & total sum
>>> a.cumsum()
array([1, 3, 6])
>>> cumsum(a) # also exists
array([1, 3, 6])
>>> a = array([[1,2,3],[4,5,6]])
>>> a.cumsum(dtype=float) # specifies type of output value(s)
array([ 1., 3., 6., 10., 15., 21.])
>>> a.cumsum(axis=0) # sum over rows for each of the 3 columns
array([[1, 2, 3],
[5, 7, 9]])
>>> a.cumsum(axis=1) # sum over columns for each of the 2 rows
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]) # remove a[2] and a[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) # remove rows 1 and 2
array([[ 0, 1, 2, 3],
[12, 13, 14, 15]])
>>> delete(a, s_[1:3], axis=1) # remove columns 1 and 2
array([[ 0, 3],
[ 4, 7],
[ 8, 11],
[12, 15]])
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) # flatten x, then put elements on diagonal
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) # Also this form exists
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) # 1st-order differences between the elements of x
array([ 1, 2, 6, -4, 5])
>>> diff(x,n=2) # 2nd-order differences, equivalent to diff(diff(x))
array([ 1, 4, -10, 9])
>>> x = array([[1,3,6,10],[0,5,6,8]])
>>> diff(x) # 1st-order differences between the columns (default: axis=-1)
array([[2, 3, 4],
[5, 1, 2]])
>>> diff(x,axis=0) # 1st-order difference between the rows
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]) # monotonically increasing
>>> d = digitize(x,bins) # in which bin falls each value of x?
>>> 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
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) # matrix multiplication (2,3) x (3,2) -> (2,2)
array([[22, 28],
[49, 64]])
>>>
>>> import numpy
>>> if id(dot) == id(numpy.core.multiarray.dot): # A way to know if you use fast blas/lapack or not.
... 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 # stacking in depth: for k in (0,..,3): b[:,:,k] = a
(2, 2, 4)
>>> c = dsplit(b,2) # split, depth-wise, in 2 equal parts
>>> print c[0].shape, c[1].shape # for k in (0,1): c[0][:,:,k] = a and c[1][:,:,k] = a
(2, 2, 2) (2, 2, 2)
>>> d = dsplit(b,[1,2]) # split before [:,:,1] and before [:,:,2]
>>> print d[0].shape, d[1].shape, d[2].shape # for any of the parts: d[.][:,:,k] = a
(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]]) # shapes of a and b can only differ in the 3rd dimension (if present)
>>> b = array([[5,6],[7,8]])
>>> dstack((a,b)) # stack arrays along a third axis (depth wise)
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') # using array-scalar type
dtype('int16')
>>> dtype([('f1', 'int16')]) # record, 1 field named 'f1', containing int16
dtype([('f1', '<i2')])
>>> dtype([('f1', [('f1', 'int16')])]) # record, 1 field named 'f1' containing a record that has 1 field.
dtype([('f1', [('f1', '<i2')])])
>>> dtype([('f1', 'uint'), ('f2', 'int32')]) # record with 2 fields: field 1 contains an unsigned int, 2nd field an int32
dtype([('f1', '<u4'), ('f2', '<i4')])
>>> dtype([('a','f8'),('b','S10')]) # using array-protocol type strings
dtype([('a', '<f8'), ('b', '|S10')])
>>> dtype("i4, (2,3)f8") # using comma-separated field formats. (2,3) is the shape
dtype([('f0', '<i4'), ('f1', '<f8', (2, 3))])
>>> dtype([('hello',('int',3)),('world','void',10)]) # using tuples. int is fixed-type: 3 is shape; void is flex-type: 10 is size.
dtype([('hello', '<i4', 3), ('world', '|V10')])
>>> dtype(('int16', {'x':('int8',0), 'y':('int8',1)})) # subdivide int16 in 2 int8, called x and y. 0 and 1 are the offsets in bytes
dtype(('<i2', [('x', '|i1'), ('y', '|i1')]))
>>> dtype({'names':['gender','age'], 'formats':['S1',uint8]}) # using dictionaries. 2 fields named 'gender' and 'age'
dtype([('gender', '|S1'), ('age', '|u1')])
>>> dtype({'surname':('S25',0),'age':(uint8,25)}) # 0 and 25 are offsets in bytes
dtype([('surname', '|S25'), ('age', '|u1')])
>>>
>>> a = dtype('int32')
>>> a
dtype('int32')
>>> a.type # type object
<type 'numpy.int32'>
>>> a.kind # character code (one of 'biufcSUV') to identify general type
'i'
>>> a.char # unique char code of each of the 21 built-in types
'l'
>>> a.num # unique number of each of the 21 built-in types
7
>>> a.str # array-protocol typestring
'<i4'
>>> a.name # name of this datatype
'int32'
>>> a.byteorder # '=':native, '<':little endian, '>':big endian, '|':not applicable
'='
>>> a.itemsize # item size in bytes
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 field
... ('nested', [('i', 'i2'),('j','i2')])])
>>> a.fields['nested'] # access nested fields
(dtype([('i', '<i2'), ('j', '<i2')]), 8)
>>> a.fields['nested'][0].fields['i'] # access nested fields
(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) # uninitialized array, size=3, dtype = float
array([ 6.08581638e+000, 3.45845952e-323, 4.94065646e-324])
>>> empty((2,3),int) # uninitialized array, dtype = 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) # uninitialized array with the same shape and datatype as '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) # Equivalent to x[newaxis,:] or x[None] or x[newaxis]
array([[1, 2]])
>>> expand_dims(x,axis=1) # Equivalent to x[:,newaxis]
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
extract()
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) # a 3x4 matrix containing zeros except for the 0th diagonal that contains ones
array([[ 1., 0., 0., 0.],
[ 0., 1., 0., 0.],
[ 0., 0., 1., 0.]])
>>> eye(3,4,1,dtype=float) # a 3x4 matrix containing zeros except for the 1st diagonal that contains ones
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.]) # could also be complex
>>> 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): # equivalent but much slower
... fourier[k] = sum(signal * exp(-1j*2*pi*k*arange(N)/N))
...
>>> timestep = 0.1 # if unit=day -> freq unit=cycles/day
>>> fftfreq(N, d=timestep) # freqs corresponding to 'fourier'
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 # if unit=day -> freq unit=cycles/day
>>> freq = fftfreq(N, d=timestep) # freqs corresponding to 'fourier'
>>> freq
array([ 0. , 1.25, 2.5 , 3.75, -5. , -3.75, -2.5 , -1.25])
>>>
>>> fftshift(freq) # freqs in ascending order
array([-5. , -3.75, -2.5 , -1.25, 0. , 1.25, 2.5 , 3.75])
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 # if unit=day -> freq unit=cycles/day
>>> freq = fftfreq(N, d=timestep) # freqs corresponding to 'fourier'
>>> freq
array([ 0. , 1.25, 2.5 , 3.75, -5. , -3.75, -2.5 , -1.25])
>>>
>>> freq = fftshift(freq) # freqs in ascending order
>>> freq
array([-5. , -3.75, -2.5 , -1.25, 0. , 1.25, 2.5 , 3.75])
>>> fourier = fftshift(fourier) # adjust fourier to new freq order
>>>
>>> freq = ifftshift(freq) # undo previous frequency shift
>>> fourier = ifftshift(fourier) # undo previous fourier shift
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) # replace all elements with the number 7
>>> a
array([7, 7, 7, 7])
>>> a.fill(6.5) # fill value is converted to dtype of a
>>> 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) # the numbers given are machine dependent
>>> f.nmant, f.nexp # nr of bits in the mantissa and in the exponent
(52, 11)
>>> f.machep # most negative n so that 1.0 + 2**n != 1.0
-52
>>> f.eps # floating point precision: 2**machep
array(2.2204460492503131e-16)
>>> f.precision # nr of precise decimal digits: int(-log10(eps))
15
>>> f.resolution # 10**(-precision)
array(1.0000000000000001e-15)
>>> f.negep # most negative n so that 1.0 - 2**n != 1.0
-53
>>> f.epsneg # floating point precision: 2**negep
array(1.1102230246251565e-16)
>>> f.minexp # most negative n so that 2**n gives normal numbers
-1022
>>> f.tiny # smallest usuable floating point nr: 2**minexp
array(2.2250738585072014e-308)
>>> f.maxexp # smallest positive n so that 2**n causes overflow
1024
>>> f.min, f.max # the most negative and most positive usuable floating number
(-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) # round a to nearest integer towards zero
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 # .flat returns an iterator
>>> iter.next() # cycle through array with .next()
10
>>> iter.next()
30
>>> iter.next()
40
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() # b is now a 1-d version of a, a new array, not a reference
>>> print b
[1 2 3 4]
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) # flip left-right
array([[ 2, 1, 0],
[ 5, 4, 3],
[ 8, 7, 6],
[11, 10, 9]])
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) # flip up-down
array([[ 9, 10, 11],
[ 6, 7, 8],
[ 3, 4, 5],
[ 0, 1, 2]])
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.]) # nearest integer smaller-than or equal to a # nearest integers greater-than or equal to a
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']) # datatype is string
>>> y = array(['F','F','M'], dtype='S1') # datatype is a single character
>>> z = array([20,25,23]) # datatype is integer
>>> data = rec.fromarrays([x,y,z], names='surname, gender, age') # convert to record array
>>> data[0]
('Smith', 'F', 20)
>>> data.age # names are available as attributes
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") # binary format
>>> y.tofile("myfile.txt", sep='\n', format = "%e") # ascii format, one column, exponential notation
>>> 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)) # evaluate functiom for all combinations of indices [0,1,2]x[0,1,2]
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]] # List of lists
>>> mydescriptor = {'names': ('weight','age'), 'formats': (float32, int32)} # Descriptor of the data
>>> myiterator = itertools.imap(tuple,mydata) # Clever way of putting list of lists into iterator
# of tuples. E.g.: myiterator.next() == (55.5, 40.)
>>> 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') # Convert to numpy scalar
>>> numpyscalar # Looks like a build-in scalar...
'7'
>>> type(numpyscalar) # ... but it isn't
<type 'numpy.string_'>
>>> buildinscalar = '7' # Build-in python scalar
>>> type(buildinscalar)
<type 'str'>
>>> isinstance(numpyscalar, generic) # Check if scalar is a NumPy one
True
>>> isinstance(buildinscalar, generic) # Example on how to recognize NumPy scalars
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)) # Gumbel distribution location=0.0, scale=1.0
array([[-1.25923601, 1.68758144, 1.76620507],
[ 1.96820048, -0.21219499, 1.83579566]])
>>> from pylab import * # histogram plot example
>>> 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()

