ARRAYS
The identifier 'array' is used as equivalent to the
class 'ndarray' of numpy, and imported by scipy. This is different from the class 'array'
defined in the standard python module 'array'. The latter should never be invoked
when scipy is loaded.
It is assumed that scipy has been imported:
>>>from scipy import *
This also imports from the numpy module.
Sources for this information are the docstrings in scipy, available from
>>>help(´scipy´)
and the python documentation, extended with examples.
The following versions
(August 2006) were used for this documentation:
python2.4.3
numpy1.0b1.
scipy0.5.0
ARRAY OBJECTS
Array objects consist of one or multidimensional homogeneous, fixedsize structures, i.e.,
they have a fixed number of elements all of the same datatype (which allows much faster
methods than Python's list object). An array element
is retrieved as A[i,j,k,..] (list elements are retrieved as L[i][j][k]..). A
matrix
is a twodimensional array.
Arrays a have
attributes
a.attr, which can be distinguished in
properties
and
methods
a.meth(). The former return values (such as the shape and type) that belong to the array;
the latter specify actions that are to be performed on the array. Often there is a
function
that performs the same action as a method; function and method then have the same name.
However,the default settings of the parameters may differ for methods and their
corresponding functions.
Array construction
Arrays can be created in various ways:
 with the function
array(obj), where 'obj' is a (nested)
sequence, e.g. a list [ ] or a tuple ( ). When 'obj' is an array, a
copy
of this array is returned. The function
matrix
does the same for matrices.
 with the function
copy(obj), where 'obj' is another array
or matrix or a (nested) sequence,
 with the function
asarray(obj), which is like 'copy',
except that no copy is made if 'obj' is already an array.
 with the function
empty(shape, dtype)
which produces an uninitialized
array with specified shape and typecode, or with the function
empty_like(a)
which produces an uninitialized array with the same shape and
typecode as its argument a,
 with the function
ones(shape, dtype)
producing
an array initialized with ones, or
ones_like(a).
 with the function
zeros(shape, dtype)
producing
an array initialized with zeros, or
zeros_like(a),
 with the function
identity(n,dtype)
producing a 2d n*n identity matrix,
 with the function
arange(..)
which
does the same as array(range(..)),
 with the function
concatenate(..)
which concatenates sequences to an array.
ARRAY ATTRIBUTES
Here the following attributes (not methods) are listed:
a.dtype
datatype of the elements of a
Examples:
>>> array((1,2)).dtype, array((1.,2.)).dtype, array((1+2j,0+0j)).dtype
(dtype('<i4'), dtype('<f8'), dtype('<c16'))
a.flags
Gives properties:
>>> array([[1,2,3],[4,5,6]]).flags
CONTIGUOUS : True
FORTRAN : False
OWNDATA : True
WRITEABLE : True
ALIGNED : True
UPDATEIFCOPY : False
Corresponding method:
none
a.flat
gives a flattened view (onedim) of a. The array is
not
copied.
Example:
>>> a=array([[1,2,3],[4,5,6]])
>>> for i in range(a.size): print a.flat[i],
1 2 3 4 5 6
a.imag
The array of imaginary values of array a. Works also if a is not complex.
>>> a=array((1., 2.j))
>>> print a
[ 1.+0.j 0.+2.j]
>>> print a.imag
[ 0. 2.]
a.itemsize
gives size in bytes of each array element
Example:
>>> array([[1,2,3],[4,5,6]]).itemsize
4
a.nbytes
Total nr of bytes occupied by a.
a.nbytes = a.size * a.itemsize
Example:
>>> array([[1,2,3],[4,5,6]]).nbytes
24
a.ndim
number of dimensions of a
Example:
>>> array([[1,2,3],[4,5,6]]).ndim
2
Corresponding function:
ndim
a.real
The array of real values of a complex array.
>>> a=array((1., 2.j))
>>> print a
[ 1.+0.j 0.+2.j]
>>> print a.real
[ 1. 0.]
a.shape
Gives the shape of a. The shape is a tuple listing the number of elements along
each dimension. A dimension is called an
axis
. Axis=0 is the outermost bracket,
axis=1,2, .. go successively inward. For a 2dim array or a matrix, axis=0
specifies the rows; axis=1 specifies the columns.
One may also redefine the shape (see example).
Example:
>>> a=array([[1,2,3],[4,5,6]])
>>> a
array([[1, 2, 3],
[4, 5, 6]])
>>> a.shape
(2, 3)
>>> a.shape=(3,2)
>>> print a
[[1 2]
[3 4]
[5 6]]
a.size
Gives the total number of elements in the array.
a.size = product(a.shape)
Example:
>>> array([[1,2,3],[4,5,6]]).size
6
Corresponding function:
size
a.strides
Gives the number of bytes that are skipped (in the contiguous mapping of
the array in memory) when the index is increased by one. For a multidimensional
array there is an index for each axis, and the result is a tuple.
Example:
>>> a=array([[1,2,3],[4,5,6]]).strides
(12, 4)
ARRAY METHODS
Here the following methods are listed:
a.all(axis=None)
Returns True if all elements of a along the specified axis are true.
If axis=None (default) True is returned if all elements of a are true.
>>> a=array([[True,False],[True,True]])
>>> a.all()
False
>>> a.all(0)
array([True, False], dtype=bool)
a.any(axis=None)
Returns True if any element of a along the specified axis is true.
If axis=None (default) True is returned if any element of a is true.
>>> a=array([[True,False],[True,True]])
>>> a.any()
True
>>> a.any(0)
array([True, True], dtype=bool)
a.argmax
Returns the indices to the maximum value of the
1D arrays along the given axis. Axis=None returns the index of the maximum value
in the flattened version of the whole array a.
Example:
>>> a
array([[3, 6, 2],
[5, 1, 4]])
>>> a.argmax(0)
array([1, 0, 1])
>>> a.argmax(1)
array([1, 0])
>>> a.argmax()
1
a.argmin(axis=None)
Returns the indices to the minimum value of the
1D arrays along the given axis. Axis=None returns the index of the minimum value
in the flattened version of the whole array a.
Example:
>>> a
array([[3, 6, 2],
[5, 1, 4]])
>>> a.argmin(0)
array([0, 1, 0])
>>> a.argmin(1)
array([2, 1])
>>> a.argmin()
4
a.argsort(axis=1,kind='quicksort')
Returns array of indexes of the elements along the specified axis, sorted with the specified
kind of sorting routine.
Examples:
>>> a=array([[1,4],[3,2]])
>>> print a
[[1 4]
[3 2]]
>>> print a.argsort()
[[0 1]
[1 0]]
a.astype(t)
Casts array a as type t. Many type names are allowed, such as
bool, int, integer, long, float, complex,
but also int8, int64, '<f8', etc.
Example
>>> array([[1,2],[3,2]]).astype(complex)
array([[ 1.+0.j, 2.+0.j],
[ 3.+0.j, 2.+0.j]])
a.byteswap(False)
Swaps the bytes in the array. Returns the byteswapped array.
If the first argument is TRUE, byteswap inplace and return
a reference to self.
Corresponding function:
None
a.choose(b0, b1, ..., bn)
Returns an array that merges the b_i arrays together using 'a' as the index.
The b_i arrays and 'a' must all be broadcastable to the same shape.
The output at a particular position is the input array b_i at that position
depending on the value of 'a' at that position. Therefore, 'a' must be
an integer array with entries in range(n+1).
Example:
>>> b0=array((1,2))
>>> b1=array((3,4))
>>> array((0,1)).choose(b0,b1)
array([1, 4])
>>> array((1,0)).choose(b0,b1)
array([3, 2])
>>> array((1,1)).choose(b0,b1)
array([3, 4])
Corresponding function:
choose
a.clip(min, max)
Every entry in a that is less than min is
replaced by min, and every entry greater than max is replaced by
max.
Example
>>> a=array([[0,2,4,6],[1,3,5,7]])
>>> a.clip(1,5)
array([[1, 2, 4, 5],
[1, 3, 5, 5]])
Corresponding function:
clip
a.compress(condition, axis=None)
Those elements of a corresponding to those elements of condition
that are True. condition must be a 1d array or sequence with
the same size as the given dimension of a. For axis=None (default)
condition works on the flattened version of a and produces a 1d array.
The corresponding function compress has default axis=1.
Examples:
>>> print a
[[1 2 3]
[4 5 6]]
>>> cond=array([True,True,True,True,False,False])
>>> a.compress(cond)
array([1, 2, 3, 4])
>>> print a.compress((True,True,False),1)
[[1 2]
[4 5]]
a.conj()
Returns the complex conjugate of a.
Example:
>>> print c
[[ 1.+1.j 2.+2.j]
[ 3.+3.j 4.+4.j]]
>>> print c.conj()
[[ 1.1.j 2.2.j]
[ 3.3.j 4.4.j]]
a.conjugate()
Equivalent to method a.conj().
Equivalent method:
a.conj()
Corresponding function
None
a.copy(order='C')
Returns a copy of the array.
If order is 'C' (False), which is the default, then the result is
contiguous in memory with the inner axis=1 filling sequential locations.
If order is 'Fortran' (True) then the result has fortran order.
If order is 'Any' (None) then the result has fortran order
only if a is already in fortran order. The corresponding function
copy has no argument to change the order, but can also take sequences
as argument.
Example:
>>> a=array([[1,2,3],[4,5,6]])
>>> a.flags
CONTIGUOUS : True
FORTRAN : False
OWNDATA : True
WRITEABLE : True
ALIGNED : True
UPDATEIFCOPY : False
>>> a.copy('Fortran').flags
CONTIGUOUS : False
FORTRAN : True
OWNDATA : True
WRITEABLE : True
ALIGNED : True
UPDATEIFCOPY : False
Corresponding function:
copy
a.cumprod(axis=None, dtype=None)
Returns the cumulative products of the elements along the given axis.
If axis=None (default), the cumulative product is taken over
the flattened version of a: a.cumprod() = a.flatten().cumprod().
Examples:
>>>array((2,3,4,5)).cumprod()
array([ 2, 6, 24, 120])
>>> a=array([[2,3],[4,5]])
>>> print a
[[2 3]
[4 5]]
>>> print a.cumprod()
[ 2 6 24 120]
>>> print a.cumprod(0)
[[ 2 3]
[ 8 15]]
>>> print a.cumprod(1)
[[ 2 6]
[ 4 20]]
a.cumsum(axis=None, dtype=None)
Returns the cumulative sum of the elements along the given axis.
If axis=None (default), the cumulative sum is taken over
the flattened version of a: a.cumsum() = a.flatten().cumsum().
Examples:
>>>array((2,3,4,5)).cumsum()
array([ 2, 5, 9, 14])
>>> a=array([[2,3],[4,5]])
>>> print a
[[2 3]
[4 5]]
>>> print a.cumsum()
[ 2 5 9 14]
>>> print a.cumsum(0)
[[ 2 3]
[ 6 8]]
>>> print a.cumsum(1)
[[ 2 5]
[ 4 9]]
a.diagonal(offset=0, axis1=0, axis2=1)
Returns the given diagonals
defined by the last two dimensions of the array.
Example:
>>> print a
[[1 2 3]
[4 5 6]
[7 8 9]]
>>> print a.diagonal()
[1 5 9]
>>> print a.diagonal(1)
[2 6]
a.dump(file)
a.dumps()
a.fill(value)
Places the scalar value at every position in the array.
a.flatten([fortran])
Returns a 1d array (always copy)
a.getfield(dtype, offset)
Returns a field of the given array as a certain type. A field is a view
of the array's data with each itemsize determined by the given type and
the offset into the current array.
a.item
Copies the first data point of the array to a standard Python scalar
and returns it.
a.max(axis=None)
Returns the maximum of 'a' along dimension axis. If axis=None (default), the
maximum over the whole array is returned.
Example:
>>> a=array([[1,5,3],[6,2,4]])
>>> a.max()
6
>>> a.max(1)
array([5, 6])
a.mean(axis=None, dtype=None)
Averages the array over the given axis. If the axis is None, average
over all dimensions of the array.
If an integer axis is given, this equals:
a.sum(axis, dtype) * 1.0 / a.shape[axis]
If axis is None, this equals:
a.sum(axis, dtype) * 1.0 / product(a.shape)
The optional dtype argument is the data type for intermediate
calculations in the sum.
Example:
>>> a=array([[1,5,3],[6,2,4]])
>>> a.mean()
3.5
>>> a.mean(0)
array([ 3.5, 3.5, 3.5])
>>> a.mean(1)
array([ 3., 4.])
a.min(axis=None)
Returns the minimum of 'a' along dimension axis. If axis=None (default),
the minimum over the whole array is returned.
Example:
>>> a=array([[1,5,3],[6,2,4]])
>>> a.min()
1
>>> a.min(1)
array([1, 2])
a.newbyteorder(<byteorder>)
Equivalent to a.view(a.dtype.newbytorder(<byteorder>))
a.nonzero()
Returns a tuple of arrays, one for each dimension of a,
containing the indices of the nonzero elements in that dimension.
The corresponding nonzero values can be obtained with
a[a.nonzero()].
To group the indices by element, rather than dimension, use
transpose(a.nonzero())
instead. The result of this is always a 2d array, with a row for each
nonzero element.
Example:
a 2d array with 3 nonzero elements at a(0,2), a(1,0) and a(1,1):
>>> print a
[[0 0 2]
[3 4 0]]
>>> a.nonzero()
(array([0, 1, 1]), array([2, 0, 1]))
>>> print a[a.nonzero()]
[2 3 4]
>>> print transpose(a.nonzero())
[[0 2]
[1 0]
[1 1]]
a.prod(axis=None, dtype=None)
Returns the product of the elements along the given axis. If axis=None,
the product of all elements of a is returned (a scalar).
Example:
>>> a
array([[1, 4],
[3, 2]])
>>> a.prod()
24
>>> a.prod(0)
array([3, 8])
>>> a.prod(1)
array([4, 6])
a.ptp(axis=None)
a.ptp(axis)= a.max(axis)a.min(axis)
a.put(values, indices)
Sets a.flat[n] = v[n] for each n in indices. v can be scalar or
shorter than indices, will repeat.
Examples:
>>> a=zeros((2,3))
>>> print a
[[ 0. 0. 0.]
[ 0. 0. 0.]]
>>> a.put([1.,2.,3.],[0,2,4])
>>> print a
[[ 1. 0. 2.]
[ 0. 3. 0.]]
>>> a.put([1.,2.],range(6))
>>> print a
[[ 1. 2. 1.]
[ 2. 1. 2.]]
a.putmask(values, mask)
Sets a.flat[n] = values[n] for each n where mask.flat[n] is True.
v can be scalar.
Example
>>> a=zeros((2,3))
>>> print a
[[ 0. 0. 0.]
[ 0. 0. 0.]]
>>> mask=array([[1,0,1],[1,0,1]])
>>> a.putmask([2.],mask)
>>> print a
[[ 2. 0. 2.]
[ 2. 0. 2.]]
a.ravel([fortran])
Return a 1d array (copy only if needed)
a.repeat(repeats=, axis=None)
Copies elements of a, repeats times. The repeats argument must
be a sequence of length a.shape[axis] or a scalar. In the case of a scalar
with axis=None (default), a flat array is returned.
Examples:
>>> print a
[[1 2 3]
[4 5 6]]
>>> print a.repeat(2)
[1 1 2 2 3 3 4 4 5 5 6 6]
>>> print a.repeat(2,0)
[[1 2 3]
[1 2 3]
[4 5 6]
[4 5 6]]
>>> print a.repeat(2,1)
[[1 1 2 2 3 3]
[4 4 5 5 6 6]]
Corresponding function:
repeat
a.reshape(d1, d2, ..., dn, order='C')
Returns a new array from this one.
The new array must have the same number of elements as a.
Always returns a view or raises a ValueError if that is
impossible.
The inputs d1, d2, ..., dn mat also be arranged as tuple
(d1, d2, ..., dn).
Example:
>>> a=array((1,2,3,4,5,6))
>>> print a.reshape(2,3)
[[1 2 3]
[4 5 6]]
>>> shape=(3,2)
>>> print a.reshape(shape)
[[1 2]
[3 4]
[5 6]]
a.resize(new_shape, refcheck=True, fortran=False)
Changes size and shape of self inplace. Fills with zeros if the new size
exceeds the size of a. Note: The function resize in that case fills
with repeats of a.
Array must own its own memory and not be referenced by other arrays.
Returns None.
Example:
>>> print a
[[1 2 3]
[4 5 6]]
>>> a.resize(3,4)
>>> print a
[[1 2 3 4]
[5 6 0 0]
[0 0 0 0]]
>>> print a.resize(3,4)
None
a.round(decimals=0)
Rounds array a to the given number of decimal places.
Rounding behaviour is equivalent to Python.
Returns 'a' if the array is not floating point. Rounds both the real
and imaginary parts separately if the array is complex.
Example:
>>> a=pi*arange(5)
>>> print a.round(2)
[ 0. 3.14 6.28 9.42 12.57]
a.searchsorted(v)
Assuming that a is a 1D array, in ascending order and
represents bin boundaries, then a.searchsorted(values) gives an
array of bin numbers, giving the bin into which each value would
be placed. This method is helpful for histograming.
Note: No warning is given if the boundaries, in a, are not
in ascending order.
a.setfield(value, dtype, offset)
Places val into field of the given array defined by the data type and offset.
a.setflags(write=None, align=None, uic=None)
a.sort(axis=1,kind='quicksort')
Sorts a in place (Return is None) and kind can be
'quicksort', 'mergesort', or 'heapsort'
a.squeeze()
Eliminates all length1 dimensions
a.std(axis=None, dtype=None)
Returns the standard deviation, a measure of the spread of a distribution.
The standard deviation is the square root of the average of the squared
deviations from the mean, i.e. std = sqrt(mean((x  x.mean())**2)).
For multidimensional arrays, std is computed by default along the first axis.
a.sum(axis=None, dtype=None)
Sums the array over the given axis. If the axis is None, sum over all
dimensions of the array.
The optional dtype argument is the data type for the returned value
and intermediate calculations. The default is to upcast (promote)
smaller integer types to the platformdependent int. For example, on
32bit platforms:
x.dtype

default sum() dtype

bool, Int8, Int16, Int32

Int32

Examples:
>>> sum([0.5, 1.5])
2.0
>>> sum([0.5, 1.5], dtype=Int32)
1
>>> sum([[0, 1], [0, 5]])
array([0, 6])
>>> sum([[0, 1], [0, 5]], axis=1)
array([1, 5])
a.swapaxes(axis1, axis2)
Returns new view with axes swapped.
a.take(indices, axis=None)
Selects the elements in indices from array a along the given axis.
a.tofile(fid, sep=)
Writes the data to a file.
a.tolist()
Copies the data portion of the array to a hierarchical python list
and returns that list.
a.tostring(order='C')
Constructs a Python string containing the raw bytes in the array
a.trace(offset=0, axis1=0, axis2=1, dtype=None)
Returns the sum along the offset diagonal of the arrays indicated
axis1 and axis2.
a.transpose(axes)
Returns a view of the array with
dimensions permuted according to axes. axes is a tuple indicating the permuted
sequence of dimensions. If axes is None
(default) the array a is returned with dimensions reversed.
Note:
For a twodimensional array transpose(a) is equivalent to
swapaxes(a,0,1).
Example:
>>> a=array([[[1,2,3],[4,5,6]],[[1,2,3],[4,5,6]]])
>>> print a
[[[ 1 2 3]
[ 4 5 6]]
[[1 2 3]
[4 5 6]]]
>>> print transpose(a,[2,0,1])
[[[ 1 4]
[1 4]]
[[ 2 5]
[2 5]]
[[ 3 6]
[3 6]]]
a.var(axis=None, dtype=None)
a.view(<type>)
Returns a new view of array with same data.
type can be either a new subtype object or a datadescriptor object
ARRAY FUNCTIONS
For most array functions corresponding array
methods
are available. The latter are often preferred. These are indicated in the
'Corresponding methods' boxes. Often a method and a function are similar,
but have different default arguments. The following functions are listed:
add_docstring(...)
(obj, docstring) >
None
Add a docstring to a builtin obj if possible.
If the obj already has a docstring raise a RuntimeError
If this routine does not know how to add a docstring to the object
raise a TypeError
add_newdoc(place, obj, doc)
Adds documentation to obj which is in module place.

If doc is a string add it to obj as a docstring

If doc is a tuple, then the first element is interpreted as
an attribute of obj and the second as the docstring
(method, docstring)

If doc is a list, then each element of the list should be a
sequence of length two >
[(method1, docstring1),
(method2, docstring2), ...]
This routine never raises an error.
alen(a)
Return the length of a Python object interpreted as an array
of at least 1 dimension.
Remark:
This function returns a zerodimensional array,
with value identical to the result of the python standard function
len(a)
, which also works on arrays.
Example
>>> a=array([[1,2,3],[4,5,6]])
>>> alen(a)
2
>>> len(a)
2
all(x, axis=None)
Returns true if all elements of x are true
allclose(a, b, rtol=1.e5, atol=1.e8)
Returns true if all components of a and b are equal
subject to given tolerances.
The relative error rtol must be positive and
< 1.0
The absolute error atol comes into play for those elements
of b that are very small or zero; it says how small a must be also.
Corresponding method:
none
alltrue(x, axis=0)
Perform a logical_and over the given axis.
Example
>>> m=array([[True, False, False],[True, True, False]])
>>> alltrue(m)
array([True, False, False], dtype=bool)
>>> alltrue(m, axis=1)
array([False, False], dtype=bool)
See also:
all,
any
Corresponding method:
none
alterdot(...)
alterdot() changes all dot functions to use blas.
Corresponding method:
none
amax(a, axis=0)
Returns the maximum of 'a' along dimension axis. If axis=None, the
maximum over the whole array is returned.
Example:
>>> a=array([[1,5,3],[6,2,4]])
>>> amax(a)
array([6, 5, 4])
>>> amax(a,1)
array([5, 6])
amin(a, axis=0)
Returns the minimum of 'a' along dimension axis. If axis=None, the
minimum over the whole array is returned.
Example:
>>> a=array([[1,5,3],[6,2,4]])
>>> amin(a)
array([1, 2, 3])
>>> amin(a,1)
array([1, 2])
angle(z, deg=0)
Returns the angle (in radian) of the complex argument z. Works also on arrays.
Example:
>>> z=1.+1.j
>>> phi=angle(z)
>>> print phi, 180.*phi/pi
0.785398163397 45.0
Corresponding method:
none
any(x, axis=None)
Returns True if any elements of x are true:
apply_along_axis(func1d, axis, arr, *args)
Execute func1d(arr[i],*args) where func1d takes 1D arrays
and arr is an Nd array. i varies so as to apply the function
along the given axis for each 1d subarray in arr.
Corresponding method:
none
apply_over_axes(func, a, axes)
Apply a function repeatedly over multiple axes, keeping the same shape
for the resulting array.
func is called as res = func(a, axis). The result is assumed
to be either the same shape as a or have one less dimension.
This call is repeated for each axis in the axes sequence.
Corresponding method:
none
arange([start,] stop[, step,], dtype=None)
For integer arguments, just like range() except it returns an array whose type can
be specified by the keyword argument dtype.
If dtype is not specified, the type of the result is deduced from the type of the
arguments.
For floating point arguments, the length of the result is ceil((stop  start)/step).
This rule may result in the last element of the result be greater than stop.
Examples:
>>> arange(5)
array([0, 1, 2, 3, 4])
>>> arange(5.)
array([ 0., 1., 2., 3., 4.])
>>> arange(1.,5.)
array([ 1., 2., 3., 4.])
>>> arange(1.,3.,0.5)
array([ 1. , 1.5, 2. , 2.5])
Corresponding method:
none
argmax(a, axis=1)
Returns the indices to the maximum value of the
1D arrays along the given axis. Axis 1 is the last axis
(in a matrix these are the rows). For examples see method a.argmax().
argmin(a, axis=1)
Returns the indices to the minimum value of the
1D arrays along the given axis. Axis 1 is the last axis
(in a matrix these are the rows). For examples see method a.argmin().
argsort(a, axis=1)
Returns the indices into a of the sorted array
along the given axis. Axis 1 is the last axis
(in a matrix these are the rows). For examples see method a.argsort().
argwhere(a)
Returs a 2d array of shape N x a.ndim where each row
is a sequence of indices into a. This sequence must be
converted to a tuple in order to be used to index into a.
Corresponding method:
none
around(a, decimals=0)
Returns 'a' rounded to the given number of decimal places. Rounding
behaviour is equivalent to Python.
Returns 'a' if the array is not floating point. Round both the real
and imaginary parts separately if the array is complex. When a is a scalar, around
defaults to the python builtin function 'round'.
Example:
>>> a=pi*arange(1,5)
>>> print a
[ 3.14159265 6.28318531 9.42477796 12.56637061]
>>> print around(a,decimals=2)
[ 3.14 6.28 9.42 12.57]
array(object, dtype=None, copy=1, order=None, subok=0,ndmin=0)
Returns an array from object with the specified datetype
Inputs:
 object  an array, any object exposing the array interface, any
object whose __array__ method returns an array, or any
(nested) sequence.
 dtype  The desired datatype 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  If true, then force a copy. Otherwise a copy will only occur
if __array__ returns a copy, obj is a nested sequence, or
a copy is needed to satisfy any of the other requirements
 order  Specify the order of the array. If order is 'C', then the
array will be in Ccontiguous order (lastindex varies the
fastest). If order is 'FORTRAN', then the returned array
will be in Fortrancontiguous order (firstindex varies the
fastest). If order is None, then the returned array may
be in either C, or Fortrancontiguous order or even
discontiguous.
 subok  If True, then subclasses will be passedthrough, otherwise
the returned array will be forced to be a baseclass array
 ndmin  Specifies the minimum number of dimensions that the resulting
array should have. 1's will be prepended to the shape as
needed to meet this requirement.
Examples:
>>> a=array([[1,2],[3,4]])
>>> print a
[[1 2]
[3 4]]
>>> b=array((1.,2,3+1.j))
>>> print b
[ 1.+0.j 2.+0.j 3.+1.j]
Corresponding method:
none
array2string(a, max_line_width=None, precision=None, suppress_small=None, separator=' ',
prefix='', style=<builtin function repr>)
Corresponding method:
none
array_repr(arr, max_line_width=None, precision=None, suppress_small=None)
Corresponding method:
none
array_split(ary, indices_or_sections, axis=0)
Divide an array into a list of subarrays.
Description:
Divide ary into a list of subarrays along the
specified axis. If indices_or_sections is an integer,
ary is divided into that many equally sized arrays.
If it is impossible to make an equal split, each of the
leading arrays in the list have one additional member. If
indices_or_sections is a list of sorted integers, its
entries define the indexes where ary is split.
Arguments:
 ary  Array to be divided into subarrays.
 indices_or_sections  integer or 1D array.
If integer, defines the number of (close to) equal sized
subarrays. If it is a 1D array of sorted indices, it
defines the indexes at which ary is divided. Any empty
list results in a single subarray equal to the original
array.
 axis  integer. default=0.
Specifies the axis along which to split ary.
Caveats:
Currently, the default for axis is 0. This
means a 2D array is divided into multiple groups
of rows. This seems like the appropriate default, but
we've agreed most other functions should default to
axis=1. Perhaps we should use axis=1 for consistency.
However, we could also make the argument that NumPy
works on "rows" by default. sum() sums up rows of
values. split() will split data into rows. Opinions?
Corresponding method:
none
array_str(a, max_line_width=None, precision=None, suppress_small=None)
Corresponding method:
none
asanyarray(a, dtype=None, order=None)
Returns a as an array, but will pass subclasses through.
Corresponding method:
none
asarray(a, dtype=None, order=None)
Returns a as an array.
Unlike array(), no copy is performed if a is already an array. Subclasses
are converted to base class ndarray.
Corresponding method:
none
asarray_chkfinite(a)
Like asarray, but check that no NaNs or Infs are present.
Corresponding method:
none
ascontiguousarray(a, dtype=None)
Returns 'a' as an array contiguous in memory (C order).
Corresponding method:
none
asfarray(a, dtype=<type 'float64scalar'>)
asfarray(a,dtype=None)
Returns a as a float array.
Corresponding method:
none
asfortranarray(a, dtype=None)
Returns 'a' as an array laid out in Fortranorder in memory.
Corresponding method:
none
asmatrix(data, dtype=None)
Returns 'data' as a matrix. Unlike matrix(), no copy is performed
if 'data' is already a matrix or array. Equivalent to:
matrix(data, copy=False)
Corresponding method:
none
asscalar(a)
Converts an array of size 1 to its scalar equivalent.
Corresponding method:
none
atleast_1d(*arys)
Force a sequence of arrays to each be at least 1D.
Description:
Force an array to be at least 1D. If an array is 0D, the
array is converted to a single row of values. Otherwise,
the array is unaltered.
Arguments:
*arys  arrays to be converted to 1 or more dimensional array.
Returns:
input array converted to at least 1D array.
Corresponding method:
none
atleast_2d(*arys)
Force a sequence of arrays to each be at least 2D.
Description:
Force an array to each be at least 2D. If the array
is 0D or 1D, the array is converted to a single
row of values. Otherwise, the array is unaltered.
Arguments
:
arys  arrays to be converted to 2 or more dimensional array.
Returns:
input array converted to at least 2D array.
Corresponding method:
none
atleast_3d(*arys)
Force a sequence of arrays to each be at least 3D.
Description:
Force an array each be at least 3D. If the array is 0D or 1D,
the array is converted to a single 1xNx1 array of values where
N is the orginal length of the array. If the array is 2D, the
array is converted to a single MxNx1 array of values where MxN
is the orginal shape of the array. Otherwise, the array is
unaltered.
Arguments:
arys  arrays to be converted to 3 or more dimensional array.
Returns:
input array converted to at least 3D array.
Corresponding method:
none
average(a, axis=0, weights=None, returned=False)
Average the array over the given axis. If the axis is None, average
over all dimensions of the array. Equivalent to the method a.mean(axis), but
with a default axis of 0 instead of None.
If an integer axis is given, this equals:
a.sum(axis) * 1.0 / a.shape[axis]
If axis is None, this equals:
a.sum(axis) * 1.0 / product(a.shape)
If weights are given, result is:
sum(a * weights) / sum(weights),
where the weights must have a's shape or be 1D with length the
size of a in the given axis. Integer weights are converted to
Float. Not specifying weights is equivalent to specifying
weights that are all 1.
If 'returned' is True, return a tuple: the result and the sum of
the weights or count of values. The shape of these two results
will be the same.
Raises ZeroDivisionError if appropriate. (The version in MA does
not  it returns masked values).
bartlett(M)
Returns array with the Mpoint Bartlett window (used in signal processing). It is a
triangular function starting and ending with 0. M is an integer.
base_repr(number, base=2, padding=0)
Returns the representation of a number in any given base.
binary_repr(num)
Returns the binary representation of the input number as a string.
This is equivalent to using base_repr with base 2, but about 25x
faster.
Corresponding method:
none
bincount(x,weights=None)
Returns the number of occurrences of each value in x.
x must be a list of nonnegative 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.
blackman(M)
Returns array with the Mpoint Blackman window (used in signal processing). It is a
bellshaped function starting and ending with 0. M is an integer.
bmat(obj, ldict=None, gdict=None)
Build a matrix object (= 2dim array) from string, nested sequence, or array.
Example:
F = bmat('A, B; C, D')
F = bmat([[A,B],[C,D]])
F = bmat(r_[c_[A,B],c_[C,D]])
all produce the same Matrix Object
[ A B ]
[ C D ]
if A, B, C, and D are appropriately shaped 2d arrays.
can_cast(from=d1, to=d2)
Returns True if data type d1 can be cast to data
type d2 without losing precision.
Corresponding method:
none
central_diff_weights(Np, ndiv=1)
Returns weights for an Nppoint central derivative of order ndiv
assuming equallyspaced function points.
If weights are in the vector w, then
derivative is w[0] * f(xho*dx) + ... + w[1] * f(x+h0*dx)
Can be inaccurate for large number of points.
Corresponding method:
none
choose(a, choices)
For description and example see method a.choose().
clip(a, min, max)
Every entry in a that is less than min is
replaced by min, and every entry greater than max is replaced by
max.
column_stack(tup)
Stacks 1D arrays as columns into a 2D array
Description:
Takes a sequence of 1D arrays and stacks them as columns
to make a single 2D array. All arrays in the sequence
must have the same length.
Arguments:
tup  sequence of 1D arrays. All arrays must have the same
length.
Example:
>>> a = array((1,2,3))
>>> b = array((2,3,4))
>>> column_stack((a,b))
array([[1, 2],
[2, 3],
[3, 4]])
Corresponding method:
none
comb(N, k, exact=0)
Binomial (combinatorial) coefficient N over k: number ways k items can be
chosen from a set of N items.
Equal to N!/[k!(Nk)!]
If exact==0, then floating point precision is used, otherwise
exact long integer is computed.
Notes:
 Array arguments accepted only for exact=0 case.
 If k > N, N < 0, or k < 0, then a 0 is returned.
Example:
>>> a=arange(6)
>>> comb(5,a)
array([ 1., 5., 10., 10., 5., 1.])
See also:
factorial
Corresponding method:
none
common_type(*arrays)
Given a sequence of arrays as arguments, returns the best inexact
scalar type which is "most" common amongst them.
The return type will always be a inexact scalar type, even if all
the arrays are integer arrays.
compress(condition, a, axis=1)
Those elements of a corresponding
to those elements of condition that are True. condition must be the
same size as the given dimension of a. See method compress for examples.
concatenate((a1, a2, ...), axis=None)
Joins arrays together.
The tuple of sequences (a1, a2, ...) are joined along the given axis
(default is the first one) into a single array.
Example:
>>> concatenate( ([0,1,2], [5,6,7]) )
array([0, 1, 2, 5, 6, 7])
Corresponding method:
none
convolve(a, v, mode='full')
Returns the discrete, linear convolution of 1D
sequences a and v; mode can be 0 (valid), 1 (same), or 2 (full)
to specify size of the resulting sequence. Produces the correlation
between a and the reverse of v, when v is shorter or of equal length
as a; otherwise a and v are interchanged.
See also:
correlate
Corresponding method:
none
copy(a)
Returns an array copy of the given object, which may be an
array or a sequence. The corresponding method a.copy() can also
change the order ('C' or 'Fortran') in which the array elements
are stored.
Example
>>> a=[1, 2., 3+1j]
>>> copy(a)
array([ 1.+0.j, 2.+0.j, 3.+1.j])
corrcoef(x, y=None, rowvar=1, bias=0)
Returns the correlation coefficients derived from the covariance matrix.
See cov for details.
The correlation coefficient between two sets of observations x and y is
defined as
cov(x,y)/sqrt(var(x)*var(y))
Corresponding method:
none
correlate(a, v, mode='valid')
Corresponding method:
none
cov(m, y=None, rowvar=1, bias=0)
Estimates the covariance matrix. The covariance of two sets of N
observations x
_{
0
},..x
_{
N1
}, y
_{
0
},..y
_{
N1
}
is defined as
cov(x,y) = (1./(N1)) Σ
_{
i
}
(x
_{
i
}
 <x>)(y
_{
i
}
 <y>),
where <x> stands for the mean or average of x. Normalization is by (N1), where N
is the number of observations (unbiased estimate). If bias=1 then normalization is by N.
The input data are a set of n variables with N
observations each. If there is one variable (i.e., m is a vector),
the variance is returned. If there are two variables, m and y, each being
a vector of the same length N, the function can be called as cov(m,y) and a
symmetric 2*2 matrix is returned containing
cov(m,m)=var(m)

cov(m,y)

cov(y,m)

cov(y,y)=var(y)

If there are n=2 or more variables, arranged in an array of shape (n,N)
(i.e., the rows contain the N the observations of one variable), and y=None (default),
the n*n covariance matrix of the rows is returned. However, if rowvar=False, the
covariance matrix of the columns is returned, and the correct covariance is obtained
if the columns contain the N observations of one variable
(the shape of the array must then be (N,n)).
Examples:
>>> x=array((1.,0.,1.))
>>> y=array((3.,0.,3.))
>>> print cov(x,y)
[[ 1. 3.]
[3. 9.]]
>>> z=asarray([x,y])
>>> print z
[[1. 0. 1.]
[ 3. 0. 3.]]
>>> print cov(z)
[[ 1. 3.]
[3. 9.]]
>>> print cov(z,rowvar=False)
[[ 8. 0. 8.]
[ 0. 0. 0. ]
[8. 0. 8.]]
>>> print corrcoef(x,y)
[[ 1. 1.]
[1. 1.]]
cross(a, b, axisa=1, axisb=1, axisc=1, axis=None)
Returns 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 zcomponent of the equivalent threedimensional cross product is
returned.
Example
>>> x=array((1,0,0))
>>> y=array((0,1,0))
>>> cross(x,y)
array([0, 0, 1])
>>> cross(y,x)
array([ 0, 0, 1])
Corresponding method:
none
ctypes_load_library(libname, loader_path)
# Adapted from Albert Strasheim
Corresponding method:
none
cumprod(a, axis=0, dtype=None)
Returns the cumulative product of the elements along the given axis.
cumprod(a) = a.cumprod(0). For examples see method
a.cumprod()
cumproduct(x, axis=0, dtype=None)
cumsum(x, axis=0, dtype=None)
Returns the cumulative sum of the elements along the given axis.
See method
a.cumsum()
for examples. Note that
method and function have different default axes.
deprecate(func, oldname, newname)
Corresponding method:
none
derivative(func, x0, dx=1.0, n=1, args=(), order=3)
Given a function, use a central difference formula with spacing dx to
compute the nth derivative at x0.
order is the number of points to use and must be odd.
Warning:
Decreasing the step size too small can result in
roundoff error.
Corresponding method:
none
diag(v, k=0)
Returns a copy of the the kth diagonal if v is a 2d array
or returns a 2d array with v as the kth diagonal if v is a
1d array.
Examples:
>>
> v=array((1,2,3))
>>> diag(v)
array([[1, 0, 0],
[0, 2, 0],
[0, 0, 3]])
>>> diag(v,k=1)
array([[0, 0, 0, 0],
[1, 0, 0, 0],
[0, 2, 0, 0],
[0, 0, 3, 0]])
Corresponding method:
none
diagonal(a, offset=0, axis1=0, axis2=1)
Returns the given diagonals
defined by the last two dimensions of the array.
See method a.diagonal() for examples.
diff(a, n=1, axis=1)
Calculates the nth order discrete difference along given axis.
Corresponding method:
none
digitize(x,bins)
Returns index of the bin to which each value of x belongs.
Each index i returned is such that bins[i1] <= x < bins[i] if
bins is monotonically increasing, or bins [i1] > x >= bins[i] if
bins is monotonically decreasing.
Beyond the bounds of the bins 0 or len(bins) is returned as appropriate.
Corresponding method:
none
disp(mesg, device=None, linefeed=True)
Displays a message to the given device (default is sys.stdout)
with or without a linefeed.
Corresponding method:
none
dot(a,b)
matrix product (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 secondtolast dimension of b.
NB:
The first argument, if complex, is not conjugated.
Examples:
Two onedim arrays (of equal length) are considered as vectors and yield the
scalar or dot product (Σ
_{
i
}
a
_{
i
}
b
_{
i
}
)
>>> a=array([1.,1.,1.])
>>> dot(a,a)
3.
Twodimensional matrices yield the matrix product C=AB; C
_{
ij
}
=
Σ
_{
k
}
A
_{
ik
}
B
_{
kj
}:
>>> A=array([[1.,1.,1.]])
>>> print A
[[1. 1. 1.]]
>>> B=A.transpose()
>>> print B
[[1.]
[1.]
[1.]]
>>> print dot(A,B)
[[3.]]
>>> print dot(B,A)
[[1. 1. 1.]
[1. 1. 1.]
[1. 1. 1.]]
See also:
inner,
vdot
Corresponding method:
none
dsplit(ary, indices_or_sections)
Splits ary into multiple subarrays along the 3rd axis (depth)
Description:
Splits a single array into multiple subarrays. The array is
divided into groups along the 3rd axis. If indices_or_sections is
an integer, ary is divided into that many equally sized sub arrays.
If it is impossible to make the subarrays equally sized, the
operation throws a ValueError exception. See array_split and
split for other options on indices_or_sections.
Arguments:
 ary  ND array.
Array to be divided into subarrays.
 indices_or_sections  integer or 1D array.
If integer, defines the number of (close to) equal sized
subarrays. If it is a 1D array of sorted indices, it
defines the indexes at which ary is divided. Any empty
list results in a single subarray equal to the original
array.
Returns:
sequence of subarrays. The returned arrays have the same
number of dimensions as the input array.
Caveats:
See vsplit caveats.
Examples:
>>> a = array([[[1,2,3,4],[1,2,3,4]]])
>>>dsplit(a,2)
[array([ [[1, 2],
[1, 2]]]), array([ [[3, 4],
[3, 4]]])]
dstack(tup)
Stacks arrays in sequence depth wise (along third dimension)
Description:
Takes a sequence of arrays and stacks them along the third axis.
All arrays in the sequence must have the same shape along all
but the third axis. This is a simple way to stack 2D arrays
(images) into a single 3D array for processing.
dstack will rebuild arrays divided by dsplit.
Arguments:
 tup  sequence of arrays. All arrays must have the same
shape.
Examples:
>>> a = array((1,2,3))
>>> b = array((2,3,4))
>>> dstack((a,b))
array([[ [1, 2],
[2, 3],
[3, 4]]])
empty(shape, dtype=float, order='C')
Returns an empty (uninitialized) array of the specified shape and typecode.
Note that this does NOT initialize the returned array. If you require
your array to be initialized, you should use zeros or ones.
empty_like(a)
Returns an empty (uninitialized) array of the shape and typecode of a.
Note that this does NOT initialize the returned array. If you require
your array to be initialized, you should use zeros_like or ones_like.
expand_dims(a, axis)
Expands the shape of a by including newaxis before given axis.
Corresponding method:
none
extract(condition, arr)
Returns the elements of ravel(arr) where ravel(condition) is True
(in 1D).
Equivalent to compress(ravel(condition), ravel(arr)).
Corresponding method:
none
eye(N, M=None, k=0, dtype=
<type 'float'>)
Returns a NbyM 2d array where the kth diagonal is all ones,
and everything else is zeros.
Corresponding method:
none
factorial(n, exact=0)
n! = special.gamma(n+1)
If exact==0, then floating point precision is used, otherwise
exact long integer is computed.
Notes:
 Array argument accepted only for exact=0 case.
 If n < 0, the return value is 0.
Corresponding method:
none
factorial2(n, exact=0)
n!! = special.gamma(n/2+1)*2**((m+1)/2)/sqrt(pi) n odd
= 2**(n) * n! n even
If exact==0, then floating point precision is used, otherwise
exact long integer is computed.
Notes
 Array argument accepted only for exact=0 case.
 If n < 0, the return value is 0.
Corresponding method:
none
factorialk(n, k, exact=1)
n(!!...!) = multifactorial of order k
k times
Corresponding method:
none
fastCopyAndTranspose(a)
Returns transposed copy of array a
Corresponding method:
none
fix(x, y=None)
Rounds x to nearest integer towards zero.
fliplr(m)
Returns an array m with the rows preserved and columns flipped
in the left/right direction. Works on the first two dimensions of m.
Corresponding method:
none
flipud(m)
Returns an array with the columns preserved and rows flipped in
the up/down direction. Works on the first dimension of m.
Corresponding method:
none
frombuffer(buffer=, dtype=float, count=1, offset=0)
Returns a 1d array of data type dtype from buffer. The buffer
argument must be an object that exposes the buffer interface.
If count is 1 then the entire buffer is used, otherwise, count
is the size of the output. If offset is given then jump that
far into the buffer. If the buffer has data that is
not in machine byteorder, than use a proper data type
descriptor. The data will not
be byteswapped, but the array will manage it in future
operations.
Corresponding method:
none
fromfile(file=, dtype=float, count=1, sep='')
Returns an array of the given data type from a
(text or binary) file. The file argument can be an open file
or a string with the name of a file to read from. If
count==1, then the entire file is read, otherwise count is
the number of items of the given type read in. If sep is ''
then read a binary file, otherwise it gives the separator
between elements in a text file.
WARNING:
This function should be used sparingly, as it is not
a platformindependent method of persistence. But it can be
useful to read in simplyformatted or binary data quickly.
Corresponding method:
none
fromfunction(function, dimensions, **kwargs)
Returns an array constructed by
calling function on a tuple of number grids. The function should
accept as many arguments as there are dimensions which is a list of
numbers indicating the length of the desired output for each axis.
The function can also accept keyword arguments which will be
passed in as well.
Corresponding method:
none
fromiter(iterable, dtype, count=1)
Returns a new 1d array initialized from iterable.
If count is nonegative, the new array will have count elements, otherwise it's size
is determined by the generator.
Corresponding method:
none
frompyfunc(func, nin, nout)
Takes 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
Corresponding method:
none
fromstring(string, dtype=float, count=1, sep='')
Returns a new 1d array initialized
from the raw binary data in string. If count is positive, the new array will have
count elements, otherwise it's size is determined by the size of string. If sep is
not empty then the string is interpreted in ASCII mode and converted to the desired
number type using sep as the separator between elements (extra whitespace is ignored).
Corresponding method:
none
get_include()
Returns the directory in the package 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. Using distutils:
import numpy
Extension('extension_name', ...
include_dirs=[numpy.get_include()])
Corresponding method:
none
get_numarray_include(type=None)
Returns the directory in the package 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. Using distutils:
import numpy
Extension('extension_name', ...
include_dirs=[numpy.get_include()])
get_numpy_include(*args, **kwds)
get_numpy_include is DEPRECATED in numpy: use get_include instead.
Returns the directory in the package 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. Using distutils:
import numpy
Extension('extension_name', ...
include_dirs=[numpy.get_include()])
Corresponding method:
none
get_printoptions()
Corresponding method:
none
getbuffer(obj [,offset[, size]])
Creates a buffer object from the given object
referencing a slice of length size starting at offset. Default
is the entire buffer. A readwrite buffer is attempted followed by a readonly buffer.
Corresponding method:
none
getbufsize()
Returns the size of the buffer used in ufuncs.
Corresponding method:
none
geterr()
Get the current way of handling floatingpoint errors.
Returns a dictionary with entries "divide", "over", "under", and
"invalid", whose values are from the strings
"ignore", "warn", "raise", and "call".
Corresponding method:
none
geterrcall()
Returns the current callback function used on floatingpoint errors.
Corresponding method:
none
geterrobj(...)
Corresponding method:
none
gradient(f, *varargs)
Calculates the gradient of an Ndimensional scalar function.
Uses central differences on the interior and first differences on boundaries
to give the same shape.
Inputs:

f  An Ndimensional array giving samples of a scalar function

varargs  0, 1, or N scalars giving the sample distances in each direction
Outputs:
N arrays of the same shape as f giving the derivative of f with respect
to each dimension.
Corresponding method:
none
hamming(M)
Returns array with the Mpoint Hamming window (used in signal processing).
It is a bellshaped function starting and ending with 0. M is an integer.
hanning(M)
Returns array with the Mpoint Hanning window (used in signal processing).
It is a bellshaped function (one cosine cycle + 1), starting and ending
with 0. M is an integer.
histogram(a, bins=10, range=None, normed=False)
Returns the distribution of a collection of samples.
Input:
 a  array containing samples
 bins  number of bins
 range  lower and upper bin edges (default: [sample.min(), sample.max()]).
Does not really work, all values greater than range are stored in
the last bin.
 normed  If False (default), returns the number of samples in each bin.
If True, return a frequency distribution.
Output:
histogram array, left bin edges array.
Example:
>>> a=randn(100)
>>> result=histogram(a, bins=8, range=[4.,4.])
>>> print result[0] # nr of samples in each bin
[ 0 1 5 42 37 12 2 1]
>>> print result[1] # left bin boundaries
[4. 3. 2. 1. 0. 1. 2. 3.]
Corresponding method:
none
histogram2d(x, y, bins, normed=False)
Computes the 2D histogram for a dataset (x,y) given the edges or
the number of bins.
Returns histogram, xedges, yedges.
The histogram array is a count of the number of samples in each bin.
The array is oriented such that H[i,j] is the number of samples falling
into binx[j] and biny[i].
Setting normed to True returns a density rather than a bin count.
Data falling outside of the edges are not counted.
Corresponding method:
none
hsplit(ary, indices_or_sections)
Splits ary into multiple columns of subarrays
Description:
Splits a single array into multiple sub arrays. The array is
divided into groups of columns. If indices_or_sections is
an integer, ary is divided into that many equally sized sub arrays.
If it is impossible to make the subarrays equally sized, the
operation throws a ValueError exception. See array_split and
split for other options on indices_or_sections.
Arguments:
 ary  ND array.
Array to be divided into subarrays.
 indices_or_sections  integer or 1D array.
If integer, defines the number of (close to) equal sized
subarrays. If it is a 1D array of sorted indices, it
defines the indexes at which ary is divided. Any empty
list results in a single subarray equal to the original
array.
Returns:
sequence of subarrays. The returned arrays have the same
number of dimensions as the input array.
Examples:
>>> a= array((1,2,3,4))
>>> hsplit(a,2)
[array([1, 2]), array([3, 4])]
>>> a = array([[1,2,3,4],[1,2,3,4]])
[array([[1, 2],
[1, 2]]), array([[3, 4],
[3, 4]])]
hstack(tup)
Stacks arrays in sequence horizontally (column wise)
Description:
Takes a sequence of arrays and stacks them horizontally
to make a single array. All arrays in the sequence
must have the same shape along all but the second axis.
hstack will rebuild arrays divided by hsplit.
Arguments:

tup  sequence of arrays. All arrays must have the same
shape.
Examples:
>>> a=array((1,2,3))
>>> b=array((4,5,6))
>>> hstack((a,b))
array([1, 2, 3, 4, 5, 6])
>>> a=array([[1],[2],[3]])
>>> b=array([[4],[5],[6]])
>>> hstack((a,b))
array([[1, 4]
[2, 5],
[3, 6]])
i0(x)
Returns zeroorder Bessel function for real or complex argument array.
Example:
>>> i0(arange(5.))
array([ 1. , 1.26606588,
2.2795853 , 4.88079259, 11.30192195])
Corresponding method:
none
identity(n, dtype=None)
identity(n) returns the identity 2d array of shape n x n.
Example:
>>> identity(2)
array([[ 1., 0.],
[ 0., 1.]])
Corresponding method:
none
imag(val)
Returns the imaginary part of val as an array.
The argument val maybe a scalar or an array. See attribute a.imag
for examples.
indices(dimensions, dtype=int)
Returns an array representing a grid
of indices with rowonly, and columnonly variation.
Corresponding method:
none
info(object=None, maxwidth=76, output=<idlelib.rpc.RPCProxy instance>)
Get help information for a function, class, or module.
Example:
>>> info(polyval)
polyval(p, x)
Evaluate the polymnomial p at x.
Description:
If p is of length N, this function returns the value:
p[0]*(x**N1) + p[1]*(x**N2) + ... + p[N2]*x + p[N1]
Corresponding method:
none
inner(a,b)
innerproduct(a,b)
Returns the inner product of a and b for arrays of floating point types.
Like the generic NumPy equivalent the product sum is over
the last dimension of a and b.
For two onedim arrays of the same length, inner(a,b) is equivalent to dot(a,b),
yielding the scalar or inner product of two vectors.
For twodimensional arrays, inner(A,B) computes the matrix product AB
^{
T
},
which is equivalent to dot(A,B.transpose()). For matrix products in the usual
mathematical sense, one should use dot and not inner.
NB:
The first argument, if complex, is not conjugated.
Examples:
>>> A=array([[1.,1.],[0.,2.]])
>>> B=array([[0.,1.],[1.,0.]])
>>> inner(A,B)
array([[ 1., 1.],
[ 2., 0.]])
>>> dot(A,B)
array([[1., 1.],
[2., 0.]])
See also:
dot,
vdot
Corresponding method:
none
insert(arr, mask, vals)
Similar to putmask arr [mask] = vals but the 1D array vals has the
same number of elements as the nonzero values of mask. Inverse of
extract. The insertion is done in place; the function returns None.
Example:
>>> a=zeros((2,3))
>>> print a
[[ 0. 0. 0.]
[ 0. 0. 0.]]
>>> mask=array([[1,0,1],[1,0,1]])
>>> insert(a,mask,[2.,1.,1.,2.])
>>> print a
[[ 2. 0. 1.]
[ 1. 0. 2.]]
See also:
put
;
putmask
Corresponding method:
none
intersect1d(ar1, ar2)
Intersection of 1D arrays with unique elements.
Corresponding method:
none
intersect1d_nu(ar1, ar2)
Intersection of 1D arrays with any elements.
Corresponding method:
none
iscomplex(x)
Returns a boolean array where elements are True if that element
is complex (has nonzero imaginary part).
For scalars, returns a boolean.
Corresponding method:
none
iscomplexobj(x)
Returns True if x is a complex type or an array of complex numbers.
Unlike iscomplex(x), complex(3.0) is considered a complex object.
Corresponding method:
none
isfortran(a)
Returns True if 'a' is laid out in Fortranorder in memory.
Corresponding method:
none
isneginf(x, y=None)
Returns a boolean array y with y[i] True for x[i] = Inf.
If y is an array, the result replaces the contents of y.
Corresponding method:
none
isposinf(x, y=None)
Returns a boolean array y with y[i] True for x[i] = +Inf.
If y is an array, the result replaces the contents of y.
Corresponding method:
none
isreal(x)
Return a boolean array where elements are True if that element
is real (has zero imaginary part)
For scalars, return a boolean.
Corresponding method:
none
isrealobj(x)
Return True if x is not a complex type.
Unlike isreal(x), complex(3.0) is considered a complex object.
Corresponding method:
none
isscalar(num)
Returns True if the type of num is a scalar type.
Determines whether the given object represents
a numeric array type.
Corresponding method:
none
issubclass_(arg1, arg2)
Corresponding method:
none
iterable(y)
Corresponding method:
none
ix_(*args)
Construct an open mesh from multiple sequences.
This function takes n 1d sequences and returns n outputs with n
dimensions each such that the shape is 1 in all but one dimension and
the dimension with the nonunit shape value cycles through all n
dimensions.
Using ix_() one can quickly construct index arrays that will index
the cross product.
a[ix_([1,3,7],[2,5,8])] returns the array
a[1,2] a[1,5] a[1,8]
a[3,2] a[3,5] a[3,8]
a[7,2] a[7,5] a[7,8]
Corresponding method:
none
kaiser(M, beta)
Returns a Kaiser window of length M with shape parameter
beta. The Kaiser window is a function that looks like a half sine wave,
but consists of a modified Bessel function and a sinh function;
it is used as a filter in signal processing.
kron(a, b)
Kronecker product of a and b
The Kronecker product of two matrices is a block matrix
[

[

a[0,0]*b

a[0,1]*b

...

a[0,n1]*b

]


[

...



...

]


[

a[m1,0]*b

a[m1,1]*b

...

a[m1,n1]*b

]

]

Example:
>>> d=diag([1,1])
>>> a=array([[1,2],[3,4]])
>>> kron(d,a)
array([[1, 2, 0, 0],
[3, 4, 0, 0],
[0, 0, 1, 2],
[0, 0, 3, 4]])
Corresponding method:
none
lexsort(keys=, axis=1)
Returns an array of indices similar to argsort,
except the sorting is done using the provided sorting keys. First the
sort is done using key[0], then the resulting list of indices is
further manipulated by sorting on key[1], and so forth. The result is
a sort on multiple keys. If the keys represented columns of a
spreadsheet, for example, this would sort using multiple columns.
The keys argument must be a sequence of things that can be converted to
arrays of the same shape.
Corresponding method:
none
linspace(start, stop, num=50, endpoint=True, retstep=False)
Returns evenly spaced floating point numbers.
Return num evenly spaced numbers from start to stop. If
endpoint is True, the last number is stop. If retstep is
True then return the step value used.
See also:
logspace
Corresponding method:
none
load(file)
Wrapper around cPickle.load which accepts either a filelike object or
a filename.
Corresponding method:
none
loads(string)
Loads a pickle from the given string
Corresponding method:
none
log2(x, y=None)
Returns the base 2 logarithm of x
If y is an array, the result replaces the contents of y.
Corresponding method:
none
logspace(start, stop, num=50, endpoint=True, base=10.0)
Evenly spaced numbers on a logarithmic scale.
Computes int(num) evenly spaced exponents from base**start to
base**stop. If endpoint=True, then last number is base**stop
See also:
linspace
Corresponding method:
none
mat(data, dtype=None) = asmatrix(data, dtype=None)
Returns 'data' as a matrix (twodim array). Unlike matrix(), no copy is performed
if 'data' is already a matrix or array. Equivalent to:
matrix(data, copy=False)
matrix(data, copy=True)
Returns 'data' as a matrix (twodim array). A copy is performed
if 'data' is already a matrix or array.
maximum_sctype(t)
Returns the scalar type of highest precision of the same general kind as 't'
Example:
>>> maximum_sctype(array((1., 2, 3+1j)))
<type 'complex128scalar'>
Corresponding method:
none
mean(a, axis=0, dtype=None)
Returns the arithmetic mean. Equivalent to average, except that no weights can be specified.
The method a.mean() has default axis None.
The mean is the sum of the elements divided by the number of elements.
Averaging is done over the given axis; if axis=None, all elements are averaged.
median(m)
Returns the median of m along the first dimension of m. There are as many values below
as there are above the median. If m contains an even number of items (along its first dimension),
the median is halfway between two successive values.
Examples:
>>> m=array((1,2,3,4,6,8))
>>> median(m)
3.5
meshgrid(x, y)
For vectors x, y with lengths Nx=len(x) and Ny=len(y), return X, Y
where X and Y are (Ny, Nx) shaped arrays with the elements of x
and y repeated to fill the matrix
Example:
>>> [X, Y] = meshgrid([1,2,3], [4,5,6,7])
>>> print X
[[1 2 3]
[1 2 3]
[1 2 3]
[1 2 3]]
>>> print Y
[[4 4 4]
[5 5 5]
[6 6 6]
[7 7 7]]
Corresponding method:
none
mintypecode(typechars, typeset='GDFgdf', default='d')
Returns a minimum data type character from typeset that
handles all typechars given.
The returned type character must be the smallest size such that
an array of the returned type can handle the data from an array of
type t for each t in typechars (or if typechars is an array,
then its dtype.char).
If the typechars does not intersect with the typeset, then default
is returned.
If t in typechars is not a string then t=asarray(t).dtype.char is
applied.
Corresponding method:
none
nanargmax(a, axis=1)
Finds the maximum over the given axis ignoring NaNs.
Corresponding method:
none
nanargmin(a, axis=1)
Finds the indices of the minimium over the given axis ignoring NaNs.
Corresponding method:
none
nanmax(a, axis=1)
Finds the maximum over the given axis ignoring NaNs.
Corresponding method:
none
nanmin(a, axis=1)
Finds the minimium over the given axis, ignoring NaNs.
Corresponding method:
none
nansum(a, axis=1)
Sums the array over the given axis, treating NaNs as 0.
Corresponding method:
none
ndim(a)
newbuffer(size)
Returns a new uninitialized buffer object of size bytes
nonzero(a)
Returns the indices of the elements of a which are not zero,
a must be 1d. Works also on sequences (lists and tuples). The method
a.nonzero() applies to any array.
Examples:
>>> a=array((0,1,2,0))
>>> nonzero(a)
array([1, 2])
>>> nonzero([0,1,2,0])
array([1, 2])
obj2sctype(rep, default=None)
ones(shape, dtype=None, order='C')
ones(shape, dtype=None) returns an array of the given
dimensions which is initialized to all ones (floats).
If you don't explicitly need the array to be initialized, you should instead
use empty, which is faster as it only allocates memory.
Example:
>>> a=ones((2,3))
array([[ 1., 1., 1.],
[ 1., 1., 1.]])
ones_like(a)
Returns an array of the same shape and typecode as a which
is initialized to all ones (floats).
If you don't explicitly need the array to be initialized, you should instead
use empty_like, which is faster as it only allocates memory.
outer(a, b)
outer(a,b) returns the outer product of two vectors.
result(i,j) = a(i)*b(j) when a and b are vectors
Will accept any arguments that can be made into vectors.
Example:
>>> a=array((1,2))
>>> b=array((3,4))
>>> outer(a,b)
array([[3, 4],
[6, 8]])
>>> outer(b,a)
array([[3, 6],
[4, 8]])
pade(an, m)
Given Taylor series coefficients in an, return a Pade approximation to
the function as the ratio of two polynomials p / q where the order of q is m.
piecewise(x, condlist, funclist, *args, **kw)
Return a piecewisedefined function.
Input:

x  the domain

condlist  a list of boolean arrays or a single boolean array
The length of the condition list must be n2 or n21 where n2
is the length of the function list. If len(condlist)==n21, then
an 'otherwise' condition is formed by 'ing all the conditions
and inverting.

funclist  a list of functions to call of length (n2).
Each function should return an array output for an array input
Each function can take (the same set) of extra arguments and
keyword arguments which are passed in after the function list.
A constant may be used in funclist for a function that returns a
constant (e.g. val and lambda x: val are equivalent in a funclist).
The output is the same shape and type as x and is found by
calling the functions on the appropriate portions of x.
Note:
This is similar to choose or select, except
that the functions are only evaluated on elements of x
that satisfy the corresponding condition.
The result is f1(x) for condition1, f2(x) for condition2, ...,
fn(x) for conditionn
poly(seq_of_zeros)
Returns a sequence representing a polynomial given a sequence of roots.
If the input is a matrix, return the characteristic polynomial.
Example:
>>> b = roots([1,3,1,5,6])
>>> poly(b)
array([1., 3., 1., 5., 6.])
polyadd(a1, a2)
Adds two polynomials represented as sequences
polyder(p, m=1)
Returns the mth derivative of the polynomial p.
polydiv(u, v)
Computes q and r polynomials so that u(s) = q(s)*v(s) + r(s)
and deg r < deg v.
polyfit(x, y, N)
Does a best fit polynomial of order N of y to x. Return value is a
vector of polynomial coefficients [pk ... p1 p0].
E.g., for N=2
p2*x0^2 + p1*x0 + p0 = y1
p2*x1^2 + p1*x1 + p0 = y1
p2*x2^2 + p1*x2 + p0 = y2
.....
p2*xk^2 + p1*xk + p0 = yk
Method:
if X is a the Vandermonde Matrix computed from x (see
http://mathworld.wolfram.com/VandermondeMatrix.html), then the
polynomial least squares solution is given by the 'p' in
X*p = y
where X is a len(x) * N+1 matrix, p is a N+1 length vector, and y
is a len(x) * 1 vector
This equation can be solved as
p = (XT*X)^1 * XT * y
where XT is the transpose of X and 1 denotes the inverse.
For more info, see
http://mathworld.wolfram.com/LeastSquaresFittingPolynomial.html,
but note the k's and n's in the superscripts and subscripts
on that page. The linear algebra is correct, however.
polyint(p, m=1, k=None)
Returns the mth analytical integral of the polynomial p.
If k is None, then zerovalued constants of integration are used.
otherwise, k should be a list of length m (or a scalar if m=1) to
represent the constants of integration to use for each integration
(starting with k[0])
polymul(a1, a2)
Multiplies two polynomials represented as sequences.
polysub(a1, a2)
Subtracts two polynomials represented as sequences
polyval(p, x)
Evaluate the polynomial p at x. If x is a polynomial then composition.
Description:
br>
If p is of length N, this function returns the value:
p[0]*(x**N1) + p[1]*(x**N2) + ... + p[N2]*x + p[N1]
x can be a sequence and p(x) will be returned for all elements of x,
or x can be another polynomial and the composite polynomial p(x) will be
returned.
Notice:
This can produce inaccurate results for polynomials with
significant variability. Use carefully.
prod(a, axis=0, dtype=None)
Returns the product of the elements along the given axis
Example:
>>> a
array([[1, 4],
[3, 2]])
>>> prod(a)
array([3, 8])
>>> prod(a,1)
array([4, 6])
product(x, axis=0, dtype=None)
Product of the array elements over the given axis. Is equivalent to prod.
ptp(a, axis=0)
Returns maximum  minimum along the the given dimension
put(a, ind, v)
Results in a[n] = v[n] for all n in ind.
If v is shorter than mask it will be repeated as necessary.
In particular v can be a scalar or length 1 array.
The routine put is the equivalent of the following (although the loop
is in C for speed):
ind = array(indices, copy=False)
v = array(values, copy=False).astype(a.dtype)
for i in ind: a.flat[i] = v[i]
a must be a contiguous numpy array.
For examples see the method a.put()
putmask(a, mask, v)
Results in a = v for all places where mask is true.
If v is shorter than mask it will be repeated as necessary.
In particular v can be a scalar or length 1 array.
For examples see the method a.putmask()
rand(d0, d1, ..., dn)
Returns an array of shape (d0, d1, ..., dn) which is initialized to
random numbers from a uniform distribution in the range [0,1).
rand() >
random values
Note:
This is a convenience function. If you want an
interface that takes a tuple as the first argument
use numpy.random.random_sample(shape_tuple).
randn(d0, d1, ..., dn)
Returns zeromean, unitvariance Gaussian random numbers in an
array of shape (d0, d1, ..., dn).
randn() >
random values
Note:
This is a convenience function. If you want an
interface that takes a tuple as the first argument
use numpy.random.standard_normal(shape_tuple).
rank(a)
Gets the rank of sequence a (the number of dimensions, not a matrix rank)
The rank of a scalar is zero.
ravel(m, order='C')
Returns a 1d array corresponding to all the elements of it's
argument. The new array is a view of m if possible, otherwise it is
a copy.
real(val)
Returns the real part of val as an array.
The argument val maybe a scalar or an array. See attribute a.real for
examples.
real_if_close(a, tol=100)
If a is a complex array, returns it as a real array if the imaginary
part is close enough to zero.
"Close enough" is defined as tol*(machine epsilon of a's element type).
repeat(a, repeats, axis=0)
Repeats elements of a repeats times along axis.
Repeats is a sequence of length a.shape[axis]
telling how many times to repeat each element.
If repeats is an integer, it is interpreted as
a tuple of length a.shape[axis] containing repeats.
The argument a can be anything array(a) will accept.
For examples see method .repeat().
repmat(a, m, n)
Repeats a 0d to 2d array m*n times
Example:
>>> m=matrix((1,2,3)).transpose()
>>> print m
[[1]
[2]
[3]]
>>> print repmat(m,1,3)
[[1 1 1]
[2 2 2]
[3 3 3]]
See also:
repeat
Corresponding method:
None
require(a, dtype=None, requirements=None)
reshape(a, newshape, order='C')
Changes the shape of a to newshape. Returns a new view object if possible
otherwise returns a copy. For examples see method .reshape().
resize(a, new_shape)
Returns a new array with the specified shape.
The original array's total size can be any size. It
fills the new array with repeated copies of a.
Note that the method a.resize(new_shape) will fill array with 0's
beyond current definition of a.
Example:
>>> print a
[[1 2 3]
[4 5 6]]
>>> print resize(a,(3,4))
[[1 2 3 4]
[5 6 1 2]
[3 4 5 6]]
restoredot(...)
restoredot() restores dots to defaults.
roots(p)
Returns the roots of the polynomial coefficients in p.
The values in the rank1 array p are coefficients of a polynomial.
If the length of p is n+1 then the polynomial is
p[0] * x**n + p[1] * x**(n1) + ... + p[n1]*x + p[n]
rot90(m, k=1)
Returns the array found by rotating m by k*90
degrees in the counterclockwise direction. Works on the first two
dimensions of m.
round_(a, decimals=0)
Rounds 'a' to the given number of decimal places. Equivalent to the array
function around. Rounding behaviour is equivalent to Python.
Returns 'a' if the array is not floating point. Rounds both the real
and imaginary parts separately if the array is complex.
Note the underscore behind 'round'! Round without underscore is a standard Python
function that acts on scalars only.
row_stack = vstack(tup)
Stacks arrays in sequence vertically (row wise)
Description:
Takes a sequence of arrays and stacks them vertically
to make a single array. All arrays in the sequence
must have the same shape along all but the first axis.
vstack will rebuild arrays divided by vsplit.
Arguments:

tup  sequence of arrays. All arrays must have the same
shape.
Examples:
>>> a = array((1,2,3))
>>> b = array((2,3,4))
>>> vstack((a,b))
array([[1, 2, 3],
[2, 3, 4]])
>>> a = array([[1],[2],[3]])
>>> b = array([[2],[3],[4]])
>>> vstack((a,b))
array([[1],
[2],
[3],
[2],
[3],
[4]])
sctype2char(sctype)
searchsorted(a, v)
select(condlist, choicelist, default=0)
Returns an array composed of different elements of choicelist
depending on the list of conditions.
Input:
 condlist is a list of condition arrays containing ones or zeros
 choicelist is a list of choice arrays (of the "same" size as the
arrays in condlist). The result array has the "same" size as the
arrays in choicelist. If condlist is [c0, ..., cN1] then choicelist
must be of length N. The elements of the choicelist can then be
represented as [v0, ..., vN1]. The default choice if none of the
conditions are met is given as the default argument.
The conditions are tested in order and the first one statisfied is
used to select the choice. In other words, the elements of the
output array are found from the following tree (notice the order of
the conditions matters):
if c0: v0
elif c1: v1
elif c2: v2
...
elif cN1: vN1
else: default
Note that one of the condition arrays must be large enough to handle
the largest array in the choice list.
set_numeric_ops(op=func, ...)
Sets some or all of the number methods for all
array objects. Don't forget **dict can be used as the argument list.
Returns the functions that were replaced  can be stored and set later.
set_printoptions(precision=None, threshold=None, edgeitems=None,
linewidth=None, suppress=None)
Sets options associated with printing.
Inputs:
 precision  the default number of digits of precision for floating
point output (default 8)
 threshold  total number of array elements which trigger summarization
rather than full repr. (default 1000)
 edgeitems  number of array items in summary at beginning and end of
each dimension. (default 3)
 linewidth  the number of characters per line for the purpose of inserting
line breaks. (default 75)
 suppress  Boolean value indicating whether or not suppress printing
of small floating point values using scientific notation (default False)
set_string_function(f, repr=1)
Sets the python function f to be the function
used to obtain a pretty printable string version of an array whenever an array
is printed. f(M) should expect an array argument M, and should return a string
consisting of the desired representation of M for printing.
setbufsize(size)
Sets the size of the buffer used in ufuncs.
setdiff1d(ar1, ar2)
Sets difference of 1D arrays with unique elements.
seterr(divide=None, over=None, under=None, invalid=None)
Sets how floatingpoint errors are handled.
Valid values for each type of error are the strings
"ignore", "warn", "raise", and "call". Returns the old settings.
Note that operations on integer scalar types (such as int16) are
handled like floating point, and are affected by these settings.
Example:
>>> seterr(over='raise')
{'over': 'ignore', 'divide': 'ignore', 'invalid': 'ignore', 'under': 'ignore'}
>>> int16(32000) * int16(3)
Traceback (most recent call last):
File "
<stdin>
", line 1, in ?
FloatingPointError: overflow encountered in short_scalars
seterrcall(func)
Sets the callback function used when a floatingpoint error handler
is set to 'call'.
'func' should be a function that takes two arguments. The first is
type of error ("divide", "over", "under", or "invalid"), and the second
is the status flag (= divide + 2*over + 4*under + 8*invalid).
Returns the old handler.
seterrobj(...)
setmember1d(ar1, ar2)
Returns an array of shape of ar1 containing 1 where the elements of
ar1 are in ar2 and 0 otherwise.
setxor1d(ar1, ar2)
Sets exclusiveor of 1D arrays with unique elements.
shape(a)
Returns the shape of a (as a function call which
also works on nested sequences).
Examples:
>>> a=[[1,2,3],[4,5,6]]
>>> b=array(a)
>>> c=array((1,2,3))
>>> d=array([[1,2,3]])
>>> print shape(a), shape(b), shape(c), shape(d)
(2, 3) (2, 3) (3,) (1, 3)
show_config()
Shows information on availability of scipy subpackages. No arguments.
sinc(x)
Returns sin(pi*x)/(pi*x) at all points of array x. Beware of the
multiplication by pi!
Example:
(prints extrema of sinc)
>>>
a=0.5*array([0]+range(3,10,2))
>>>
print a
[ 0. 1.5 2.5 3.5 4.5]
>>>
print sinc(a)
[ 1. 0.21220659 0.12732395 0.09094568 0.07073553]
size(a, axis=None)
Gets the number of elements in sequence a, or along a certain axis.
Example:
>>> a=array([[1,2,3],[4,5,6]])
>>> print size(a), size(a,0), size(a,1)
6 2 3
>>> print shape(a)
(2, 3)
>>> print len(a), alen(a)
2 2
sometrue(x, axis=0)
Performs a logical_or over the given axis.
sort(a, axis=1)
Returns array with elements sorted along given axis.
Example:
>>> a=array([[3,1,5],[2,6,4]])
>>> print a
[[3 1 5]
[2 6 4]]
>>> print sort(a)
[[1 3 5]
[2 4 6]]
>>> print sort(a,0)
[[2 1 4]
[3 6 5]]
sort_complex(a)
Sort 'a' as a complex array using the real part first and then
the imaginary part if the real part is equal (the default sort order
for complex arrays). This function is a wrapper ensuring a complex
return type.
source(object, output=<idlelib.rpc.RPCProxy instance>)
Write source for this object to output.
split(ary, indices_or_sections, axis=0)
Divide an array into a list of subarrays.
Description:
Divide ary into a list of subarrays along the
specified axis. If indices_or_sections is an integer,
ary is divided into that many equally sized arrays.
If it is impossible to make an equal split, an error is
raised. This is the only way this function differs from
the array_split() function. If indices_or_sections is a
list of sorted integers, its entries define the indexes
where ary is split.
Input:
 ary  Array to be divided into subarrays.
 indices_or_sections  integer or 1D array.
If integer, defines the number of (close to) equal sized
subarrays. If it is a 1D array of sorted indices, it
defines the indexes at which ary is divided. Any empty
list results in a single subarray equal to the original
array.
 axis  integer. default=0.
Specifies the axis along which to split ary.
Caveats:
Currently, the default for axis is 0. This
means a 2D array is divided into multiple groups
of rows. This seems like the appropriate default, but
we've agreed most other functions should default to
axis=1. Perhaps we should use axis=1 for consistency.
However, we could also make the argument that NumPy
works on "rows" by default. sum() sums up rows of
values. split() will split data into rows. Opinions?
squeeze(a)
Returns a with any ones from the shape of a removed
Example:
>>> a=array([[1,2,3]])
>>> at=a.transpose()
>>> print a
[[1 2 3]]
>>> print squeeze(a)
[1 2 3]
>>> print at
[[1]
[2]
[3]]
>>> squeeze(at)
array([1, 2, 3])
std(a, axis=0, dtype=None)
Returns the standard deviation of the elements of a.
The standard deviation is the square root of the variance var; var is the
average of the squared deviations from the mean, i.e.
std = sqrt(mean((x  x.mean())**2)).
Note:
var is really the meansquare deviation from the mean and
not
the unbiased
expectation of the variance of the underlying distribution, which equals n/(n1)*var
for uncorrelated samples. Likewise std is the rms (rootmeansquare) deviation from
the mean, and not the unbiased estimate of the standard deviation of the
distribution, which equals std*sqrt(n/(n1)).
sum(x, axis=0, dtype=None)
Sums the array over the given axis. The optional dtype argument
is the data type for intermediate calculations.
The default is to upcast (promote) smaller integer types to the
platformdependent Int. For example, on 32bit platforms:
x.dtype

default sum() dtype

bool, Int8, Int16, Int32

Int32

Examples:
>>> sum([0.5, 1.5])
2.0
>>> sum([0.5, 1.5], dtype=Int32)
1
>>> sum([[0, 1], [0, 5]])
array([0, 6])
>>> sum([[0, 1], [0, 5]], axis=1)
array([1, 5])
swapaxes(a, axis1, axis2)
Returns array a with axis1 and axis2 interchanged.
Note:
For a twodimensional array swapaxes(a,0,1) is equivalent to
transpose(a). swapaxes swaps two axes, while transpose is able to
permute all axes.
take(a, indices, axis=0)
test(level=1, verbosity=1)
Runs Scipy tests suite with level and verbosity.
trace(a, offset=0, axis1=0, axis2=1, dtype=None)
Returns the sum along diagonals
(defined by the last two dimensions) of the array.
transpose(a, axes=None)
Returns a view of the array with
dimensions permuted according to axes. axes is a tuple indicating the permuted
sequence of dimensions. If axes is None
(default) the array a is returned with dimensions reversed.
Note:
For a twodimensional array transpose(a) is equivalent to
swapaxes(a,0,1).
Example:
>>> a=array([[[1,2,3],[4,5,6]],[[1,2,3],[4,5,6]]])
>>> print a
[[[ 1 2 3]
[ 4 5 6]]
[[1 2 3]
[4 5 6]]]
>>> print transpose(a,[2,0,1])
[[[ 1 4]
[1 4]]
[[ 2 5]
[2 5]]
[[ 3 6]
[3 6]]]
trapz(y, x=None, dx=1.0, axis=1)
Integrates y(x) using samples along the given axis and the composite
trapezoidal rule. If x is None, spacing given by dx is assumed.
Example
Integrate f(x)=x**2 from 0 to 100: exact value is 333333.3....
>>> x=arange(101)
>>> y=x*x
>>> trapz(y)
333350.0
tri(N, M=None, k=0, dtype=<type 'float'>)
Returns a NbyM array where all the diagonals starting from
lower left corner up to the kth are all ones.
tril(m, k=0)
Returns the elements on and below the kth diagonal of matrix m. k=0 is the
main diagonal, k > 0 is above and k < 0 is below the main diagonal.
Example:
>>> a=array([[1,2,3],[4,5,6],[7,8,9]])
>>> print a
[[1 2 3]
[4 5 6]
[7 8 9]]
>>> print tril(a)
[[1 0 0]
[4 5 0]
[7 8 9]]
>>> print tril(a,1)
[[1 2 0]
[4 5 6]
[7 8 9]]
trim_zeros(filt, trim='fb')
Trims the leading and trailing zeros from a 1D array.
Example:
>>> a = array((0, 0, 0, 1, 2, 3, 2, 1, 0))
>>> trim_zeros(a)
array([1, 2, 3, 2, 1])
triu(m, k=0)
returns the elements on and above the kth diagonal of m. k=0 is the
main diagonal, k > 0 is above and k < 0 is below the main diagonal.
typename(char)
Returns an english description for the given data type character.
Examples:
>>> for c in ('b','i','l','f','d','g','h','q'): print c, typename(c)
b signed char
i integer
l long integer
f single precision
d double precision
g long precision
h short
q long long integer
unique(x)
Returns sorted unique items from an array or sequence.
Example:
>>> unique([5,2,4,0,4,4,2,2,1])
array([0,1,2,4,5])
unique1d(ar1, retindx=False)
Unique elements of 1D array. When ret_indx is True, return also the
indices indx such that ar1.flat[indx] is the resulting array of unique
elements.
unravel_index(x, dims)
Convert a flat index into an index tuple for an array of given shape.
e.g. for a 2x2 array, unravel_index(2,(2,2)) returns (1,0).
Example:
>>> x=array([[1,3,7],[4,2,5]])
>>> p=x.argmax()
>>> unravel_index(p,x.shape)
>>> print p, idx, x[idx], x.max()
2 (0, 2) 7 7
Note:
x.flat[p] == x.max()
Thus, it may be easier to use flattened indexing than to remap
the index to a tuple.
unwrap(p, discont=3.1415926535897931, axis=1)
Unwrap radian phase p by changing absolute jumps greater than
'discont' to their 2*pi complement along the given axis.
vander(x, N=None)
Returns the Vandermonde matrix X of vector x. The ith column of X is the
the ith power of x. N is the maximum power to compute; if N is
None it defaults to len(x).
Example:
>>> x=arange(1.,5.,1.)
>>> print x
[ 1. 2. 3. 4.]
>>> print vander(x)
[[ 1. 1. 1. 1.]
[ 8. 4. 2. 1.]
[ 27. 9. 3. 1.]
[ 64. 16. 4. 1.]]
var(a, axis=0, dtype=None)
Returns the variance of the elements of a.
var is the average of the squared deviations from the mean, i.e.
var = mean((x  x.mean())**2).
Note:
var is really the meansquare deviation from the mean and
not
the unbiased
expectation of the variance of the underlying distribution, which equals n/(n1)*var
for uncorrelated samples.
vdot(a,b)
Returns the dot product of a and b for scalars and vectors
of floating point and complex types. The first argument, a, is conjugated,
i.e., the signs of its imaginary parts are reversed.
vsplit(ary, indices_or_sections)
Splits ary into multiple rows of subarrays
Description:
Splits a single array into multiple sub arrays. The array is
divided into groups of rows. If indices_or_sections is
an integer, ary is divided into that many equally sized sub arrays.
If it is impossible to make the subarrays equally sized, the
operation throws a ValueError exception. See array_split and
split for other options on indices_or_sections.
Input:
 ary  array to be divided into subarrays.
 indices_or_sections  integer or 1D array.
If integer, defines the number of (close to) equal sized
subarrays. If it is a 1D array of sorted indices, it
defines the indexes at which ary is divided. Any empty
list results in a single subarray equal to the original
array.
Returns:
sequence of subarrays. The returned arrays have the same
number of dimensions as the input array.
Caveats:
How should we handle 1D arrays here? I am currently raising
an error when I encounter them. Any better approach?
Should we reduce the returned array to their minium dimensions
by getting rid of any dimensions that are 1?
Example:
>>> a=array([[1,2,3,4],[1,2,3,4]])
>>> vsplit(a,2)
[array([[1, 2, 3, 4]]), array([[1, 2, 3, 4]])]
vstack(tup)
Stacks arrays in sequence vertically (row wise)
Description:
Takes a sequence of arrays and stacks them vertically
to make a single array. All arrays in the sequence
must have the same shape along all but the first axis.
vstack will rebuild arrays divided by vsplit.
Input:
 tup  sequence of arrays. All arrays must have the same
shape.
Examples:
>>> a=array((1,2,3))
>>> b=array((4,5,6))
>>> vstack((a,b))
array([[1, 2, 3],
[4, 5, 6]])
>>> a = array([[1],[2],[3]])
>>> b = array([[2],[3],[4]])
>>> vstack((a,b))
array([[1],
[2],
[3],
[2],
[3],
[4]])
where(condition,  x, y)
Returns array that is shaped like condition and has elements of
x and y where condition is respectively true or false. If x or y are
not given, then it is equivalent to condition.nonzero().
To group the indices by element, rather than dimension, use
transpose(where(condition,  x, y))
instead. The result of this is always a 2d array, with a row of indices
for each element that satisfies the condition.
who(vardict=None)
Print the scipy arrays in the given dictionary (or globals() if None).
zeros(shape, dtype=float, order='C')
Returns an array of zeros of the specified shape and typecode.
If you don't explicitly need the array to be zeroed, you should instead
use empty, which is faster as it only allocates memory.
zeros_like(a)
Return an array of zeros of the shape and typecode of a.
If you don't explicitly need the array to be zeroed, you should instead
use empty_like, which is faster as it only allocates memory.
SCIPY SUBPACKAGES
Here the content information from the files info.py of the different
subpackages of scipy is given. This gives the names of the functions available
in the subpackages. A short description of each function is obtained after importing
the subpackage by typing info(subpackage.function).
Example:
>>> import linalg as la
>>> info(la.inv)
inv(a, overwrite_a=0)
inv(a, overwrite_a=0) > a_inv
Return inverse of square matrix a.
The following scipy subpackages are available:
cluster
Vector Quantization / Kmeans
============================
Clustering Algorithms are useful in Information Theory, target detection,
communications, compression, and other areas. Currently only Vector
Quantization and the KMeans algorithm are supported by the vq module.
Self Organized Feature Maps (SOM) and other approaches are also scheduled
to appear at a theater near you.
fftpack
Discrete Fourier Transform algorithms
=====================================
Fast Fourier Transforms:
fft

FFT of arbitrary type periodic sequences

ifft

Inverse of fft

fftn

Multidimensional FFT

ifftn

Inverse of fftn

fft2

Twodimensional FFT

ifft2

Inverse of fft2

rfft

FFT of real periodic sequences

irfft

Inverse of rfft

Differential and pseudodifferential operators:
diff

Differentiation and integration of periodic sequences

tilbert

Tilbert transform: cs_diff(x,h,h)

itilbert

Inverse Tilbert transform: sc_diff(x,h,h)

hilbert

Hilbert transform: cs_diff(x,inf,inf)

ihilbert

Inverse Hilbert transform: sc_diff(x,inf,inf)

cs_diff

cosh/sinh pseudoderivative of periodic sequences

sc_diff

sinh/cosh pseudoderivative of periodic sequences

ss_diff

sinh/sinh pseudoderivative of periodic sequences

cc_diff

cosh/cosh pseudoderivative of periodic sequences

shift

Shift periodic sequences

Helper functions:
fftshift

Shift zerofrequency component to center of spectrum

ifftshift

Inverse of freqshift

dftfreq

DFT sample frequencies

rfftfreq

DFT sample frequencies(specific to rfft,irfft)

Extension modules:
_fftpack

Provides functions zfft, drfft, zrfft, zfftnd,
destroy_*_cache

convolve

Provides functions convolve, convolve_z,
init_convolution_kernel, destroy_convolve_cache

integration
Integration routines
====================
Methods for Integrating Functions given function object.
quad

General purpose integration.

dblquad

General purpose double integration.

tplquad

General purpose triple integration.

fixed_quad

Integrate func(x) using Gaussian quadrature of order n.

quadrature

Integrate with given tolerance using Gaussian quadrature.

romberg

Integrate func using Romberg integration.

Methods for Integrating Functions given fixed samples.
trapz

Use trapezoidal rule to compute integral from samples.

cumtrapz

Use trapezoidal rule to cumulatively compute integral.

simps

Use Simpson's rule to compute integral from samples.

romb

Use Romberg Integration to compute integral from
(2**k + 1) evenlyspaced samples.

See the special module's orthogonal polynomials (special) for Gaussian
quadrature roots and weights for other weighting factors and regions.
Interface to numerical integrators of ODE systems.
odeint

General integration of ordinary differential equations.

ode

Integrate ODE using vode routine.

interpolation
Interpolation Tools
===================
Wrappers around FITPACK functions:
splrep

find smoothing spline given (x,y) points on curve.

splprep

find smoothing spline given parametrically defined curve.

splev

evaluate the spline or its derivatives.

splint

compute definite integral of a spline.

sproot

find the roots of a cubic spline.

spalde

compute all derivatives of a spline at given points.

bisplrep

find bivariate smoothing spline representation.

bisplev

evaluate bivariate smoothing spline.

Interpolation Class
interp1d

Create a class whose instances can linearly interpolate
to compute unknown values.

io
Data input and output
=====================
Classes
fopen

a class for easily reading and writing binary data.

Functions
read_array

reading ascii streams into Numeric arrays

write_array

write an array to an ascii stream

loadmat

read a MATLAB style mat file (version 4 and 5)

savemat

write a MATLAB (version < 4) style mat file

fread

lowlevel reading

fwrite

lowlevel writing

bswap

inplace byteswapping

packbits

Pack a binary array of 1's and 0's into an array of bytes

unpackbits

Unpack an array packed by packbits.

save

simple storing of Python dictionary into module
that can then be imported and the data accessed as
attributes of the module.

mminfo

query matrix info from Matrix Market formatted file

mmread

read matrix from Matrix Market formatted file

mmwrite

write matrix to Matrix Market formatted file

lib
Python wrappers to external libraries
=====================================
lapack

wrappers for LAPACK/ATLAS libraries

blas

wrappers for BLAS/ATLAS libraries

linalg
Linear algebra routines
=======================
Linear Algebra Basics:
inv

Find the inverse of a square matrix

solve

Solve a linear system of equations

solve_banded

Solve a linear system of equations with a banded matrix

det

Find the determinant of a square matrix

norm

matrix and vector norm

lstsq

Solve linear leastsquares problem

pinv

Pseudoinverse (MoorePenrose) using lstsq

pinv2

Pseudoinverse using svd

Eigenvalues and Decompositions:
eig

Find the eigenvalues and vectors of a square matrix

eigvals

Find the eigenvalues of a square matrix

eig_banded

Find the eigenvalues and vectors of a band matrix

eigvals_banded

Find the eigenvalues of a band matrix

lu

LU decomposition of a matrix

lu_factor

LU decomposition returning unordered matrix and pivots

lu_solve

solve Ax=b using back substitution with output of lu_factor

svd

Singular value decomposition of a matrix

svdvals

Singular values of a matrix

diagsvd

construct matrix of singular values from output of svd

orth

construct orthonormal basis for range of A using svd

cholesky

Cholesky decomposition of a matrix

cho_factor

Cholesky decomposition for use in solving linear system

cho_solve

Solve previously factored linear system

qr

QR decomposition of a matrix

schur

Schur decomposition of a matrix

rsf2csf

Real to complex schur form

hessenberg

Hessenberg form of a matrix

matrix Functions:
expm2

matrix exponential using Eigenvalue decomp.

expm3

matrix exponential using Taylorseries expansion

logm

matrix logarithm

cosm

matrix cosine

sinm

matrix sine

tanm

matrix tangent

coshm

matrix hyperbolic cosine

sinhm

matrix hyperbolic sine

tanhm

matrix hyperbolic tangent

signm

matrix sign

sqrtm

matrix square root

funm

Evaluating an arbitrary matrix function.

Iterative linear systems solutions
cg

Conjugate gradient (symmetric systems only)

cgs

Conjugate gradient squared

qmr

Quasiminimal residual

gmres

Generalized minimal residual

bicg

Biconjugate gradient

bicgstab

Biconjugate gradient stabilized

linsolve
Linear Solvers
==============
linear solvers for sparse matrices: in development
maxentropy
Routines for fitting maximum entropy models
===========================================
Contains two classes for fitting maximum entropy models subject to linear
constraints on the expectations of arbitrary feature statistics. One
class, "model", is for small discrete sample spaces, using explicit
summation. The other, "bigmodel", is for sample spaces that are either
continuous (and perhaps highdimensional) or discrete but too large to
sum over, and uses importance sampling. conditional Monte Carlo methods.
The maximum entropy model has exponential form
p(x) = exp(theta^T . f_vec(x)) / Z(theta).
with a real parameter vector theta of the same length as the feature
statistic f_vec. For more background, see, for example, Cover and
Thomas (1991), Elements of Information Theory.
See the file bergerexample.py for a walkthrough of how to use these
routines when the sample space is small enough to be enumerated.
See bergerexamplesimulated.py for a a similar walkthrough using
simulation.
Copyright: Ed Schofield, 20032006
License: BSDstyle (see LICENSE.txt in main source directory)
misc
Various utilities that don't have another home.
ndimage
ndimensional image package
===========================
This package contains various functions for multidimensional image processing.
optimize
Optimization Tools
==================
A collection of generalpurpose optimization routines.
fmin

NelderMead Simplex algorithm
(uses only function calls)

fmin_powell

Powell's (modified) level set method (uses only
function calls)

fmin_cg

Nonlinear (PolakRibiere) conjugate gradient algorithm
(can use function and gradient).

fmin_bfgs

QuasiNewton method (BroydonFletcherGoldfarbShanno);
(can use function and gradient)

fmin_ncg

Linesearch Newton Conjugate Gradient (can use
function, gradient and Hessian).

leastsq

Minimize the sum of squares of M equations in
N unknowns given a starting estimate.

Constrained Optimizers (multivariate)
fmin_l_bfgs_b

Zhu, Byrd, and Nocedal's LBFGSB constrained optimizer
(if you use this please quote their papers  see help)

fmin_tnc

Truncated Newton Code originally written by Stephen Nash and
adapted to C by JeanSebastien Roy.

fmin_cobyla

Constrained Optimization BY Linear Approximation

Global Optimizers
anneal

Simulated Annealing

brute

Brute force searching optimizer

Scalar function minimizers
fminbound

Bounded minimization of a scalar function.

brent

1D function minimization using Brent method.

golden

1D function minimization using Golden Section method

bracket

Bracket a minimum (given two starting points)

Also a collection of generalpurpose rootfinding routines.
fsolve

Nonlinear multivariable equation solver.

Scalar function solvers
brentq

quadratic interpolation Brent method

brenth

Brent method (modified by Harris with hyperbolic
extrapolation)

ridder

Ridder's method

bisect

Bisection method

newton

Secant method or Newton's method

fixed_point

Singlevariable fixedpoint solver.

Utility Functions
line_search

Return a step that satisfies the strong Wolfe conditions.

check_grad

Check the supplied derivative using finite difference
techniques.

sandbox
Sandbox:
A repository of unused routines.
signal
Signal Processing Tools
===========================
Convolution:
convolve

Ndimensional convolution.

correlate

Ndimensional correlation.

fftconvolve

Ndimensional convolution using the FFT.

convolve2d

2dimensional convolution (more options).

correlate2d

2dimensional correlation (more options).

sepfir2d

Convolve with a 2D separable FIR filter.

Bsplines:
bspline

Bspline basis function of order n.

gauss_spline

Gaussian approximation to the Bspline basis function.

cspline1d

Coefficients for 1D cubic (3rd order) Bspline.

qspline1d

Coefficients for 1D quadratic (2nd order) Bspl

cspline2d

Coefficients for 2D cubic (3rd order) Bspline.

qspline2d

Coefficients for 2D quadratic (2nd order) Bspline.

spline_filter

Smoothing spline (cubic) filtering of a rank2 array.

Filtering:
order_filter

Ndimensional order filter.

medfilt

Ndimensional median filter.

medfilt2

2dimensional median filter (faster).

wiener

Ndimensional wiener filter.

symiirorder1

2ndorder IIR filter (cascade of firstorder systems).

symiirorder2

4thorder IIR filter (cascade of secondorder systems).

lfilter

1dimensional FIR and IIR digital linear filtering.

deconvolve

1d deconvolution using lfilter.

hilbert

Compute the analytic signal of a 1d signal.

get_window

Create FIR window.

detrend

Remove linear and/or constant trends from data.

Filter design:
remez

Optimal FIR filter design.

firwin

Windowed FIR filter design.

iirdesign

IIR filter design given bands and gains

iirfilter

IIR filter design given order and critical frequencies

freqs

Analog filter frequency response

freqz

Digital filter frequency response

Matlabstyle IIR filter design:
butter (buttord)

Butterworth

cheby1 (cheb1ord)

Chebyshev Type I

cheby2 (cheb2ord)

Chebyshev Type II

ellip (ellipord)

Elliptic (Cauer)

bessel

Bessel (no order selection available  try butterod)

Linear Systems:
lti

linear time invariant system object.

lsim

continuoustime simulation of output to linear system.

impulse

impulse response of linear, timeinvariant (LTI) system.

step

step response of continoustime LTI system.

LTI Representations:
tf2zpk

transfer function to zeropolegain.

zpk2tf

zeropolegain to transfer function.

tf2ss

transfer function to statespace.

ss2tf

statepace to transfer function.

zpk2ss

zeropolegain to statespace.

ss2zpk

statespace to polezerogain.

Waveforms:
sawtooth

Periodic sawtooth

square

Square wave

gausspulse

Gaussian modulated sinusoid

chirp

Frequency swept cosine signal

Wavelets:
daub

return lowpass filter for daubechies wavelets

qmf

return quadrature mirror filter from lowpass

cascade

compute scaling function and wavelet from coefficients

sparse
Sparse matrix
=============
Scipy 2D sparse matrix module.
Original code by Travis Oliphant.
Modified and extended by Ed Schofield and Robert Cimrman.
There are four available sparse matrix types:
(1) csc_matrix: Compressed Sparse Column format
(2) csr_matrix: Compressed Sparse Row format
(3) lil_matrix: List of Lists format
(4) dok_matrix: Dictionary of Keys format
To construct a matrix efficiently, use either lil_matrix (recommended) or
dok_matrix. The lil_matrix class supports basic slicing and fancy
indexing with a similar syntax to NumPy arrays.
To perform manipulations such as multiplication or inversion, first
convert the matrix to either CSC or CSR format. The lil_matrix format is
rowbased, so conversion to CSR is efficient, whereas conversion to CSC
is less so.
Example:
Construct a 10x1000 lil_matrix and add some values to it:
>>> from scipy import sparse, linsolve
>>> from numpy import rand, linalg
>>> A = sparse.lil_matrix((1000, 1000))
>>> A[0, :100] = rand(100)
>>> A[1, 100:200] = A[0, :100]
>>> A.setdiag(rand(1000))
Now convert it to CSR format and solve (A A^T) x = b for x:
>>> A = A.tocsr()
>>> b = rand(1000)
>>> x = linsolve.spsolve(A * A.T, b)
Convert it to a dense matrix and solve, and check that the result
is the same:
>>> A_ = A.todense()
>>> x_ = linalg.solve(A_ * A_.T, b)
>>> err = linalg.norm(xx_)
Now we can print the error norm with:
print "Norm error =", err
It should be small :)
special
Special Functions
=================
Airy Functions
airy

Airy functions and their derivatives.

airye

Exponentially scaled Airy functions

ai_zeros

**Zeros of Airy functions Ai(x) and Ai'(x)

bi_zeros

**Zeros of Airy functions Bi(x) and Bi'(x)

Elliptic Functions and Integrals
ellipj

Jacobian elliptic functions

ellipk

Complete elliptic integral of the first kind.

ellipkinc

Incomplete elliptic integral of the first kind.

ellipe

Complete elliptic integral of the second kind.

ellipeinc

Incomplete elliptic integral of the second kind.

Bessel Functions
jn

Bessel function of integer order and real argument.

jv

Bessel function of realvalued order and complex argument.

jve

Exponentially scaled Bessel function.

yn

Bessel function of second kind (integer order).

yv

Bessel function of the second kind (realvalued order).

yve

Exponentially scaled Bessel function of the second kind.

kn

Modified Bessel function of the third kind (integer order).

kv

Modified Bessel function of the third kind (real order).

kve

Exponentially scaled modified Bessel function of the third kind.

iv

Modified Bessel function.

ive

Exponentially scaled modified Bessel function.

hankel1

Hankel function of the first kind.

hankel1e

Exponentially scaled Hankel function of the first kind.

hankel2

Hankel function of the second kind.

hankel2e

Exponentially scaled Hankel function of the second kind.

lmbda

**Sequence of lambda functions with arbitrary order v.

Zeros of Bessel Functions
jnjnp_zeros

**Zeros of integerorder Bessel functions and derivatives
sorted in order.

jnyn_zeros

**Zeros of integerorder Bessel functions and derivatives
as separate arrays.

jn_zeros

**Zeros of Jn(x)

jnp_zeros

**Zeros of Jn'(x)

yn_zeros

**Zeros of Yn(x)

ynp_zeros

**Zeros of Yn'(x)

y0_zeros

**Complex zeros: Y0(z0)=0 and values of Y0'(z0)

y1_zeros

**Complex zeros: Y1(z1)=0 and values of Y1'(z1)

y1p_zeros

**Complex zeros of Y1'(z1')=0 and values of Y1(z1')

Faster versions of common Bessel Functions.
j0

Bessel function of order 0.

j1

Bessel function of order 1.

y0

Bessel function of second kind of order 0.

y1

Bessel function of second kind of order 1.

i0

Modified Bessel function of order 0.

i0e

Exponentially scaled modified Bessel function of order 0.

i1

Modified Bessel function of order 1.

i1e

Exponentially scaled modified Bessel function of order 1.

k0

Modified Bessel function of the third kind of order 0.

k0e

Exponentially scaled modified Bessel function of the
third kind of order 0.

k1

Modified Bessel function of the third kind of order 1.

k1e

Exponentially scaled modified Bessel function of the
third kind of order 1.

Integrals of Bessel Functions.
itj0y0

Basic integrals of j0 and y0 from 0 to x.

it2j0y0

Integrals of (1j0(t))/t from 0 to x and
y0(t)/t from x to inf.

iti0k0

Basic integrals of i0 and k0 from 0 to x.

it2i0k0

Integrals of (i0(t)1)/t from 0 to x and
k0(t)/t from x to inf.

besselpoly

Integral of a bessel function: Jv(2*a*x) * x**lambda
from x=0 to 1.

Derivatives of Bessel Functions.
jvp

Nth derivative of Jv(v,z)

yvp

Nth derivative of Yv(v,z)

kvp

Nth derivative of Kv(v,z)

ivp

Nth derivative of Iv(v,z)

h1vp

Nth derivative of H1v(v,z)

h2vp

Nth derivative of H2v(v,z)

Spherical Bessel Functions
sph_jn

**Sequence of spherical Bessel functions, jn(z)

sph_yn

**Sequence of spherical Bessel functions, yn(z)

sph_jnyn

**Sequence of spherical Bessel functions, jn(z) and yn(z)

sph_in

**Sequence of spherical Bessel functions, in(z)

sph_kn

**Sequence of spherical Bessel functions, kn(z)

sph_inkn

**Sequence of spherical Bessel functions, in(z) and kn(z)

RicattiBessel Functions
riccati_jn

**Sequence of RicattiBessel functions of first kind.

riccati_yn

**Sequence of RicattiBessel functions of second kind.

Struve Functions
struve

Struve function  Hv(x)

modstruve

Modified struve function  Lv(x)

itstruve0

Integral of H0(t) from 0 to x

it2struve0

Integral of H0(t)/t from x to Inf.

itmodstruve0

Integral of L0(t) from 0 to x.

Raw Statistical Functions (Friendly versions in scipy.stats)
bdtr

Sum of terms 0 through k of of the binomial pdf.

bdtrc

Sum of terms k+1 through n of the binomial pdf.

bdtri

Inverse of bdtr

btdtr

Integral from 0 to x of beta pdf.

btdtri

Quantiles of beta distribution

fdtr

Integral from 0 to x of F pdf.

fdtrc

Integral from x to infinity under F pdf.

fdtri

Inverse of fdtrc

gdtr

Integral from 0 to x of gamma pdf.

gdtrc

Integral from x to infinity under gamma pdf.

gdtri

Quantiles of gamma distribution

nbdtr

Sum of terms 0 through k of the negative binomial pdf.

nbdtrc

Sum of terms k+1 to infinity under negative binomial pdf.

nbdtri

Inverse of nbdtr

pdtr

Sum of terms 0 through k of the Poisson pdf.

pdtrc

Sum of terms k+1 to infinity of the Poisson pdf.

pdtri

Inverse of pdtr

stdtr

Integral from infinity to t of the Studentt pdf.

stdtri

Inverse of stdtr (quantiles)

chdtr

Integral from 0 to x of the Chisquare pdf.

chdtrc

Integral from x to infnity of Chisquare pdf.

chdtri

Inverse of chdtrc.

ndtr

Integral from infinity to x of standard normal pdf

ndtri

Inverse of ndtr (quantiles)

smirnov

KolmogorovSmirnov complementary CDF for onesided
test statistic (Dn+ or Dn)

smirnovi

Inverse of smirnov.

kolmogorov

The complementary CDF of the (scaled) twosided test
statistic (Kn*) valid for large n.

tklmbda

TukeyLambda CDF

Gamma and Related Functions
gamma

Gamma function.

gammaln

Log of the absolute value of the gamma function.

gammainc

Incomplete gamma integral.

gammaincinv

Inverse of gammainc.

gammaincc

Complemented incomplete gamma integral.

gammainccinv

Inverse of gammaincc.

beta

Beta function.

betaln

Log of the absolute value of the beta function.

betainc

Incomplete beta integral.

betaincinv

Inverse of betainc.

betaincinva

Inverse (in first argument, a) of betainc

betaincinvb

Inverse (in first argument, b) of betainc

psi(digamma)

Logarithmic derivative of the gamma function.

rgamma

One divided by the gamma function.

polygamma

Nth derivative of psi function.

Error Function and Fresnel Integrals
erf

Error function.

erfc

Complemented error function (1 erf(x))

erfinv

Inverse of error function

erfcinv

Inverse of erfc

erf_zeros

**Complex zeros of erf(z)

fresnel

Fresnel sine and cosine integrals.

fresnel_zeros

Complex zeros of both Fresnel integrals

fresnelc_zeros

**Complex zeros of fresnel cosine integrals

fresnels_zeros

**Complex zeros of fresnel sine integrals

modfresnelp

Modified Fresnel integrals F_+(x) and K_+(x)

modfresnelm

Modified Fresnel integrals F_(x) and K_(x)

Legendre Functions
lpn

**Legendre Functions (polynomials) of the first kind

lqn

**Legendre Functions of the second kind.

lpmn

**Associated Legendre Function of the first kind.

lqmn

**Associated Legendre Function of the second kind.

lpmv

Associated Legendre Function of arbitrary nonnegative
degree v.

sph_harm

Spherical Harmonics (complexvalued) Y^m_n(theta,phi)

Orthogonal polynomials  15 types
** These functions all return a polynomial class which can then be
evaluated: vals = chebyt(n)(x)
This class also has an attribute 'weights' which
return the roots, weights, and total weights for the appropriate
form of Gaussian quadrature. These are returned in an n x 3 array with roots
in the first column, weights in the second column, and total weights in the final
column
legendre

**Legendre polynomial P_n(x) (lpn for function).

chebyt

**Chebyshev polynomial T_n(x)

chebyu

**Chebyshev polynomial U_n(x)

chebyc

**Chebyshev polynomial C_n(x)

chebys

**Chebyshev polynomial S_n(x)

jacobi

**Jacobi polynomial P^(alpha,beta)_n(x)

laguerre

**Laguerre polynomial, L_n(x)

genlaguerre

**Generalized (Associated) Laguerre polynomial, L^alpha_n(x)

hermite

**Hermite polynomial H_n(x)

hermitenorm

**Normalized Hermite polynomial, He_n(x)

gegenbauer

**Gegenbauer (Ultraspherical) polynomials, C^(alpha)_n(x)

sh_legendre

**shifted Legendre polynomial, P*_n(x)

sh_chebyt

**shifted Chebyshev polynomial, T*_n(x)

sh_chebyu

**shifted Chebyshev polynomial, U*_n(x)

sh_jacobi

**shifted Jacobi polynomial, J*_n(x) = G^(p,q)_n(x)

HyperGeometric Functions
hyp2f1

Gauss hypergeometric function (2F1)

hyp1f1

Confluent hypergeometric function (1F1)

hyperu

Confluent hypergeometric function (U)

hyp0f1

Confluent hypergeometric limit function (0F1)

hyp2f0

Hypergeometric function (2F0)

hyp1f2

Hypergeometric function (1F2)

hyp3f0

Hypergeometric function (3F0)

Parabolic Cylinder Functions
pbdv

Parabolic cylinder function Dv(x) and derivative.

pbvv

Parabolic cylinder function Vv(x) and derivative.

pbwa

Parabolic cylinder function W(a,x) and derivative.

pbdv_seq

**Sequence of parabolic cylinder functions Dv(x)

pbvv_seq

**Sequence of parabolic cylinder functions Vv(x)

pbdn_seq

**Sequence of parabolic cylinder functions Dn(z), complex z

mathieu and Related Functions (and derivatives)
** All the following return both function and first derivative **
mathieu_a

Characteristic values for even solution (ce_m)

mathieu_b

Characteristic values for odd solution (se_m)

mathieu_even_coef

**sequence of expansion coefficients for even solution

mathieu_odd_coef

**sequence of expansion coefficients for odd solution

mathieu_cem

Even mathieu function

mathieu_sem

Odd mathieu function

mathieu_modcem1

Even modified mathieu function of the first kind

mathieu_modcem2

Even modified mathieu function of the second kind

mathieu_modsem1

Odd modified mathieu function of the first kind

mathieu_modsem2

Odd modified mathieu function of the second kind

Spheroidal Wave Functions
** The following functions require precomputed characteristic values **
pro_ang1

Prolate spheroidal angular function of the first kind

pro_rad1

Prolate spheroidal radial function of the first kind

pro_rad2

Prolate spheroidal radial function of the second kind

obl_ang1

Oblate spheroidal angluar function of the first kind

obl_rad1

Oblate spheroidal radial function of the first kind

obl_rad2

Oblate spheroidal radial function of the second kind

pro_cv

Compute characteristic value for prolate functions

obl_cv

Compute characteristic value for oblate functions

pro_cv_seq

Compute sequence of prolate characteristic values

obl_cv_seq

Compute sequence of oblate characteristic values

pro_ang1_cv

Prolate spheroidal angular function of the first kind

pro_rad1_cv

Prolate spheroidal radial function of the first kind

pro_rad2_cv

Prolate spheroidal radial function of the second kind

obl_ang1_cv

Oblate spheroidal angluar function of the first kind

obl_rad1_cv

Oblate spheroidal radial function of the first kind

obl_rad2_cv

Oblate spheroidal radial function of the second kind

Kelvin Functions
kelvin

All Kelvin functions (order 0) and derivatives.

kelvin_zeros

**Zeros of All Kelvin functions (order 0) and derivatives

ber

Kelvin function ber x

bei

Kelvin function bei x

berp

Derivative of Kelvin function ber x

beip

Derivative of Kelvin function bei x

ker

Kelvin function ker x

kei

Kelvin function kei x

kerp

Derivative of Kelvin function ker x

keip

Derivative of Kelvin function kei x

ber_zeros

**Zeros of Kelvin function bei x

bei_zeros

**Zeros of Kelvin function ber x

berp_zeros

**Zeros of derivative of Kelvin function ber x

beip_zeros

**Zeros of derivative of Kelvin function bei x

ker_zeros

**Zeros of Kelvin function kei x

kei_zeros

**Zeros of Kelvin function ker x

kerp_zeros

**Zeros of derivative of Kelvin function ker x

keip_zeros

**Zeros of derivative of Kelvin function kei x

Other Special Functions
expn

Exponential integral.

exp1

Exponential integral of order 1 (for complex argument)

expi

Another exponential integral Ei(x)

wofz

Fadeeva function.

dawsn

Dawson's integral.

shichi

Hyperbolic sine and cosine integrals.

sici

Integral of the sinc and "cosinc" functions.

spence

Dilogarithm integral.

zeta

Riemann zeta function of two arguments.

zetac

1.0  standard Riemann zeta function.

Convenience Functions
cbrt

Cube root.

exp10

10 raised to the x power.

exp2

2 raised to the x power.

radian

radian angle given degrees, minutes, and seconds.

cosdg

cosine of the angle given in degrees.

sindg

sine of the angle given in degrees.

tandg

tangent of the angle given in degrees.

cotdg

cotangent of the angle given in degrees.

log1p

log(1+x)

expm1

exp(x)1

cosm1

cos(x)1

round

round the argument to the nearest integer. If argument
ends in 0.5 exactly, pick the nearest even integer.

** in the description indicates a function which is not a universal
function and does not follow broadcasting and automatic
arraylooping rules.
Error handling:
Errors are handled by returning nans, or other appropriate values.
Some of the special function routines will print an error message
when an error occurs. By default this printing
is disabled. To enable such messages use errprint(1)
To disable such messages use errprint(0).
Example:
>>> print scipy.special.bdtr(1,10,0.3)
>>> scipy.special.errprint(1)
>>> print scipy.special.bdtr(1,10,0.3)
stats
Statistical Functions
=====================
This module contains a large number of probability distributions as
well as a growing library of statistical functions.
Each included distribution is an instance of the class rv_continous.
For each given name the following methods are available. See docstring for
rv_continuous for more information
rvs

random variates with the distribution

pdf

probability density function

cdf

cummulative distribution function

sf

survival function (1.0  cdf)

ppf

percentpoint function (inverse of cdf)

isf

inverse survival function

stats

mean, variance, and optionally skew and kurtosis

Calling the instance as a function returns a frozen pdf whose shape,
location, and scale parameters are fixed.
The distributions available with the above methods are:
CONTINUOUS (Total == 81 distributions)
===========
norm

Normal (Gaussian)

alpha

Alpha

anglit

Anglit

arcsine

Arcsine

beta

Beta

betaprime

Beta Prime

bradford

Bradford

burr

Burr

fisk

Fisk

cauchy

Cauchy

chi

Chi

chi2

Chisquared

cosine

Cosine

dgamma

Double Gamma

dweibull

Double Weibull

erlang

Erlang

expon

Exponential

exponweib

Exponentiated Weibull

exponpow

Exponential Power

fatiguelife

Fatigue Life (BirnbaumSanders)

foldcauchy

Folded Cauchy

f

F (Snecdor F)

foldnorm

Folded Normal

frechet_r

Frechet Right Sided, Extreme Value Type II (Extreme LB) or weibull_min

frechet_l

Frechet Left Sided, Weibull_max

genlogistic

Generalized Logistic

genpareto

Generalized Pareto

genexpon

Generalized Exponential

genextreme

Generalized Extreme Value

gausshyper

Gauss Hypergeometric

gamma

Gamma

gengamma

Generalized gamma

genhalflogistic

Generalized Half Logistic

gompertz

Gompertz (Truncated Gumbel)

gumbel_r

Right Sided Gumbel, LogWeibull, FisherTippett, Extreme Value Type I

gumbel_l

Left Sided Gumbel, etc.

halfcauchy

Half Cauchy

halflogistic

Half Logistic

halfnorm

Half Normal

hypsecant

Hyperbolic Secant

invgamma

Inverse Gamma

invnorm

Inverse Normal

invweibull

Inverse Weibull

johnsonsb

Johnson SB

johnsonsu

Johnson SU

laplace

Laplace

logistic

Logistic

loggamma

LogGamma

loglaplace

LogLaplace (Log Double Exponential)

lognorm

LogNormal

gilbrat

Gilbrat

lomax

Lomax (Pareto of the second kind)

maxwell

Maxwell

mielke

Mielke's BetaKappa

nakagami

Nakagami

ncx2

Noncentral chisquared

ncf

Noncentral F

t

Student's T

nct

Noncentral Student's T

pareto

Pareto

powerlaw

Powerfunction

powerlognorm

Power log normal

powernorm

Power normal

rdist

R distribution

reciprocal

Reciprocal

rayleigh

Rayleigh

rice

Rice

recipinvgauss

Reciprocal Inverse Gaussian

semicircular

Semicircular

triang

Triangular

truncexpon

Truncated Exponential

truncnorm

Truncated Normal

tukeylambda

TukeyLambda

uniform

Uniform

von_mises

VonMises (Circular)

wald

Waldv

weibull_min

Minimum Weibull (see Frechet)

weibull_max

Maximum Weibull (see Frechet)

wrapcauchy

Wrapped Cauchy

ksone

KolmogorovSmirnov onesided (no stats)

kstwobign

KolmogorovSmirnov twosided test for Large N (no stats)

DISCRETE (Total == 10 distributions)
============
binom

Binomial

bernoulli

Bernoulli

nbinom

Negative Binomial

geom

Geometric

hypergeom

Hypergeometric

logser

Logarithmic (LogSeries, Series)

poisson

Poisson

planck

Planck (Discrete Exponential)

boltzmann

Boltzmann (Truncated Discrete Exponential)

randint

Discrete Uniform

zipf

Zipf

dlaplace

Discrete Laplacian

Statistical Functions (adapted from Gary Strangman)
gmean

_

hmean

_

mean

_

cmedian

_

median

_

mode

_

tmean

_

tvar

_

tmin

_

tmax

_

tstd

_

tsem

_

moment

_

variation

_

skew

_

kurtosis

_

describe

_

skewtest

_

kurtosistest

_

normaltest

_

itemfreq

_

scoreatpercentile

_

percentileofscore

_

histogram2

_

histogram

_

cumfreq

_

relfreq

_

obrientransform

_

samplevar

_

samplestd

_

signaltonoise

_

bayes_mvs

_

var

_

std

_

stderr

_

sem

_

z

_

zs

_

zmap

_

threshold

_

trimboth

_

trim1

_

cov

_

corrcoef

_

f_oneway

_

paired

_

pearsonr

_

spearmanr

_

pointbiserialr

_

kendalltau

_

linregress

_

ttest_1samp

_

ttest_ind

_

ttest_rel

_

kstest

_

chisquare

_

ks_2samp

_

meanwhitneyu

_

tiecorrect

_

ranksums

_

wilcoxon

_

kruskal

_

friedmanchisquare

_

ansari

_

bartlett

_

levene

_

shapiro

_

anderson

_

binom_test

_

fligner

_

mood

_

oneway

_

glm

_

anova

_

Plottests
probplot

_

ppcc_max

_

ppcc_plot

_

For many more stat related functions install the software R and the
interface package rpy.
weave
C/C++ integration
=================
inline

a function for including C/C++ code within Python

blitz

a function for compiling Numeric expressions to C++

ext_tools

a module that helps construct C/C++ extension modules.

accelerate

a module that inline accelerates Python functions
