Package numpy
[hide private]
[frames] | no frames]

Package numpy

source code

NumPy
==========

You can support the development of NumPy and SciPy by purchasing
the book "Guide to NumPy" at

  http://www.trelgol.com

It is being distributed for a fee for only a few years to
cover some of the costs of development.  After the restriction period
it will also be freely available.

Additional documentation is available in the docstrings and at

http://www.scipy.org.


Available subpackages
---------------------
core      --- Defines a multi-dimensional array and useful procedures
              for Numerical computation.
lib       --- Basic functions used by several sub-packages and useful
              to have in the main name-space.
random    --- Core Random Tools
linalg    --- Core Linear Algebra Tools
fft       --- Core FFT routines
testing   --- Numpy testing tools

  These packages require explicit import
f2py      --- Fortran to Python Interface Generator.
distutils --- Enhancements to distutils with support for
              Fortran compilers support and more.


Global symbols from subpackages
-------------------------------
core    --> *
lib     --> *
testing --> NumpyTest


Utility tools
-------------

  test        --- Run numpy unittests
  pkgload     --- Load numpy packages
  show_config --- Show numpy build configuration
  dual        --- Overwrite certain functions with high-performance Scipy tools
  matlib      --- Make everything matrices.
  __version__ --- Numpy version string




Version: 1.0.4

Submodules [hide private]
  • numpy.add_newdocs
  • numpy.core
  • numpy.ctypeslib
  • numpy.fft: Core FFT routines...
  • numpy.lib
    • numpy.lib.scimath: Wrapper functions to more user-friendly calling of certain math functions whose output data-type is different than the input data-type in certain domains of the input.
  • numpy.linalg: Core Linear Algebra Tools =========== Linear Algebra Basics: norm --- Vector or matrix norm inv --- Inverse of a square matrix solve --- Solve a linear system of equations det --- Determinant of a square matrix lstsq --- Solve linear least-squares problem pinv --- Pseudo-inverse (Moore-Penrose) using lstsq Eigenvalues and Decompositions: eig --- Eigenvalues and vectors of a square matrix eigh --- Eigenvalues and eigenvectors of a Hermitian matrix eigvals --- Eigenvalues of a square matrix eigvalsh --- Eigenvalues of a Hermitian matrix.
  • numpy.random:  

Classes [hide private]
  MachAr
Diagnosing machine parameters.
  NumpyTest
Numpy tests site manager.
  PackageLoader
  RankWarning
Issued by polyfit when Vandermonde matrix is rank deficient.
  ScipyTest
  bool8
  bool_
  broadcast
  byte
  cdouble
Composed of two 64 bit floats
  cfloat
Composed of two 64 bit floats
  character
  chararray
  clongdouble
Composed of two 96 bit floats
  clongfloat
Composed of two 96 bit floats
  complex128
Composed of two 64 bit floats
  complex192
Composed of two 96 bit floats
  complex64
Composed of two 32 bit floats
  complex_
Composed of two 64 bit floats
  complexfloating
  csingle
Composed of two 32 bit floats
  double
  dtype
  errstate
with errstate(**state): --> operations in following block use given state.
  finfo
Machine limits for floating point types.
  flatiter
  flexible
  float32
  float64
  float96
  float_
  floating
  format_parser
  generic
  iinfo
Limits for integer types.
  inexact
  int0
  int16
  int32
  int64
  int8
  int_
  intc
  integer
  intp
  longcomplex
Composed of two 96 bit floats
  longdouble
  longfloat
  longlong
  matrix
  memmap
  ndarray
An array object represents a multidimensional, homogeneous array of fixed-size items.
  ndenumerate
A simple nd index iterator over an array.
  ndindex
Pass in a sequence of integers corresponding to the number of dimensions in the counter.
  number
  object0
  object_
  poly1d
A one-dimensional polynomial class.
  recarray
  record
  short
  signedinteger
  single
  singlecomplex
Composed of two 32 bit floats
  str_
  string0
  string_
  ubyte
  ufunc
Optimized functions make it possible to implement arithmetic with arrays efficiently
  uint
  uint0
  uint16
  uint32
  uint64
  uint8
  uintc
  uintp
  ulonglong
  unicode0
  unicode_
  unsignedinteger
  ushort
  vectorize
vectorize(somefunction, otypes=None, doc=None) Generalized Function class.
  void
  void0
Functions [hide private]
 
add_docstring(obj, docstring)
Add a docstring to a built-in obj if possible.
 
add_newdoc(place, obj, doc)
Adds documentation to obj which is in module place.
 
alen(a)
Return the length of a Python object interpreted as an array of at least 1 dimension.
 
all(a, axis=None, out=None)
Return true if all elements of x are true:
 
allclose(a, b, rtol=1e-05, atol=1e-08)
Returns True if all components of a and b are equal subject to given tolerances.
 
alltrue(a, axis=None, out=None)
Perform a logical_and over the given axis.
 
alterdot()
 
amax(a, axis=None, out=None)
Return the maximum of 'a' along dimension axis.
 
amin(a, axis=None, out=None)
Return the minimum of a along dimension axis.
 
angle(z, deg=0)
Return the angle of the complex argument z.
 
any(a, axis=None, out=None)
Return true if any elements of x are true.
 
append(arr, values, axis=None)
Append to the end of an array along axis (ravel first if None)
 
apply_along_axis(func1d, axis, arr, *args)
Execute func1d(arr[i],*args) where func1d takes 1-D arrays and arr is an N-d array.
 
apply_over_axes(func, a, axes)
Apply a function repeatedly over multiple axes, keeping the same shape for the resulting array.
 
arange(...)
arange([start,] stop[, step,], dtype=None)
 
argmax(a, axis=None)
Returns array of indices of the maximum values of along the given axis.
 
argmin(a, axis=None)
Return array of indices to the minimum values along the given axis.
 
argsort(a, axis=-1, kind='quicksort', order=None)
Returns array of indices that index 'a' in sorted order.
 
argwhere(a)
Return a 2-d array of shape N x a.ndim where each row is a sequence of indices into a.
 
around(a, decimals=0, out=None)
Round a to the given number of decimals.
 
array(object, dtype=None, copy=1, order=None, subok=0, ndmin=0)
Return an array from object with the specified date-type.
 
array2string(a, max_line_width=None, precision=None, suppress_small=None, separator=' ', prefix='', style=<built-in function repr>)
Return a string representation of an array.
 
array_equal(a1, a2)
 
array_equiv(a1, a2)
 
array_repr(arr, max_line_width=None, precision=None, suppress_small=None)
 
array_split(ary, indices_or_sections, axis=0)
Divide an array into a list of sub-arrays.
 
array_str(a, max_line_width=None, precision=None, suppress_small=None)
 
asanyarray(a, dtype=None, order=None)
Returns a as an array, but will pass subclasses through.
 
asarray(a, dtype=None, order=None)
Returns a as an array.
 
asarray_chkfinite(a)
Like asarray, but check that no NaNs or Infs are present.
 
ascontiguousarray(a, dtype=None)
Return 'a' as an array contiguous in memory (C order).
 
asfarray(a, dtype=<type 'numpy.float64'>)
asfarray(a,dtype=None) returns a as a float array.
 
asfortranarray(a, dtype=None)
Return 'a' as an array laid out in Fortran-order in memory.
 
asmatrix(data, dtype=None)
Returns 'data' as a matrix.
 
asscalar(a)
Convert an array of size 1 to its scalar equivalent.
 
atleast_1d(*arys)
Force a sequence of arrays to each be at least 1D.
 
atleast_2d(*arys)
Force a sequence of arrays to each be at least 2D.
 
atleast_3d(*arys)
Force a sequence of arrays to each be at least 3D.
 
average(a, axis=None, weights=None, returned=False)
Average the array over the given axis.
 
bartlett(M)
bartlett(M) returns the M-point Bartlett window.
 
base_repr(number, base=2, padding=0)
Return the representation of a number in the given base.
 
binary_repr(num, width=None)
Return the binary representation of the input number as a string.
 
bincount(x, weights=None)
Return the number of occurrences of each value in x.
 
blackman(M)
blackman(M) returns the M-point Blackman window.
 
bmat(obj, ldict=None, gdict=None)
Build a matrix object from string, nested sequence, or array.
 
byte_bounds(a)
(low, high) are pointers to the end-points of an array
 
can_cast(from=d1, to=d2)
Returns True if data type d1 can be cast to data type d2 without losing precision.
 
choose(a, choices, out=None, mode='raise')
Use an index array to construct a new array from a set of choices.
 
clip(a, a_min, a_max)
Limit the values of a to [a_min, a_max].
 
column_stack(tup)
Stack 1D arrays as columns into a 2D array Description: Take a sequence of 1D arrays and stack them as columns to make a single 2D array.
 
common_type(*arrays)
Given a sequence of arrays as arguments, return the best inexact scalar type which is "most" common amongst them.
 
compare_chararrays(...)
 
compress(condition, a, axis=None, out=None)
Return a where condition is true.
 
concatenate(...)
concatenate((a1, a2, ...), axis=0)
 
convolve(a, v, mode='full')
Returns the discrete, linear convolution of 1-D sequences a and v; mode can be 'valid', 'same', or 'full' to specify size of the resulting sequence.
 
copy(a)
Return an array copy of the given object.
 
corrcoef(x, y=None, rowvar=1, bias=0)
The correlation coefficients
 
correlate(a, v, mode='valid')
Return the discrete, linear correlation of 1-D sequences a and v; mode can be 'valid', 'same', or 'full' to specify the size of the resulting sequence
 
cov(m, y=None, rowvar=1, bias=0)
Estimate the covariance matrix.
 
cross(a, b, axisa=-1, axisb=-1, axisc=-1, axis=None)
Return the cross product of two (arrays of) vectors.
 
cumprod(a, axis=None, dtype=None, out=None)
Return the cumulative product of the elements along the given axis.
 
cumproduct(a, axis=None, dtype=None, out=None)
Return the cumulative product over the given axis.
 
cumsum(a, axis=None, dtype=None, out=None)
Sum the array over the given axis.
 
delete(arr, obj, axis=None)
Return a new array with sub-arrays along an axis deleted.
 
deprecate(func, oldname, newname)
 
diag(v, k=0)
returns a copy of the the k-th diagonal if v is a 2-d array or returns a 2-d array with v as the k-th diagonal if v is a 1-d array.
 
diagflat(v, k=0)
 
diagonal(a, offset=0, axis1=0, axis2=1)
Return specified diagonals.
 
diff(a, n=1, axis=-1)
Calculate the nth order discrete difference along given axis.
 
digitize(x, bins)
Return the index of the bin to which each value of x belongs.
 
disp(mesg, device=None, linefeed=False)
Display a message to the given device (default is sys.stdout) with or without a linefeed.
 
dot(...)
 
dsplit(ary, indices_or_sections)
Split ary into multiple sub-arrays along the 3rd axis (depth) Description: Split a single array into multiple sub arrays.
 
dstack(tup)
Stack arrays in sequence depth wise (along third dimension) Description: Take a sequence of arrays and stack them along the third axis.
 
ediff1d(ary, to_end=None, to_begin=None)
The differences between consecutive elements of an array, possibly with prefixed and/or appended values.
 
empty(...)
empty((d1,...,dn),dtype=float,order='C')
 
empty_like(a)
Return an empty (uninitialized) array of the shape and typecode of a.
 
expand_dims(a, axis)
Expand the shape of a by including newaxis before given axis.
 
extract(condition, arr)
Return the elements of ravel(arr) where ravel(condition) is True (in 1D).
 
eye(N, M=None, k=0, dtype=<type 'float'>)
eye returns a N-by-M 2-d array where the k-th diagonal is all ones, and everything else is zeros.
 
fastCopyAndTranspose(a)
 
fix(x, y=None)
Round x to nearest integer towards zero.
 
flatnonzero(a)
Return indicies that are not-zero in flattened version of a
 
fliplr(m)
returns an array m with the rows preserved and columns flipped in the left/right direction.
 
flipud(m)
returns an array with the columns preserved and rows flipped in the up/down direction.
 
frombuffer(buffer=, dtype=float, count=-1, offset=0)
Returns a 1-d array of data type dtype from buffer.
 
fromfile(file=, dtype=float, count=-1, sep='')
Required arguments: file -- open file object or string containing file name.
 
fromfunction(function, shape, **kwargs)
Returns an array constructed by calling a function on a tuple of number grids.
 
fromiter(iterable, dtype, count=-1)
Return a new 1d array initialized from iterable.
 
frompyfunc(...)
frompyfunc(func, nin, nout) take an arbitrary python function that takes nin objects as input and returns nout objects and return a universal function (ufunc).
 
fromstring(string, dtype=float, count=-1, sep='')
Return a new 1d array initialized from the raw binary data in string.
 
get_array_wrap(*args)
Find the wrapper for the array with the highest priority.
 
get_include()
Return the directory in the package that contains the numpy/*.h header files.
 
get_numarray_include(type=None)
Return the directory in the package that contains the numpy/*.h header files.
 
get_numpy_include(*args, **kwds)
get_numpy_include is DEPRECATED in numpy: use get_include instead Return the directory in the package that contains the numpy/*.h header files.
 
get_printoptions()
Return the current print options.
 
getbuffer(obj, offset=..., size=...)
Create a buffer object from the given object referencing a slice of length size starting at offset.
 
getbufsize()
Return the size of the buffer used in ufuncs.
 
geterr()
Get the current way of handling floating-point errors.
 
geterrcall()
Return the current callback function used on floating-point errors.
 
geterrobj(...)
 
gradient(f, *varargs)
Calculate the gradient of an N-dimensional scalar function.
 
hamming(M)
hamming(M) returns the M-point Hamming window.
 
hanning(M)
hanning(M) returns the M-point Hanning window.
 
histogram(a, bins=10, range=None, normed=False)
Compute the histogram from a set of data.
 
histogram2d(x, y, bins=10, range=None, normed=False)
Compute the 2D histogram from samples x,y.
 
histogramdd(sample, bins=10, range=None, normed=False, weights=None)
Return the N-dimensional histogram of the sample.
 
hsplit(ary, indices_or_sections)
Split ary into multiple columns of sub-arrays Description: Split a single array into multiple sub arrays.
 
hstack(tup)
Stack arrays in sequence horizontally (column wise) Description: Take a sequence of arrays and stack them horizontally to make a single array.
 
i0(x)
 
identity(n, dtype=None)
Returns the identity 2-d array of shape n x n.
 
imag(val)
Return the imaginary part of val.
 
indices(dimensions, dtype=<type 'int'>)
Returns an array representing a grid of indices with row-only, and column-only variation.
 
info(object=None, maxwidth=76, output=<epydoc.docintrospecter._DevNull instance at 0xb7b60eec>, toplevel='numpy')
Get help information for a function, class, or module.
 
inner(a, b)
Returns the dot product of two arrays, which has shape a.shape[:-1] + b.shape[:-1] with elements computed by the product of the elements from the last dimensions of a and b.
 
insert(arr, obj, values, axis=None)
Return a new array with values inserted along the given axis before the given indices
 
int_asbuffer(...)
 
interp(x, xp, fp, left=None, right=None)
Return the value of a piecewise-linear function at each value in x.
 
intersect1d(ar1, ar2)
Intersection of 1D arrays with unique elements.
 
intersect1d_nu(ar1, ar2)
Intersection of 1D arrays with any elements.
 
iscomplex(x)
Return a boolean array where elements are True if that element is complex (has non-zero imaginary part).
 
iscomplexobj(x)
Return True if x is a complex type or an array of complex numbers.
 
isfortran(a)
Returns True if 'a' is arranged in Fortran-order in memory with a.ndim > 1
 
isneginf(x, y=None)
Return a boolean array y with y[i] True for x[i] = -Inf.
 
isposinf(x, y=None)
Return a boolean array y with y[i] True for x[i] = +Inf.
 
isreal(x)
Return a boolean array where elements are True if that element is real (has zero imaginary part)
 
isrealobj(x)
Return True if x is not a complex type.
 
isscalar(num)
Returns True if the type of num is a scalar type.
 
issctype(rep)
Determines whether the given object represents a numeric array type.
 
issubclass_(arg1, arg2)
 
issubdtype(arg1, arg2)
 
issubsctype(arg1, arg2)
 
iterable(y)
 
ix_(*args)
Construct an open mesh from multiple sequences.
 
kaiser(M, beta)
kaiser(M, beta) returns a Kaiser window of length M with shape parameter beta.
 
kron(a, b)
kronecker product of a and b Kronecker product of two arrays is block array [[ a[ 0 ,0]*b, a[ 0 ,1]*b, ...
 
lexsort(keys=, axis=-1)
Argsort with list of keys.
 
linspace(start, stop, num=50, endpoint=False, retstep=False)
Return evenly spaced numbers.
 
load(file)
Wrapper around cPickle.load which accepts either a file-like object or a filename.
 
loads(string)
Load a pickle from the given string
 
loadtxt(fname, dtype=<type 'float'>, comments='#', delimiter=None, converters=None, skiprows=0, usecols=None, unpack=False)
Load ASCII data from fname into an array and return the array.
 
log2(x, y=None)
Returns the base 2 logarithm of x
 
logspace(start, stop, num=50, endpoint=False, base=10.0)
Evenly spaced numbers on a logarithmic scale.
 
mat(data, dtype=None)
Returns 'data' as a matrix.
 
maximum_sctype(t)
returns the sctype of highest precision of the same general kind as 't'
 
may_share_memory(a, b)
Determine if two arrays can share memory
 
mean(a, axis=None, dtype=None, out=None)
Compute the mean along the specified axis.
 
median(m)
median(m) returns a median of m along the first dimension of m.
 
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
 
mintypecode(typechars, typeset='GDFgdf', default='d')
Return a minimum data type character from typeset that handles all typechars given
 
msort(a)
 
nan_to_num(x)
Returns a copy of replacing NaN's with 0 and Infs with large numbers...
 
nanargmax(a, axis=None)
Find the maximum over the given axis ignoring NaNs.
 
nanargmin(a, axis=None)
Find the indices of the minimium over the given axis ignoring NaNs.
 
nanmax(a, axis=None)
Find the maximum over the given axis ignoring NaNs.
 
nanmin(a, axis=None)
Find the minimium over the given axis, ignoring NaNs.
 
nansum(a, axis=None)
Sum the array over the given axis, treating NaNs as 0.
 
ndim(a)
Return the number of dimensions of a.
 
newbuffer(size)
Return a new uninitialized buffer object of size bytes
 
nonzero(a)
Return the indices of the elements of a which are not zero.
 
obj2sctype(rep, default=None)
 
ones(shape, dtype=None, order='C')
Returns an array of the given dimensions which is initialized to all ones.
 
outer(a, b)
Returns the outer product of two vectors.
 
piecewise(x, condlist, funclist, *args, **kw)
Return a piecewise-defined function.
 
pkgload(*packages, **options) source code
 
place(arr, mask, vals)
Similar to putmask arr[mask] = vals but the 1D array vals has the same number of elements as the non-zero values of mask.
 
poly(seq_of_zeros)
Return a sequence representing a polynomial given a sequence of roots.
 
polyadd(a1, a2)
Adds two polynomials represented as sequences
 
polyder(p, m=1)
Return 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, deg, rcond=None, full=False)
Least squares polynomial fit.
 
polyint(p, m=1, k=None)
Return the mth analytical integral of the polynomial p.
 
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.
 
prod(a, axis=None, dtype=None, out=None)
Return the product of the elements along the given axis.
 
product(a, axis=None, dtype=None, out=None)
Product of the array elements over the given axis.
 
ptp(a, axis=None, out=None)
Return maximum - minimum along the the given dimension.
 
put(a, ind, v, mode='raise')
Set a[n] = v[n] for all n in ind.
 
putmask(...)
putmask(a, mask, values) sets a.flat[n] = values[n] for each n where mask.flat[n] is true.
 
rank(a)
Return the number of dimensions of a.
 
ravel(a, order='C')
Return a 1d array containing the elements of a.
 
real(val)
Return the real part of val.
 
real_if_close(a, tol=100)
If a is a complex array, return it as a real array if the imaginary part is close enough to zero.
 
repeat(a, repeats, axis=None)
Repeat elements of an array.
 
require(a, dtype=None, requirements=None)
 
reshape(a, newshape, order='C')
Returns an array containing the data of a, but with a new shape.
 
resize(a, new_shape)
Return a new array with the specified shape.
 
restoredot()
 
roll(a, shift, axis=None)
Roll the elements in the array by 'shift' positions along the given axis.
 
rollaxis(a, axis, start=0)
Return transposed array so that axis is rolled before start.
 
roots(p)
Return the roots of the polynomial coefficients in p.
 
rot90(m, k=1)
returns the array found by rotating m by k*90 degrees in the counterclockwise direction.
 
round_(a, decimals=0, out=None)
Round a to the given number of decimals.
 
row_stack(tup)
Stack arrays in sequence vertically (row wise) Description: Take a sequence of arrays and stack them vertically to make a single array.
 
savetxt(fname, X, fmt='%.18e', delimiter=' ')
Save the data in X to file fname using fmt string to convert the data to strings
 
sctype2char(sctype)
 
searchsorted(a, v, side='left')
Return indices where keys in v should be inserted to maintain order.
 
select(condlist, choicelist, default=0)
Return an array composed of different elements in choicelist, depending on the list of conditions.
 
set_numeric_ops(op=func, ...)
Set some or all of the number methods for all array objects.
 
set_printoptions(precision=None, threshold=None, edgeitems=None, linewidth=None, suppress=None, nanstr=None, infstr=None)
Set options associated with printing.
 
set_string_function(f, repr=1)
Set the python function f to be the function used to obtain a pretty printable string version of an array whenever an array is printed.
 
setbufsize(size)
Set the size of the buffer used in ufuncs.
 
setdiff1d(ar1, ar2)
Set difference of 1D arrays with unique elements.
 
seterr(all=None, divide=None, over=None, under=None, invalid=None)
Set how floating-point errors are handled.
 
seterrcall(func)
Set the callback function used when a floating-point error handler is set to 'call' or the object with a write method for use when the floating-point error handler is set to 'log'
 
seterrobj(...)
 
setmember1d(ar1, ar2)
Return a boolean array of shape of ar1 containing True where the elements of ar1 are in ar2 and False otherwise.
 
setxor1d(ar1, ar2)
Set exclusive-or of 1D arrays with unique elements.
 
shape(a)
Return the shape of a.
 
show_config()
 
sinc(x)
sinc(x) returns sin(pi*x)/(pi*x) at all points of array x.
 
size(a, axis=None)
Return the number of elements along given axis.
 
sometrue(a, axis=None, out=None)
Perform a logical_or over the given axis.
 
sort(a, axis=-1, kind='quicksort', order=None)
Return copy of 'a' sorted along the given axis.
 
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).
 
source(object, output=<epydoc.docintrospecter._DevNull instance at 0xb7b60eec>)
Write source for this object to output.
 
split(ary, indices_or_sections, axis=0)
Divide an array into a list of sub-arrays.
 
squeeze(a)
Remove single-dimensional entries from the shape of a.
 
std(a, axis=None, dtype=None, out=None)
Compute the standard deviation along the specified axis.
 
sum(a, axis=None, dtype=None, out=None)
Sum the array over the given axis.
 
swapaxes(a, axis1, axis2)
Return array a with axis1 and axis2 interchanged.
 
take(a, indices, axis=None, out=None, mode='raise')
Return an array formed from the elements of a at the given indices.
 
tensordot(a, b, axes=2)
tensordot returns the product for any (ndim >= 1) arrays.
 
test(*args, **kw)
Run Numpy module test suite with level and verbosity.
source code
 
tile(A, reps)
Repeat an array the number of times given in the integer tuple, reps.
 
trace(a, offset=0, axis1=0, axis2=1, dtype=None, out=None)
Return the sum along diagonals of the array.
 
transpose(a, axes=None)
Return a view of the array with dimensions permuted.
 
trapz(y, x=None, dx=1.0, axis=-1)
Integrate y(x) using samples along the given axis and the composite trapezoidal rule.
 
tri(N, M=None, k=0, dtype=<type 'float'>)
returns a N-by-M array where all the diagonals starting from lower left corner up to the k-th are all ones.
 
tril(m, k=0)
returns the elements on and below the k-th diagonal of m.
 
trim_zeros(filt, trim='fb')
Trim the leading and trailing zeros from a 1D array.
 
triu(m, k=0)
returns the elements on and above the k-th diagonal of m.
 
typename(char)
Return an english description for the given data type character.
 
union1d(ar1, ar2)
Union of 1D arrays with unique elements.
 
unique(x)
Return sorted unique items from an array or sequence.
 
unique1d(ar1, return_index=False)
Find the unique elements of 1D array.
 
unravel_index(x, dims)
Convert a flat index into an index tuple for an array of given shape.
 
unwrap(p, discont=3.14159265359, 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)
X = vander(x,N=None)
 
var(a, axis=None, dtype=None, out=None)
Compute the variance along the specified axis.
 
vdot(a, b)
Returns the dot product of 2 vectors (or anything that can be made into a vector).
 
vsplit(ary, indices_or_sections)
Split ary into multiple rows of sub-arrays Description: Split a single array into multiple sub arrays.
 
vstack(tup)
Stack arrays in sequence vertically (row wise) Description: Take a sequence of arrays and stack them vertically to make a single array.
 
where(...)
where(condition, x, y) or where(condition) Return elements from `x` or `y`, depending on `condition`.
 
who(vardict=None)
Print the Numpy arrays in the given dictionary (or globals() if None).
 
zeros(...)
zeros((d1,...,dn),dtype=float,order='C')
 
zeros_like(a)
Return an array of zeros of the shape and typecode of a.
Variables [hide private]
  ALLOW_THREADS = 1
  BUFSIZE = 10000
  CLIP = 0
  ERR_CALL = 3
  ERR_DEFAULT = 0
  ERR_DEFAULT2 = 2084
  ERR_IGNORE = 0
  ERR_LOG = 5
  ERR_PRINT = 4
  ERR_RAISE = 2
  ERR_WARN = 1
  FLOATING_POINT_SUPPORT = 1
  FPE_DIVIDEBYZERO = 1
  FPE_INVALID = 8
  FPE_OVERFLOW = 2
  FPE_UNDERFLOW = 4
  False_ = False
  Inf = inf
  Infinity = inf
  MAXDIMS = 32
  NAN = nan
  NINF = -inf
  NZERO = -0.0
  NaN = nan
  PINF = inf
  PZERO = 0.0
  RAISE = 2
  SHIFT_DIVIDEBYZERO = 0
  SHIFT_INVALID = 9
  SHIFT_OVERFLOW = 3
  SHIFT_UNDERFLOW = 6
  ScalarType = (<type 'int'>, <type 'float'>, <type 'complex'>, ...
  True_ = True
  UFUNC_BUFSIZE_DEFAULT = 10000
  UFUNC_PYVALS_NAME = 'UFUNC_PYVALS'
  WRAP = 1
  abs = <ufunc 'absolute'>
  absolute = <ufunc 'absolute'>
  add = <ufunc 'add'>
  arccos = <ufunc 'arccos'>
  arccosh = <ufunc 'arccosh'>
  arcsin = <ufunc 'arcsin'>
  arcsinh = <ufunc 'arcsinh'>
  arctan = <ufunc 'arctan'>
  arctan2 = <ufunc 'arctan2'>
  arctanh = <ufunc 'arctanh'>
  bitwise_and = <ufunc 'bitwise_and'>
  bitwise_not = <ufunc 'invert'>
  bitwise_or = <ufunc 'bitwise_or'>
  bitwise_xor = <ufunc 'bitwise_xor'>
  c_ = <numpy.lib.index_tricks.c_class object at 0x85f790c>
  cast = {<type 'numpy.int64'>: <function <lambda> at 0x8544614>...
  ceil = <ufunc 'ceil'>
  conj = <ufunc 'conjugate'>
  conjugate = <ufunc 'conjugate'>
  cos = <ufunc 'cos'>
  cosh = <ufunc 'cosh'>
  divide = <ufunc 'divide'>
  e = 2.71828182846
  equal = <ufunc 'equal'>
  exp = <ufunc 'exp'>
  expm1 = <ufunc 'expm1'>
  fabs = <ufunc 'fabs'>
  floor = <ufunc 'floor'>
  floor_divide = <ufunc 'floor_divide'>
  fmod = <ufunc 'fmod'>
  frexp = <ufunc 'frexp'>
  greater = <ufunc 'greater'>
  greater_equal = <ufunc 'greater_equal'>
  hypot = <ufunc 'hypot'>
  index_exp = <numpy.lib.index_tricks._index_expression_class ob...
  inf = inf
  infty = inf
  invert = <ufunc 'invert'>
  isfinite = <ufunc 'isfinite'>
  isinf = <ufunc 'isinf'>
  isnan = <ufunc 'isnan'>
  ldexp = <ufunc 'ldexp'>
  left_shift = <ufunc 'left_shift'>
  less = <ufunc 'less'>
  less_equal = <ufunc 'less_equal'>
  little_endian = False
  log = <ufunc 'log'>
  log10 = <ufunc 'log10'>
  log1p = <ufunc 'log1p'>
  logical_and = <ufunc 'logical_and'>
  logical_not = <ufunc 'logical_not'>
  logical_or = <ufunc 'logical_or'>
  logical_xor = <ufunc 'logical_xor'>
  maximum = <ufunc 'maximum'>
  mgrid = <numpy.lib.index_tricks.nd_grid object at 0x85f780c>
  minimum = <ufunc 'minimum'>
  mod = <ufunc 'remainder'>
  modf = <ufunc 'modf'>
  multiply = <ufunc 'multiply'>
  nan = nan
  nbytes = {<type 'numpy.int64'>: 8, <type 'numpy.int16'>: 2, <t...
  negative = <ufunc 'negative'>
  newaxis = None
  not_equal = <ufunc 'not_equal'>
  ogrid = <numpy.lib.index_tricks.nd_grid object at 0x85f782c>
  ones_like = <ufunc 'ones_like'>
  pi = 3.14159265359
  power = <ufunc 'power'>
  r_ = <numpy.lib.index_tricks.r_class object at 0x85f788c>
  reciprocal = <ufunc 'reciprocal'>
  remainder = <ufunc 'remainder'>
  right_shift = <ufunc 'right_shift'>
  rint = <ufunc 'rint'>
  s_ = <numpy.lib.index_tricks._index_expression_class object at...
  sctypeDict = {0: <type 'numpy.bool_'>, 1: <type 'numpy.int8'>,...
  sctypeNA = {'?': 'Bool', 'B': 'UInt8', 'Bool': <type 'numpy.bo...
  sctypes = {'complex': [<type 'numpy.complex64'>, <type 'numpy....
  sign = <ufunc 'sign'>
  signbit = <ufunc 'signbit'>
  sin = <ufunc 'sin'>
  sinh = <ufunc 'sinh'>
  sqrt = <ufunc 'sqrt'>
  square = <ufunc 'square'>
  subtract = <ufunc 'subtract'>
  tan = <ufunc 'tan'>
  tanh = <ufunc 'tanh'>
  true_divide = <ufunc 'true_divide'>
  typeDict = {0: <type 'numpy.bool_'>, 1: <type 'numpy.int8'>, 2...
  typeNA = {'?': 'Bool', 'B': 'UInt8', 'Bool': <type 'numpy.bool...
  typecodes = {'All': '?bhilqpBHILQPfdgFDGSUVO', 'AllFloat': 'fd...
Function Details [hide private]

add_docstring(obj, docstring)

 
Add a docstring to a built-in 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.

Blah, Blah.

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

 

Return true if all elements of x are true:

See Also:

ndarray.all : equivalent method

alltrue : equivalent function

allclose(a, b, rtol=1e-05, atol=1e-08)

 

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 usually comes into play for those elements of b that are very small or zero; it says how small a must be also.

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

 

Perform a logical_and over the given axis.

See Also:

ndarray.all : equivalent method

all : equivalent function

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

 

Return the maximum of 'a' along dimension axis.

Blah, Blah.

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

 

Return the minimum of a along dimension axis.

Blah, Blah.

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

 

Return true if any elements of x are true.

See Also:

ndarray.any : equivalent method

apply_along_axis(func1d, axis, arr, *args)

 
Execute func1d(arr[i],*args) where func1d takes 1-D arrays and arr is an N-d array. i varies so as to apply the function along the given axis for each 1-d subarray in arr.

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.

arange(...)

 

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 being greater than stop.

argmax(a, axis=None)

 

Returns array of indices of the maximum values of along the given axis.

Parameters:

a : {array_like}
Array to look in.
axis : {None, integer}
If None, the index is into the flattened array, otherwise along the specified axis

Returns:

index_array : {integer_array}

Examples

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

argmin(a, axis=None)

 

Return array of indices to the minimum values along the given axis.

Parameters:

a : {array_like}
Array to look in.
axis : {None, integer}
If None, the index is into the flattened array, otherwise along the specified axis

Returns:

index_array : {integer_array}

Examples

>>> a = arange(6).reshape(2,3)
>>> argmin(a)
0
>>> argmin(a,0)
array([0, 0, 0])
>>> argmin(a,1)
array([0, 0])

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

 

Returns array of indices that index 'a' in sorted order.

Perform an indirect sort along the given axis using the algorithm specified by the kind keyword. It returns an array of indices of the same shape as a that index data along the given axis in sorted order.

Parameters:

a : array
Array to be sorted.
axis : {None, int} optional
Axis along which to sort. None indicates that the flattened array should be used.
kind : {'quicksort', 'mergesort', 'heapsort'}, optional
Sorting algorithm to use.
order : {None, list type}, optional
When a is an array with fields defined, this argument specifies which fields to compare first, second, etc. Not all fields need be specified.

Returns:

index_array : {integer_array}
Array of indices that sort 'a' along the specified axis.

See Also:

lexsort : Indirect stable sort with multiple keys.

sort : Inplace sort.

Notes

The various sorts are characterized by average speed, worst case performance, need for work space, and whether they are stable. A stable sort keeps items with the same key in the same relative order. The three available algorithms have the following properties:

kind speed worst case work space stable
quicksort 1 O(n^2) 0 no
mergesort 2 O(n*log(n)) ~n/2 yes
heapsort 3 O(n*log(n)) 0 no

All the sort algorithms make temporary copies of the data when the sort is not along the last axis. Consequently, sorts along the last axis are faster and use less space than sorts along other axis.

argwhere(a)

 
Return a 2-d 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.

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

 

Round a to the given number of decimals.

The real and imaginary parts of complex numbers are rounded separately. The result of rounding a float is a float so the type must be cast if integers are desired. Nothing is done if the input is an integer array and the decimals parameter has a value >= 0.

Parameters:

a : {array_like}
Array containing numbers whose rounded values are desired. If a is not an array, a conversion is attempted.
decimals : {0, int}, optional
Number of decimal places to round to. When decimals is negative it specifies the number of positions to the left of the decimal point.
out : {None, array}, optional
Alternative output array in which to place the result. It must have the same shape as the expected output but the type will be cast if necessary. Numpy rounds floats to floats by default.

Returns:

rounded_array : {array}
If out=None, returns a new array of the same type as a containing the rounded values, otherwise a reference to the output array is returned.

See Also:

round_ : equivalent function

ndarray.round : equivalent method

Notes

Numpy rounds to even. Thus 1.5 and 2.5 round to 2.0, -0.5 and 0.5 round to 0.0, etc. Results may also be surprising due to the inexact representation of decimal fractions in IEEE floating point and the errors introduced when scaling by powers of ten.

Examples

>>> around([.5, 1.5, 2.5, 3.5, 4.5])
array([ 0.,  2.,  2.,  4.,  4.])
>>> around([1,2,3,11], decimals=1)
array([ 1,  2,  3, 11])
>>> around([1,2,3,11], decimals=-1)
array([ 0,  0,  0, 10])

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

 
Return an array from object with the specified date-type.

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 data-type for the array.  If not given, then
            the type will be determined as the minimum type required
            to hold the objects in the sequence.  This argument can only
            be used to 'upcast' the array.  For downcasting, use the
            .astype(t) method.
  copy   - 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 C-contiguous order (last-index varies the
            fastest).  If order is 'FORTRAN', then the returned array
            will be in Fortran-contiguous order (first-index varies the
            fastest).  If order is None, then the returned array may
            be in either C-, or Fortran-contiguous order or even
            discontiguous.
  subok  - If True, then sub-classes will be passed-through, otherwise
            the returned array will be forced to be a base-class array
  ndmin  - Specifies the minimum number of dimensions that the resulting
            array should have.  1's will be pre-pended to the shape as
            needed to meet this requirement.

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

 

Return a string representation of an array.

Examples

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

Parameters:

a : ndarray
Input array.
max_line_width : int
The maximum number of columns the string should span. Newline characters splits the string appropriately after array elements.
precision : int
Floating point precision.
suppress_small : bool
Represent very small numbers as zero.
separator : string
Inserted between elements.
prefix : string

An array is typically printed as

'prefix(' + array2string(a) + ')'

The length of the prefix string is used to align the output correctly.

style : function

array_split(ary, indices_or_sections, axis=0)

 
Divide an array into a list of sub-arrays.

Description:
   Divide ary into a list of sub-arrays 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 -- N-D array.
      Array to be divided into sub-arrays.
   indices_or_sections -- integer or 1D array.
      If integer, defines the number of (close to) equal sized
      sub-arrays.  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 sub-array 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,

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.

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)

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.

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.

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.

average(a, axis=None, 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 a.mean(axis) and to

a.sum(axis) / size(a, axis)
If weights are given, result is:
sum(a * weights,axis) / sum(weights,axis),

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

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

 

Return the representation of a number in the given base.

Base can't be larger than 36.

binary_repr(num, width=None)

 

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

This is equivalent to using base_repr with base 2, but about 25x faster.

For negative numbers, if width is not given, a - sign is added to the front. If width is given, the two's complement of the number is returned, with respect to that width.

bincount(x, weights=None)

 

Return the number of occurrences of each value in x.

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

See also: histogram, digitize, unique.

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

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

Ex:  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 2-d arrays.

byte_bounds(a)

 

(low, high) are pointers to the end-points of an array

low is the first byte high is just *past* the last byte

If the array is not single-segment, then it may not actually use every byte between these bounds.

The array provided must conform to the Python-side of the array interface

choose(a, choices, out=None, mode='raise')

 

Use an index array to construct a new array from a set of choices.

Given an array of integers in {0, 1, ..., n-1} and a set of n choice arrays, this function will create a new array that merges each of the choice arrays. Where a value in a is i, then the new array will have the value that choices[i] contains in the same place.

Parameters:

a : int array
This array must contain integers in [0, n-1], where n is the number of choices.
choices : sequence of arrays
Each of the choice arrays should have the same shape as the index array.
out : array, optional
If provided, the result will be inserted into this array. It should be of the appropriate shape and dtype
mode : {'raise', 'wrap', 'clip'}, optional
Specifies how out-of-bounds indices will behave. 'raise' : raise an error 'wrap' : wrap around 'clip' : clip to the range

Returns:

merged_array : array

See Also:

ndarray.choose : equivalent method

Examples

>>> choices = [[0, 1, 2, 3], [10, 11, 12, 13],
...   [20, 21, 22, 23], [30, 31, 32, 33]]
>>> choose([2, 3, 1, 0], choices)
array([20, 31, 12,  3])
>>> choose([2, 4, 1, 0], choices, mode='clip')
array([20, 31, 12,  3])
>>> choose([2, 4, 1, 0], choices, mode='wrap')
array([20,  1, 12,  3])

clip(a, a_min, a_max)

 

Limit the values of a to [a_min, a_max]. Equivalent to

a[a < a_min] = a_min a[a > a_max] = a_max

column_stack(tup)

 
Stack 1D arrays as columns into a 2D array

Description:
    Take a sequence of 1D arrays and stack them as columns
    to make a single 2D array.  All arrays in the sequence
    must have the same first dimension.  2D arrays are
    stacked as-is, just like with hstack.  1D arrays are turned
    into 2D columns first.

Arguments:
    tup -- sequence of 1D or 2D arrays.  All arrays must have the same
           first dimension.
Examples:
    >>> import numpy
    >>> a = array((1,2,3))
    >>> b = array((2,3,4))
    >>> numpy.column_stack((a,b))
    array([[1, 2],
           [2, 3],
           [3, 4]])

common_type(*arrays)

 

Given a sequence of arrays as arguments, return 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=None, out=None)

 

Return a where condition is true.

Equivalent to a[condition].

concatenate(...)

 

concatenate((a1, a2, ...), axis=0)

Join arrays together.

The tuple of sequences (a1, a2, ...) are joined along the given axis (default is the first one) into a single numpy array.

Example:
>>> concatenate( ([0,1,2], [5,6,7]) )
array([0, 1, 2, 5, 6, 7])

cov(m, y=None, rowvar=1, bias=0)

 

Estimate the covariance matrix.

If m is a vector, return the variance. For matrices return the covariance matrix.

If y is given it is treated as an additional (set of) variable(s).

Normalization is by (N-1) where N is the number of observations (unbiased estimate). If bias is 1 then normalization is by N.

If rowvar is non-zero (default), then each row is a variable with observations in the columns, otherwise each column is a variable and the observations are in the rows.

cross(a, b, axisa=-1, axisb=-1, axisc=-1, axis=None)

 

Return the cross product of two (arrays of) vectors.

The cross product is performed over the last axis of a and b by default, and can handle axes with dimensions 2 and 3. For a dimension of 2, the z-component of the equivalent three-dimensional cross product is returned.

cumprod(a, axis=None, dtype=None, out=None)

 

Return the cumulative product of the elements along the given axis.

Blah, Blah.

cumproduct(a, axis=None, dtype=None, out=None)

 

Return the cumulative product over the given axis.

Blah, Blah.

cumsum(a, axis=None, dtype=None, out=None)

 

Sum the array over the given axis.

Blah, Blah.

delete(arr, obj, axis=None)

 

Return a new array with sub-arrays along an axis deleted.

Return a new array with the sub-arrays (i.e. rows or columns) deleted along the given axis as specified by obj

obj may be a slice_object (s_[3:5:2]) or an integer or an array of integers indicated which sub-arrays to remove.

If axis is None, then ravel the array first.

Example: >>> arr = [[3,4,5], ... [1,2,3], ... [6,7,8]]

>>> delete(arr, 1, 1)
array([[3, 5],
       [1, 3],
       [6, 8]])
>>> delete(arr, 1, 0)
array([[3, 4, 5],
       [6, 7, 8]])

diagonal(a, offset=0, axis1=0, axis2=1)

 

Return specified diagonals.

If a is 2-d, returns the diagonal of self with the given offset, i.e., the collection of elements of the form a[i,i+offset]. If a has more than two dimensions, then the axes specified by axis1 and axis2 are used to determine the 2-d subarray whose diagonal is returned. The shape of the resulting array can be determined by removing axis1 and axis2 and appending an index to the right equal to the size of the resulting diagonals.

Parameters:

a : {array_like}
Array from whis the diagonals are taken.
offset : {0, integer}, optional
Offset of the diagonal from the main diagonal. Can be both positive and negative. Defaults to main diagonal.
axis1 : {0, integer}, optional
Axis to be used as the first axis of the 2-d subarrays from which the diagonals should be taken. Defaults to first axis.
axis2 : {1, integer}, optional
Axis to be used as the second axis of the 2-d subarrays from which the diagonals should be taken. Defaults to second axis.

Returns:

array_of_diagonals : array of same type as a
If a is 2-d, a 1-d array containing the diagonal is returned. If a has larger dimensions, then an array of diagonals is returned.

See Also:

diag : Matlab workalike for 1-d and 2-d arrays.

diagflat : Create diagonal arrays.

trace : Sum along diagonals.

Examples

>>> a = arange(4).reshape(2,2)
>>> a
array([[0, 1],
       [2, 3]])
>>> a.diagonal()
array([0, 3])
>>> a.diagonal(1)
array([1])
>>> a = arange(8).reshape(2,2,2)
>>> a
array([[[0, 1],
        [2, 3]],
       [[4, 5],
        [6, 7]]])
>>> a.diagonal(0,-2,-1)
array([[0, 3],
       [4, 7]])

digitize(x, bins)

 

Return the index of the bin to which each value of x belongs.

Each index i returned is such that bins[i-1] <= x < bins[i] if bins is monotonically increasing, or bins [i-1] > x >= bins[i] if bins is monotonically decreasing.

Beyond the bounds of the bins 0 or len(bins) is returned as appropriate.

dsplit(ary, indices_or_sections)

 
Split ary into multiple sub-arrays along the 3rd axis (depth)

Description:
    Split a single array into multiple sub arrays.  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 sub-arrays equally sized, the
    operation throws a ValueError exception. See array_split and
    split for other options on indices_or_sections.
Arguments:
   ary -- N-D array.
      Array to be divided into sub-arrays.
   indices_or_sections -- integer or 1D array.
      If integer, defines the number of (close to) equal sized
      sub-arrays.  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 sub-array equal to the original
      array.
Returns:
    sequence of sub-arrays.  The returned arrays have the same
    number of dimensions as the input array.
Caveats:
   See vsplit caveats.
Related:
    dstack, split, array_split, hsplit, vsplit.
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)

 
Stack arrays in sequence depth wise (along third dimension)

Description:
    Take a sequence of arrays and stack 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:
    >>> import numpy
    >>> a = array((1,2,3))
    >>> b = array((2,3,4))
    >>> numpy.dstack((a,b))
    array([[[1, 2],
            [2, 3],
            [3, 4]]])
    >>> a = array([[1],[2],[3]])
    >>> b = array([[2],[3],[4]])
    >>> numpy.dstack((a,b))
    array([[[1, 2]],
    <BLANKLINE>
           [[2, 3]],
    <BLANKLINE>
           [[3, 4]]])

ediff1d(ary, to_end=None, to_begin=None)

 

The differences between consecutive elements of an array, possibly with prefixed and/or appended values.

:Parameters:
  • `ary` : array This array will be flattened before the difference is taken.
  • `to_end` : number, optional If provided, this number will be tacked onto the end of the returned differences.
  • `to_begin` : number, optional If provided, this number will be taked onto the beginning of the returned differences.
:Returns:
  • `ed` : array The differences. Loosely, this will be (ary[1:] - ary[:-1]).

empty(...)

 

empty((d1,...,dn),dtype=float,order='C')

Return a new array of shape (d1,...,dn) and given type with all its entries uninitialized. This can be faster than zeros.

empty_like(a)

 

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

extract(condition, arr)

 

Return the elements of ravel(arr) where ravel(condition) is True (in 1D).

Equivalent to compress(ravel(condition), ravel(arr)).

flatnonzero(a)

 

Return indicies that are not-zero in flattened version of a

Equivalent to a.ravel().nonzero()[0]

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.

flipud(m)

 
returns an array with the columns preserved and rows flipped in the up/down direction. Works on the first dimension of m.

frombuffer(buffer=, dtype=float, count=-1, offset=0)

 
Returns a 1-d 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 out not in machine byte-order, than use a propert data type descriptor. The data will not be byteswapped, but the array will manage it in future operations.

fromfile(file=, dtype=float, count=-1, sep='')

 
Required arguments:
    file -- open file object or string containing file name.

Keyword arguments:
    dtype -- type and order of the returned array (default float)
    count -- number of items to input (default all)
    sep -- separater between items if file is a text file (default "")

Return 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 the entire file is read, otherwise count is the
number of items of the given type to read in.  If 'sep' is "" it means to
read binary data from the file using the specified dtype, otherwise it gives
the separator between elements in a text file. The 'dtype' value is also
used to determine the size and order of the items in binary files.


Data written using the tofile() method can be conveniently recovered using
this function.

WARNING: This function should be used sparingly as the binary files are not
platform independent. In particular, they contain no endianess or datatype
information. Nevertheless it can be useful for reading in simply formatted
or binary data quickly.

Returns:
array

fromfunction(function, shape, **kwargs)

 

Returns an array constructed by calling a function on a tuple of number grids.

The function should accept as many arguments as the length of shape and work on array inputs. The shape argument is a sequence of numbers indicating the length of the desired output for each axis.

The function can also accept keyword arguments (except dtype), which will be passed through fromfunction to the function itself. The dtype argument (default float) determines the data-type of the index grid passed to the function.

fromiter(iterable, dtype, count=-1)

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

frompyfunc(...)

 
frompyfunc(func, nin, nout) take an arbitrary python function that takes nin objects as input and returns nout objects and return a universal function (ufunc). This ufunc always returns PyObject arrays

fromstring(string, dtype=float, count=-1, sep='')

 

Return a new 1d array initialized from the raw binary data in string.

If count is positive, the new array will have count elements, otherwise its 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).

get_array_wrap(*args)

 

Find the wrapper for the array with the highest priority.

In case of ties, leftmost wins. If no wrapper is found, return None

get_include()

 
Return 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_numarray_include(type=None)

 
Return 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_numarray_include()])

get_numpy_include(*args, **kwds)

 
get_numpy_include is DEPRECATED in numpy: use get_include instead
Return 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_printoptions()

 
Return the current print options.
Returns:
dictionary of current print options with keys - precision : int - threshold : int - edgeitems : int - linewidth : int - suppress : bool - nanstr : string - infstr : string

See Also:

  • set_printoptions : parameter descriptions

getbuffer(obj, offset=..., size=...)

 
Create a buffer object from the given object referencing a slice of length size starting at offset. Default is the entire buffer. A read-write buffer is attempted followed by a read-only buffer.

geterr()

 

Get the current way of handling floating-point errors.

Returns a dictionary with entries "divide", "over", "under", and "invalid", whose values are from the strings "ignore", "print", "log", "warn", "raise", and "call".

gradient(f, *varargs)

 

Calculate the gradient of an N-dimensional scalar function.

Uses central differences on the interior and first differences on boundaries to give the same shape.

Inputs:

f -- An N-dimensional 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.

histogram(a, bins=10, range=None, normed=False)

 

Compute the histogram from a set of data.

Parameters:

a : array
The data to histogram. n-D arrays will be flattened.
bins : int or sequence of floats
If an int, then the number of equal-width bins in the given range. Otherwise, a sequence of the lower bound of each bin.
range : (float, float)
The lower and upper range of the bins. If not provided, then (a.min(), a.max()) is used. Values outside of this range are allocated to the closest bin.
normed : bool
If False, the result array will contain the number of samples in each bin. If True, the result array is the value of the probability density function at the bin normalized such that the integral over the range is 1. Note that the sum of all of the histogram values will not usually be 1; it is not a probability mass function.

Returns:

hist : array
The values of the histogram. See normed for a description of the possible semantics.
lower_edges : float array
The lower edges of each bin.

SeeAlso:

histogramdd

histogram2d(x, y, bins=10, range=None, normed=False)

 

Compute the 2D histogram from samples x,y.

:Parameters:
  • `x,y` : Sample arrays (1D).
  • `bins` : Number of bins -or- [nbin x, nbin y] -or- [bin edges] -or- [x bin edges, y bin edges].
  • `range` : A sequence of lower and upper bin edges (default: [min, max]).
  • `normed` : Boolean, if False, return the number of samples in each bin, if True, returns the density.
  • `weights` : An array of weights. The weights are normed only if normed is True. Should weights.sum() not equal N, the total bin count will not be equal to the number of samples.
:Return:
  • `hist` : Histogram array.
  • `xedges, yedges` : Arrays defining the bin edges.
Example:
>>> x = random.randn(100,2)
>>> hist2d, xedges, yedges = histogram2d(x, bins = (6, 7))
:SeeAlso: histogramdd
Returns:
H, xedges, yedges

histogramdd(sample, bins=10, range=None, normed=False, weights=None)

 

Return the N-dimensional histogram of the sample.

Parameters:

sample : sequence or array
A sequence containing N arrays or an NxM array. Input data.
bins : sequence or scalar
A sequence of edge arrays, a sequence of bin counts, or a scalar which is the bin count for all dimensions. Default is 10.
range : sequence
A sequence of lower and upper bin edges. Default is [min, max].
normed : boolean
If False, return the number of samples in each bin, if True, returns the density.
weights : array
Array of weights. The weights are normed only if normed is True. Should the sum of the weights not equal N, the total bin count will not be equal to the number of samples.

Returns:

hist : array
Histogram array.
edges : list
List of arrays defining the lower bin edges.

SeeAlso:

histogram

Example

>>> x = random.randn(100,3)
>>> hist3d, edges = histogramdd(x, bins = (5, 6, 7))

hsplit(ary, indices_or_sections)

 
Split ary into multiple columns of sub-arrays

Description:
    Split 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 sub-arrays equally sized, the
    operation throws a ValueError exception. See array_split and
    split for other options on indices_or_sections.
Arguments:
   ary -- N-D array.
      Array to be divided into sub-arrays.
   indices_or_sections -- integer or 1D array.
      If integer, defines the number of (close to) equal sized
      sub-arrays.  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 sub-array equal to the original
      array.
Returns:
    sequence of sub-arrays.  The returned arrays have the same
    number of dimensions as the input array.
Related:
    hstack, split, array_split, vsplit, dsplit.
Examples:
    >>> import numpy
    >>> a= array((1,2,3,4))
    >>> numpy.hsplit(a,2)
    [array([1, 2]), array([3, 4])]
    >>> a = array([[1,2,3,4],[1,2,3,4]])
    >>> hsplit(a,2)
    [array([[1, 2],
           [1, 2]]), array([[3, 4],
           [3, 4]])]

hstack(tup)

 
Stack arrays in sequence horizontally (column wise)

Description:
    Take a sequence of arrays and stack 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:
    >>> import numpy
    >>> a = array((1,2,3))
    >>> b = array((2,3,4))
    >>> numpy.hstack((a,b))
    array([1, 2, 3, 2, 3, 4])
    >>> a = array([[1],[2],[3]])
    >>> b = array([[2],[3],[4]])
    >>> numpy.hstack((a,b))
    array([[1, 2],
           [2, 3],
           [3, 4]])

identity(n, dtype=None)

 
Returns the identity 2-d array of shape n x n.

identity(n)[i,j] == 1 for all i == j
                 == 0 for all i != j

imag(val)

 

Return the imaginary part of val.

Useful if val maybe a scalar or an array.

info(object=None, maxwidth=76, output=<epydoc.docintrospecter._DevNull instance at 0xb7b60eec>, toplevel='numpy')

 
Get help information for a function, class, or module.

Example:
   >>> from numpy import *
   >>> info(polyval) # doctest: +SKIP

   polyval(p, x)

     Evaluate the polymnomial p at x.

     Description:
         If p is of length N, this function returns the value:
         p[0]*(x**N-1) + p[1]*(x**N-2) + ... + p[N-2]*x + p[N-1]

insert(arr, obj, values, axis=None)

 

Return a new array with values inserted along the given axis before the given indices

If axis is None, then ravel the array first.

The obj argument can be an integer, a slice, or a sequence of integers.

Example: >>> a = array([[1,2,3], ... [4,5,6], ... [7,8,9]])

>>> insert(a, [1,2], [[4],[5]], axis=0)
array([[1, 2, 3],
       [4, 4, 4],
       [4, 5, 6],
       [5, 5, 5],
       [7, 8, 9]])

interp(x, xp, fp, left=None, right=None)

 

Return the value of a piecewise-linear function at each value in x.

The piecewise-linear function, f, is defined by the known data-points fp=f(xp). The xp points must be sorted in increasing order but this is not checked.

For values of x < xp[0] return the value given by left. If left is None, then return fp[0]. For values of x > xp[-1] return the value given by right. If right is None, then return fp[-1].

intersect1d(ar1, ar2)

 
Intersection of 1D arrays with unique elements.

Use unique1d() to generate arrays with only unique elements to use as inputs
to this function. Alternatively, use intersect1d_nu() which will find the
unique values for you.

:Parameters:
  - `ar1` : array
  - `ar2` : array

:Returns:
  - `intersection` : array

:See also:
  numpy.lib.arraysetops has a number of other functions for performing set
  operations on arrays.

intersect1d_nu(ar1, ar2)

 
Intersection of 1D arrays with any elements.

The input arrays do not have unique elements like intersect1d() requires.

:Parameters:
  - `ar1` : array
  - `ar2` : array

:Returns:
  - `intersection` : array

:See also:
  numpy.lib.arraysetops has a number of other functions for performing set
  operations on arrays.

iscomplex(x)

 

Return a boolean array where elements are True if that element is complex (has non-zero imaginary part).

For scalars, return a boolean.

iscomplexobj(x)

 

Return True if x is a complex type or an array of complex numbers.

Unlike iscomplex(x), complex(3.0) is considered a complex object.

isneginf(x, y=None)

 

Return a boolean array y with y[i] True for x[i] = -Inf.

If y is an array, the result replaces the contents of y.

isposinf(x, y=None)

 

Return a boolean array y with y[i] True for x[i] = +Inf.

If y is an array, the result replaces the contents of y.

isreal(x)

 

Return a boolean array where elements are True if that element is real (has zero imaginary part)

For scalars, return a boolean.

isrealobj(x)

 

Return True if x is not a complex type.

Unlike isreal(x), complex(3.0) is considered a complex object.

ix_(*args)

 

Construct an open mesh from multiple sequences.

This function takes n 1-d sequences and returns n outputs with n dimensions each such that the shape is 1 in all but one dimension and the dimension with the non-unit shape value cycles through all n dimensions.

Using ix_() one can quickly construct index arrays that will index the cross product.

a[ix_([1,3,7],[2,5,8])] returns the array

a[1,2] a[1,5] a[1,8] a[3,2] a[3,5] a[3,8] a[7,2] a[7,5] a[7,8]

kron(a, b)

 
kronecker product of a and b

Kronecker product of two arrays is block array
[[ a[ 0 ,0]*b, a[ 0 ,1]*b, ... , a[ 0 ,n-1]*b  ],
 [ ...                                   ...   ],
 [ a[m-1,0]*b, a[m-1,1]*b, ... , a[m-1,n-1]*b  ]]

lexsort(keys=, axis=-1)

 
Argsort with list of keys.

Perform an indirect sort using a list of keys. The first key is sorted,
then the second, and so on through the list of keys. At each step the
previous order is preserved when equal keys are encountered. 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 last key being
used for the primary sort order, the second-to-last key for the secondary
sort order, and so on).  The keys argument must be a sequence of things
that can be converted to arrays of the same shape.

Parameters:

    a : array type
        Array containing values that the returned indices should sort.

    axis : integer
        Axis to be indirectly sorted. None indicates that the flattened
        array should be used. Default is -1.

Returns:

    indices : integer array
        Array of indices that sort the keys along the specified axis. The
        array has the same shape as the keys.

SeeAlso:

    argsort : indirect sort
    sort : inplace sort

Returns:
array of indices

linspace(start, stop, num=50, endpoint=False, retstep=False)

 

Return evenly spaced numbers.

Return num evenly spaced samples from start to stop. If endpoint is True, the last sample is stop. If retstep is True then return (seq, step_value), where step_value used.

Parameters:
  • start ({float}) - The value the sequence starts at.
  • stop ({float}) - The value the sequence stops at. If endpoint is false, then this is not included in the sequence. Otherwise it is guaranteed to be the last value.
  • num ({integer}) - Number of samples to generate. Default is 50.
  • endpoint ({boolean}) - If true, stop is the last sample. Otherwise, it is not included. Default is true.
  • retstep ({boolean}) - If true, return (samples, step), where step is the spacing used in generating the samples.
Returns:
samples : {array}
num equally spaced samples from the range [start, stop] or [start, stop).
step : {float} (Only if retstep is true)
Size of spacing between samples.

loadtxt(fname, dtype=<type 'float'>, comments='#', delimiter=None, converters=None, skiprows=0, usecols=None, unpack=False)

 

Load ASCII data from fname into an array and return the array.

The data must be regular, same number of values in every row

fname can be a filename or a file handle.  Support for gzipped files is
automatic, if the filename ends in .gz

See scipy.loadmat to read and write matfiles.

Example usage:

  X = loadtxt('test.dat')  # data in two columns
  t = X[:,0]
  y = X[:,1]

Alternatively, you can do the same with "unpack"; see below

  X = loadtxt('test.dat')    # a matrix of data
  x = loadtxt('test.dat')    # a single column of data


dtype - the data-type of the resulting array.  If this is a
record data-type, the the resulting array will be 1-d and each row will
be interpreted as an element of the array. The number of columns
used must match the number of fields in the data-type in this case.

comments - the character used to indicate the start of a comment
in the file

delimiter is a string-like character used to seperate values in the
file. If delimiter is unspecified or none, any whitespace string is
a separator.

converters, if not None, is a dictionary mapping column number to
a function that will convert that column to a float.  Eg, if
column 0 is a date string: converters={0:datestr2num}

skiprows is the number of rows from the top to skip

usecols, if not None, is a sequence of integer column indexes to
extract where 0 is the first column, eg usecols=(1,4,5) to extract
just the 2nd, 5th and 6th columns

unpack, if True, will transpose the matrix allowing you to unpack
into named arguments on the left hand side

    t,y = load('test.dat', unpack=True) # for  two column data
    x,y,z = load('somefile.dat', usecols=(3,5,7), unpack=True)

log2(x, y=None)

 

Returns the base 2 logarithm of x

If y is an array, the result replaces the contents of y.

logspace(start, stop, num=50, endpoint=False, 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

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

may_share_memory(a, b)

 

Determine if two arrays can share memory

The memory-bounds of a and b are computed. If they overlap then this function returns True. Otherwise, it returns False.

A return of True does not necessarily mean that the two arrays share any element. It just means that they *might*.

mean(a, axis=None, dtype=None, out=None)

 

Compute the mean along the specified axis.

Returns the average of the array elements. The average is taken over the flattened array by default, otherwise over the specified axis. The dtype returned for integer type arrays is float

Parameters:

a : {array_like}
Array containing numbers whose mean is desired. If a is not an array, a conversion is attempted.
axis : {None, integer}, optional
Axis along which the means are computed. The default is to compute the standard deviation of the flattened array.
dtype : {None, dtype}, optional
Type to use in computing the means. For arrays of integer type the default is float32, for arrays of float types it is the same as the array type.
out : {None, array}, optional
Alternative output array in which to place the result. It must have the same shape as the expected output but the type will be cast if necessary.

Returns:

mean : {array, scalar}, see dtype parameter above
If out=None, returns a new array containing the mean values, otherwise a reference to the output array is returned.

See Also:

var : Variance

std : Standard deviation

Notes

The mean is the sum of the elements along the axis divided by the number of elements.

Examples

>>> a = array([[1,2],[3,4]])
>>> mean(a)
2.5
>>> mean(a,0)
array([ 2.,  3.])
>>> mean(a,1)
array([ 1.5,  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

EG,

[X, Y] = meshgrid([1,2,3], [4,5,6,7])

X =
1 2 3 1 2 3 1 2 3 1 2 3
Y =
4 4 4 5 5 5 6 6 6 7 7 7

mintypecode(typechars, typeset='GDFgdf', default='d')

 

Return a minimum data type character from typeset that handles all typechars given

The returned type character must be the smallest size such that an array of the returned type can handle the data from an array of type t for each t in typechars (or if typechars is an array, then its dtype.char).

If the typechars does not intersect with the typeset, then default is returned.

If t in typechars is not a string then t=asarray(t).dtype.char is applied.

nan_to_num(x)

 

Returns a copy of replacing NaN's with 0 and Infs with large numbers

The following mappings are applied:
    NaN -> 0
    Inf -> limits.double_max
   -Inf -> limits.double_min

ndim(a)

 

Return the number of dimensions of a.

If a is not already an array, a conversion is attempted. Scalars are zero dimensional.

Parameters:

a : {array_like}
Array whose number of dimensions are desired. If a is not an array, a conversion is attempted.

Returns:

number_of_dimensions : {integer}
Returns the number of dimensions.

See Also:

rank : equivalent function.

ndarray.ndim : equivalent method

shape : dimensions of array

ndarray.shape : dimensions of array

Examples

>>> ndim([[1,2,3],[4,5,6]])
2
>>> ndim(array([[1,2,3],[4,5,6]]))
2
>>> ndim(1)
0

nonzero(a)

 

Return the indices of the elements of a which are not zero.

Parameters:

a : {array_like}

Returns:

tuple_of_arrays : {tuple}

Examples

>>> eye(3)[nonzero(eye(3))]
array([ 1.,  1.,  1.])
>>> nonzero(eye(3))
(array([0, 1, 2]), array([0, 1, 2]))
>>> eye(3)[nonzero(eye(3))]
array([ 1.,  1.,  1.])

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.

piecewise(x, condlist, funclist, *args, **kw)

 

Return a piecewise-defined function.

x is the domain

condlist is a list of boolean arrays or a single boolean array
The length of the condition list must be n2 or n2-1 where n2 is the length of the function list. If len(condlist)==n2-1, then an 'otherwise' condition is formed by |'ing all the conditions and inverting.
funclist is 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
the the functions are only evaluated on elements of x that satisfy the corresponding condition.
The result is
|-- | f1(x) for condition1
y = --| f2(x) for condition2
...
fn(x) for conditionn

|--

place(arr, mask, vals)

 
Similar to putmask arr[mask] = vals but the 1D array vals has the same number of elements as the non-zero values of mask. Inverse of extract.

poly(seq_of_zeros)

 

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

polyfit(x, y, deg, rcond=None, full=False)

 
Least squares polynomial fit.

Required arguments

    x -- vector of sample points
    y -- vector or 2D array of values to fit
    deg -- degree of the fitting polynomial

Keyword arguments

    rcond -- relative condition number of the fit (default len(x)*eps)
    full -- return full diagnostic output (default False)

Returns

    full == False -- coefficients
    full == True -- coefficients, residuals, rank, singular values, rcond.

Warns

    RankWarning -- if rank is reduced and not full output

Do a best fit polynomial of degree 'deg' of 'x' to 'y'.  Return value is a
vector of polynomial coefficients [pk ... p1 p0].  Eg, 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) x N+1 matrix, p is a N+1 length vector, and y
is a len(x) 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. However, this
method is susceptible to rounding errors and generally the singular value
decomposition is preferred and that is the method used here. The singular
value method takes a paramenter, 'rcond', which sets a limit on the
relative size of the smallest singular value to be used in solving the
equation. This may result in lowering the rank of the Vandermonde matrix,
in which case a RankWarning is issued. If polyfit issues a RankWarning, try
a fit of lower degree or replace x by x - x.mean(), both of which will
generally improve the condition number. The routine already normalizes the
vector x by its maximum absolute value to help in this regard. The rcond
parameter may also be set to a value smaller than its default, but this may
result in bad fits. The current default value of rcond is len(x)*eps, where
eps is the relative precision of the floating type being used, generally
around 1e-7 and 2e-16 for IEEE single and double precision respectively.
This value of rcond is fairly conservative but works pretty well when x -
x.mean() is used in place of x.

The warnings can be turned off by:

>>> import numpy
>>> import warnings
>>> warnings.simplefilter('ignore',numpy.RankWarning)

DISCLAIMER: Power series fits are full of pitfalls for the unwary once the
degree of the fit becomes large or the interval of sample points is badly
centered. The basic problem is that the powers x**n are generally a poor
basis for the functions on the sample interval with the result that the
Vandermonde matrix is ill conditioned and computation of the polynomial
values is sensitive to coefficient error. The quality of the resulting fit
should be checked against the data whenever the condition number is large,
as the quality of polynomial fits *can not* be taken for granted. If all
you want to do is draw a smooth curve through the y values and polyfit is
not doing the job, try centering the sample range or look into
scipy.interpolate, which includes some nice spline fitting functions that
may be of use.

For more info, see
http://mathworld.wolfram.com/LeastSquaresFittingPolynomial.html,
but note that the k's and n's in the superscripts and subscripts
on that page.  The linear algebra is correct, however.

See also polyval

polyint(p, m=1, k=None)

 

Return the mth analytical integral of the polynomial p.

If k is None, then zero-valued 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])

polyval(p, x)

 
Evaluate the polynomial p at x.  If x is a polynomial then composition.

Description:

  If p is of length N, this function returns the value:
  p[0]*(x**N-1) + p[1]*(x**N-2) + ... + p[N-2]*x + p[N-1]

  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=None, dtype=None, out=None)

 

Return the product of the elements along the given axis.

Blah, Blah.

product(a, axis=None, dtype=None, out=None)

 

Product of the array elements over the given axis.

Parameters:

a : {array_like}
Array containing elements whose product is desired. If a is not an array, a conversion is attempted.
axis : {None, integer}
Axis over which the product is taken. If None is used, then the product is over all the array elements.
dtype : {None, dtype}, optional
Determines the type of the returned array and of the accumulator where the elements are multiplied. If dtype has the value None and the type of a is an integer type of precision less than the default platform integer, then the default platform integer precision is used. Otherwise, the dtype is the same as that of a.
out : {None, array}, optional
Alternative output array in which to place the result. It must have the same shape as the expected output but the type will be cast if necessary.

Returns:

product_along_axis : {array, scalar}, see dtype parameter above.
Returns an array whose shape is the same as a with the specified axis removed. Returns a 0d array when a is 1d or dtype=None. Returns a reference to the specified output array if specified.

See Also:

ndarray.prod : equivalent method

Examples

>>> product([1.,2.])
2.0
>>> product([1.,2.], dtype=int32)
2
>>> product([[1.,2.],[3.,4.]])
24.0
>>> product([[1.,2.],[3.,4.]], axis=1)
array([  2.,  12.])

ptp(a, axis=None, out=None)

 

Return maximum - minimum along the the given dimension.

Blah, Blah.

put(a, ind, v, mode='raise')

 

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

putmask(...)

 
putmask(a, mask, values) sets a.flat[n] = values[n] for each n where mask.flat[n] is true. If values is not the same size of a and mask then it will repeat. This gives different behavior than a[mask] = values.

rank(a)

 

Return the number of dimensions of a.

In old Numeric, rank was the term used for the number of dimensions. If a is not already an array, a conversion is attempted. Scalars are zero dimensional.

Parameters:

a : {array_like}
Array whose number of dimensions is desired. If a is not an array, a conversion is attempted.

Returns:

number_of_dimensions : {integer}
Returns the number of dimensions.

See Also:

ndim : equivalent function

ndarray.ndim : equivalent method

shape : dimensions of array

ndarray.shape : dimensions of array

Examples

>>> rank([[1,2,3],[4,5,6]])
2
>>> rank(array([[1,2,3],[4,5,6]]))
2
>>> rank(1)
0

ravel(a, order='C')

 

Return a 1d array containing the elements of a.

Returns the elements of a as a 1d array. The elements in the new array are taken in the order specified by the order keyword. The new array is a view of a if possible, otherwise it is a copy.

Parameters:

a : {array_like}

order : {'C','F'}, optional
If order is 'C' the elements are taken in row major order. If order is 'F' they are taken in column major order.

Returns:

1d_array : {array}

See Also:

ndarray.flat : 1d iterator over the array.

ndarray.flatten : 1d array copy of the elements of a in C order.

Examples

>>> x = array([[1,2,3],[4,5,6]])
>>> x
array([[1, 2, 3],
      [4, 5, 6]])
>>> ravel(x)
array([1, 2, 3, 4, 5, 6])

real(val)

 

Return the real part of val.

Useful if val maybe a scalar or an array.

real_if_close(a, tol=100)

 

If a is a complex array, return 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=None)

 

Repeat elements of an array.

Parameters:

a : {array_like}
Blah.
repeats : {integer, integer_array}
The number of repetitions for each element. If a plain integer, then it is applied to all elements. If an array, it needs to be of the same length as the chosen axis.
axis : {None, integer}, optional
The axis along which to repeat values. If None, then this function will operated on the flattened array a and return a similarly flat result.

Returns:

repeated_array : array

See Also:

ndarray.repeat : equivalent method

Examples

>>> repeat([0, 1, 2], 2)
array([0, 0, 1, 1, 2, 2])
>>> repeat([0, 1, 2], [2, 3, 4])
array([0, 0, 1, 1, 1, 2, 2, 2, 2])

reshape(a, newshape, order='C')

 

Returns an array containing the data of a, but with a new shape.

Parameters:

a : array
Array to be reshaped.
newshape : shape tuple or int
The new shape should be compatible with the original shape. If an integer, then the result will be a 1D array of that length.
order : {'C', 'FORTRAN'}, optional
Determines whether the array data should be viewed as in C (row-major) order or FORTRAN (column-major) order.

Returns:

reshaped_array : array
This will be a new view object if possible; otherwise, it will return a copy.

See Also:

ndarray.reshape : Equivalent method.

resize(a, new_shape)

 

Return a new array with the specified shape.

The original array's total size can be any size. The new array is filled with repeated copies of a.

Note that a.resize(new_shape) will fill the array with 0's beyond current definition of a.

Parameters:

a : {array_like}
Array to be reshaped.
new_shape : {tuple}
Shape of reshaped array.

Returns:

reshaped_array : {array}
The new array is formed from the data in the old array, repeated if necessary to fill out the required number of elements, with the new shape.

rollaxis(a, axis, start=0)

 

Return transposed array so that axis is rolled before start.

if a.shape is (3,4,5,6) rollaxis(a, 3, 1).shape is (3,6,4,5) rollaxis(a, 2, 0).shape is (5,3,4,6) rollaxis(a, 1, 3).shape is (3,5,4,6) rollaxis(a, 1, 4).shape is (3,5,6,4)

roots(p)

 

Return the roots of the polynomial coefficients in p.

The values in the rank-1 array p are coefficients of a polynomial. If the length of p is n+1 then the polynomial is p[0] * x**n + p[1] * x**(n-1) + ... + p[n-1]*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, out=None)

 

Round a to the given number of decimals.

The real and imaginary parts of complex numbers are rounded separately. The result of rounding a float is a float so the type must be cast if integers are desired. Nothing is done if the input is an integer array and the decimals parameter has a value >= 0.

Parameters:

a : {array_like}
Array containing numbers whose rounded values are desired. If a is not an array, a conversion is attempted.
decimals : {0, integer}, optional
Number of decimal places to round to. When decimals is negative it specifies the number of positions to the left of the decimal point.
out : {None, array}, optional
Alternative output array in which to place the result. It must have the same shape as the expected output but the type will be cast if necessary.

Returns:

rounded_array : {array}
If out=None, returns a new array of the same type as a containing the rounded values, otherwise a reference to the output array is returned.

See Also:

around : equivalent function

ndarray.round : equivalent method

Notes

Numpy rounds to even. Thus 1.5 and 2.5 round to 2.0, -0.5 and 0.5 round to 0.0, etc. Results may also be surprising due to the inexact representation of decimal fractions in IEEE floating point and the errors introduced when scaling by powers of ten.

Examples

>>> round_([.5, 1.5, 2.5, 3.5, 4.5])
array([ 0.,  2.,  2.,  4.,  4.])
>>> round_([1,2,3,11], decimals=1)
array([ 1,  2,  3, 11])
>>> round_([1,2,3,11], decimals=-1)
array([ 0,  0,  0, 10])

row_stack(tup)

 
Stack arrays in sequence vertically (row wise)

Description:
    Take a sequence of arrays and stack 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:
    >>> import numpy
    >>> a = array((1,2,3))
    >>> b = array((2,3,4))
    >>> numpy.vstack((a,b))
    array([[1, 2, 3],
           [2, 3, 4]])
    >>> a = array([[1],[2],[3]])
    >>> b = array([[2],[3],[4]])
    >>> numpy.vstack((a,b))
    array([[1],
           [2],
           [3],
           [2],
           [3],
           [4]])

savetxt(fname, X, fmt='%.18e', delimiter=' ')

 

Save the data in X to file fname using fmt string to convert the data to strings

fname can be a filename or a file handle. If the filename ends in .gz, the file is automatically saved in compressed gzip format. The load() command understands gzipped files transparently.

Example usage:

save('test.out', X) # X is an array save('test1.out', (x,y,z)) # x,y,z equal sized 1D arrays save('test2.out', x) # x is 1D save('test3.out', x, fmt='%1.4e') # use exponential notation

delimiter is used to separate the fields, eg delimiter ',' for comma-separated values

searchsorted(a, v, side='left')

 

Return indices where keys in v should be inserted to maintain order.

Find the indices into a sorted array such that if the corresponding keys in v were inserted before the indices the order of a would be preserved. If side='left', then the first such index is returned. If side='right', then the last such index is returned. If there is no such index because the key is out of bounds, then the length of a is returned, i.e., the key would need to be appended. The returned index array has the same shape as v.

Parameters:

a : 1-d array
Array must be sorted in ascending order.
v : array or list type
Array of keys to be searched for in a.
side : {'left', 'right'}, optional
If 'left', the index of the first location where the key could be inserted is found, if 'right', the index of the last such element is returned. If the is no such element, then either 0 or N is returned, where N is the size of the array.

Returns:

indices : integer array
Array of insertion points with the same shape as v.

See Also:

sort : Inplace sort.

histogram : Produce histogram from 1-d data.

Notes

The array a must be 1-d and is assumed to be sorted in ascending order. Searchsorted uses binary search to find the required insertion points.

Examples

>>> searchsorted([1,2,3,4,5],[6,4,0])
array([5, 3, 0])

select(condlist, choicelist, default=0)

 
Return an array composed of different elements in choicelist,
depending on the list of conditions.

:Parameters:
    condlist : list of N boolean arrays of length M
        The conditions C_0 through C_(N-1) which determine
        from which vector the output elements are taken.
    choicelist : list of N arrays of length M
        Th vectors V_0 through V_(N-1), from which the output
        elements are chosen.

:Returns:
    output : 1-dimensional array of length M
        The output at position m is the m-th element of the first
        vector V_n for which C_n[m] is non-zero.  Note that the
        output depends on the order of conditions, since the
        first satisfied condition is used.

        Equivalent to:

            output = []
            for m in range(M):
                output += [V[m] for V,C in zip(values,cond) if C[m]]
                          or [default]

set_numeric_ops(op=func, ...)

 
Set some or all of the number methods for all array objects. Do not forget **dict can be used as the argument list. Return the functions that were replaced, which can be stored and set later.

set_printoptions(precision=None, threshold=None, edgeitems=None, linewidth=None, suppress=None, nanstr=None, infstr=None)

 
Set options associated with printing.
Parameters:
  • precision (int) - Number of digits of precision for floating point output (default 8).
  • threshold (int) - Total number of array elements which trigger summarization rather than full repr (default 1000).
  • edgeitems (int) - Number of array items in summary at beginning and end of each dimension (default 3).
  • linewidth (int) - The number of characters per line for the purpose of inserting line breaks (default 75).
  • suppress (bool) - Whether or not suppress printing of small floating point values using scientific notation (default False).
  • nanstr (string) - String representation of floating point not-a-number (default nan).
  • infstr (string) - String representation of floating point infinity (default inf).

set_string_function(f, repr=1)

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

setdiff1d(ar1, ar2)

 
Set difference of 1D arrays with unique elements.

Use unique1d() to generate arrays with only unique elements to use as inputs
to this function.

:Parameters:
  - `ar1` : array
  - `ar2` : array

:Returns:
  - `difference` : array
    The values in ar1 that are not in ar2.

:See also:
  numpy.lib.arraysetops has a number of other functions for performing set
  operations on arrays.

seterr(all=None, divide=None, over=None, under=None, invalid=None)

 

Set how floating-point errors are handled.

Valid values for each type of error are the strings "ignore", "warn", "raise", and "call". Returns the old settings. If 'all' is specified, values that are not otherwise specified will be set to 'all', otherwise they will retain their old values.

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') # doctest: +SKIP
{'over': 'ignore', 'divide': 'ignore', 'invalid': 'ignore', 'under': 'ignore'}
>>> seterr(all='warn', over='raise') # doctest: +SKIP
{'over': 'raise', 'divide': 'ignore', 'invalid': 'ignore', 'under': 'ignore'}
>>> int16(32000) * int16(3) # doctest: +SKIP
Traceback (most recent call last):
      File "<stdin>", line 1, in ?
FloatingPointError: overflow encountered in short_scalars
>>> seterr(all='ignore') # doctest: +SKIP
{'over': 'ignore', 'divide': 'ignore', 'invalid': 'ignore', 'under': 'ignore'}

seterrcall(func)

 

Set the callback function used when a floating-point error handler is set to 'call' or the object with a write method for use when the floating-point error handler is set to 'log'

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

setmember1d(ar1, ar2)

 
Return a boolean array of shape of ar1 containing True where the elements
of ar1 are in ar2 and False otherwise.

Use unique1d() to generate arrays with only unique elements to use as inputs
to this function.

:Parameters:
  - `ar1` : array
  - `ar2` : array

:Returns:
  - `mask` : bool array
    The values ar1[mask] are in ar2.

:See also:
  numpy.lib.arraysetops has a number of other functions for performing set
  operations on arrays.

setxor1d(ar1, ar2)

 
Set exclusive-or of 1D arrays with unique elements.

Use unique1d() to generate arrays with only unique elements to use as inputs
to this function.

:Parameters:
  - `ar1` : array
  - `ar2` : array

:Returns:
  - `xor` : array
    The values that are only in one, but not both, of the input arrays.

:See also:
  numpy.lib.arraysetops has a number of other functions for performing set
  operations on arrays.

shape(a)

 

Return the shape of a.

Parameters:

a : {array_like}
Array whose shape is desired. If a is not an array, a conversion is attempted.

Returns:

tuple_of_integers :
The elements of the tuple are the length of the corresponding array dimension.

Examples

>>> shape(eye(3))
(3, 3)
>>> shape([[1,2]])
(1, 2)

size(a, axis=None)

 

Return the number of elements along given axis.

Parameters:

a : {array_like}
Array whose axis size is desired. If a is not an array, a conversion is attempted.
axis : {None, integer}, optional
Axis along which the elements are counted. None means all elements in the array.

Returns:

element_count : {integer}
Count of elements along specified axis.

See Also:

shape : dimensions of array

ndarray.shape : dimensions of array

ndarray.size : number of elements in array

Examples

>>> a = array([[1,2,3],[4,5,6]])
>>> size(a)
6
>>> size(a,1)
3
>>> size(a,0)
2

sometrue(a, axis=None, out=None)

 

Perform a logical_or over the given axis.

See Also:

ndarray.any : equivalent method

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

 

Return copy of 'a' sorted along the given axis.

Perform an inplace sort along the given axis using the algorithm specified by the kind keyword.

Parameters:

a : array
Array to be sorted.
axis : {None, int} optional
Axis along which to sort. None indicates that the flattened array should be used.
kind : {'quicksort', 'mergesort', 'heapsort'}, optional
Sorting algorithm to use.
order : {None, list type}, optional
When a is an array with fields defined, this argument specifies which fields to compare first, second, etc. Not all fields need be specified.

Returns:

sorted_array : array of same type as a

See Also:

argsort : Indirect sort.

lexsort : Indirect stable sort on multiple keys.

searchsorted : Find keys in sorted array.

Notes

The various sorts are characterized by average speed, worst case performance, need for work space, and whether they are stable. A stable sort keeps items with the same key in the same relative order. The three available algorithms have the following properties:

kind speed worst case work space stable
quicksort 1 O(n^2) 0 no
mergesort 2 O(n*log(n)) ~n/2 yes
heapsort 3 O(n*log(n)) 0 no

All the sort algorithms make temporary copies of the data when the sort is not along the last axis. Consequently, sorts along the last axis are faster and use less space than sorts along other axis.

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.

split(ary, indices_or_sections, axis=0)

 
Divide an array into a list of sub-arrays.

Description:
   Divide ary into a list of sub-arrays 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.

Arguments:
   ary -- N-D array.
      Array to be divided into sub-arrays.
   indices_or_sections -- integer or 1D array.
      If integer, defines the number of (close to) equal sized
      sub-arrays.  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 sub-array 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

squeeze(a)

 

Remove single-dimensional entries from the shape of a.

Examples

>>> x = array([[[1,1,1],[2,2,2],[3,3,3]]])
>>> x
array([[[1, 1, 1],
      [2, 2, 2],
      [3, 3, 3]]])
>>> x.shape
(1, 3, 3)
>>> squeeze(x).shape
(3, 3)

std(a, axis=None, dtype=None, out=None)

 

Compute the standard deviation along the specified axis.

Returns the standard deviation of the array elements, a measure of the spread of a distribution. The standard deviation is computed for the flattened array by default, otherwise over the specified axis.

Parameters:

a : {array_like}
Array containing numbers whose standard deviation is desired. If a is not an array, a conversion is attempted.
axis : {None, integer}, optional
Axis along which the standard deviation is computed. The default is to compute the standard deviation of the flattened array.
dtype : {None, dtype}, optional
Type to use in computing the standard deviation. For arrays of integer type the default is float32, for arrays of float types it is the same as the array type.
out : {None, array}, optional
Alternative output array in which to place the result. It must have the same shape as the expected output but the type will be cast if necessary.

Returns:

standard_deviation : {array, scalar}, see dtype parameter above.
If out=None, returns a new array containing the standard deviation, otherwise a reference to the output array is returned.

See Also:

var : Variance

mean : Average

Notes

The standard deviation is the square root of the average of the squared deviations from the mean, i.e. var = sqrt(mean((x - x.mean())**2)). The computed standard deviation is biased, i.e., the mean is computed by dividing by the number of elements, N, rather than by N-1.

Examples

>>> a = array([[1,2],[3,4]])
>>> std(a)
1.1180339887498949
>>> std(a,0)
array([ 1.,  1.])
>>> std(a,1)
array([ 0.5,  0.5])

sum(a, axis=None, dtype=None, out=None)

 

Sum the array over the given axis.

Parameters:

a : {array_type}
Array containing elements whose sum is desired. If a is not an array, a conversion is attempted.
axis : {None, integer}
Axis over which the sum is taken. If None is used, then the sum is over all the array elements.
dtype : {None, dtype}, optional
Determines the type of the returned array and of the accumulator where the elements are summed. If dtype has the value None and the type of a is an integer type of precision less than the default platform integer, then the default platform integer precision is used. Otherwise, the dtype is the same as that of a.
out : {None, array}, optional
Array into which the sum can be placed. It's type is preserved and it must be of the right shape to hold the output.

Returns:

sum_along_axis : {array, scalar}, see dtype parameter above.
Returns an array whose shape is the same as a with the specified axis removed. Returns a 0d array when a is 1d or dtype=None. Returns a reference to the specified output array if specified.

See Also:

ndarray.sum : equivalent method

Examples

>>> sum([0.5, 1.5])
2.0
>>> sum([0.5, 1.5], dtype=N.int32)
1
>>> sum([[0, 1], [0, 5]])
6
>>> sum([[0, 1], [0, 5]], axis=1)
array([1, 5])

swapaxes(a, axis1, axis2)

 

Return array a with axis1 and axis2 interchanged.

Blah, Blah.

take(a, indices, axis=None, out=None, mode='raise')

 

Return an array formed from the elements of a at the given indices.

This function does the same thing as "fancy" indexing; however, it can be easier to use if you need to specify a given axis.

Parameters:

a : array
The source array
indices : int array
The indices of the values to extract.
axis : {None, int}, optional
The axis over which to select values. None signifies that the operation should be performed over the flattened array.
out : {None, array}, optional
If provided, the result will be inserted into this array. It should be of the appropriate shape and dtype.
mode : {'raise', 'wrap', 'clip'}, optional
Specifies how out-of-bounds indices will behave. 'raise' -- raise an error 'wrap' -- wrap around 'clip' -- clip to the range

Returns:

subarray : array
The returned array has the same type as a.

See Also:

ndarray.take : equivalent method

tensordot(a, b, axes=2)

 

tensordot returns the product for any (ndim >= 1) arrays.

r_{xxx, yyy} = \sum_k a_{xxx,k} b_{k,yyy} where

the axes to be summed over are given by the axes argument. the first element of the sequence determines the axis or axes in arr1 to sum over, and the second element in axes argument sequence determines the axis or axes in arr2 to sum over.

When there is more than one axis to sum over, the corresponding arguments to axes should be sequences of the same length with the first axis to sum over given first in both sequences, the second axis second, and so forth.

If the axes argument is an integer, N, then the last N dimensions of a and first N dimensions of b are summed over.

test(*args, **kw)

source code 
Run Numpy module test suite with level and verbosity.

level:
  None           --- do nothing, return None
  < 0            --- scan for tests of level=abs(level),
                     don't run them, return TestSuite-list
  > 0            --- scan for tests of level, run them,
                     return TestRunner
  > 10           --- run all tests (same as specifying all=True).
                     (backward compatibility).

verbosity:
  >= 0           --- show information messages
  > 1            --- show warnings on missing tests

all:
  True            --- run all test files (like self.testall())
  False (default) --- only run test files associated with a module

sys_argv          --- replacement of sys.argv[1:] during running
                      tests.

testcase_pattern  --- run only tests that match given pattern.

It is assumed (when all=False) that package tests suite follows
the following convention: for each package module, there exists
file <packagepath>/tests/test_<modulename>.py that defines
TestCase classes (with names having prefix 'test_') with methods
(with names having prefixes 'check_' or 'bench_'); each of these
methods are called when running unit tests.

tile(A, reps)

 
Repeat an array the number of times given in the integer tuple, reps.

If reps has length d, the result will have dimension of max(d, A.ndim).
If reps is scalar it is treated as a 1-tuple.

If A.ndim < d, A is promoted to be d-dimensional by prepending new axes.
So a shape (3,) array is promoted to (1,3) for 2-D replication,
or shape (1,1,3) for 3-D replication.
If this is not the desired behavior, promote A to d-dimensions manually
before calling this function.

If d < A.ndim, tup is promoted to A.ndim by pre-pending 1's to it.  Thus
for an A.shape of (2,3,4,5), a tup of (2,2) is treated as (1,1,2,2)


Examples:
>>> a = array([0,1,2])
>>> tile(a,2)
array([0, 1, 2, 0, 1, 2])
>>> tile(a,(1,2))
array([[0, 1, 2, 0, 1, 2]])
>>> tile(a,(2,2))
array([[0, 1, 2, 0, 1, 2],
       [0, 1, 2, 0, 1, 2]])
>>> tile(a,(2,1,2))
array([[[0, 1, 2, 0, 1, 2]],
<BLANKLINE>
       [[0, 1, 2, 0, 1, 2]]])

See Also:
   repeat

trace(a, offset=0, axis1=0, axis2=1, dtype=None, out=None)

 

Return the sum along diagonals of the array.

If a is 2-d, returns the sum along the diagonal of self with the given offset, i.e., the collection of elements of the form a[i,i+offset]. If a has more than two dimensions, then the axes specified by axis1 and axis2 are used to determine the 2-d subarray whose trace is returned. The shape of the resulting array can be determined by removing axis1 and axis2 and appending an index to the right equal to the size of the resulting diagonals. Arrays of integer type are summed

Parameters:

a : {array_like}
Array from whis the diagonals are taken.
offset : {0, integer}, optional
Offset of the diagonal from the main diagonal. Can be both positive and negative. Defaults to main diagonal.
axis1 : {0, integer}, optional
Axis to be used as the first axis of the 2-d subarrays from which the diagonals should be taken. Defaults to first axis.
axis2 : {1, integer}, optional
Axis to be used as the second axis of the 2-d subarrays from which the diagonals should be taken. Defaults to second axis.
dtype : {None, dtype}, optional
Determines the type of the returned array and of the accumulator where the elements are summed. If dtype has the value None and a is of integer type of precision less than the default integer precision, then the default integer precision is used. Otherwise, the precision is the same as that of a.
out : {None, array}, optional
Array into which the sum can be placed. It's type is preserved and it must be of the right shape to hold the output.

Returns:

sum_along_diagonals : array
If a is 2-d, a 0-d array containing the diagonal is returned. If a has larger dimensions, then an array of diagonals is returned.

Examples

>>> trace(eye(3))
3.0
>>> a = arange(8).reshape((2,2,2))
>>> trace(a)
array([6, 8])

transpose(a, axes=None)

 

Return a view of the array with dimensions permuted.

Permutes axis according to list axes. If axes is None (default) returns array with dimensions reversed.

trapz(y, x=None, dx=1.0, axis=-1)

 
Integrate y(x) using samples along the given axis and the composite trapezoidal rule. If x is None, spacing given by dx is assumed.

tril(m, k=0)

 
returns the elements on and below the k-th diagonal of m. k=0 is the main diagonal, k > 0 is above and k < 0 is below the main diagonal.

triu(m, k=0)

 
returns the elements on and above the k-th diagonal of m. k=0 is the main diagonal, k > 0 is above and k < 0 is below the main diagonal.

union1d(ar1, ar2)

 
Union of 1D arrays with unique elements.

Use unique1d() to generate arrays with only unique elements to use as inputs
to this function.

:Parameters:
  - `ar1` : array
  - `ar2` : array

:Returns:
  - `union` : array

:See also:
  numpy.lib.arraysetops has a number of other functions for performing set
  operations on arrays.

unique(x)

 

Return 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, return_index=False)

 
Find the unique elements of 1D array.

Most of the other array set operations operate on the unique arrays
generated by this function.

:Parameters:
  - `ar1` : array
    This array will be flattened if it is not already 1D.
  - `return_index` : bool, optional
    If True, also return the indices against ar1 that result in the unique
    array.

:Returns:
  - `unique` : array
    The unique values.
  - `unique_indices` : int array, optional
    The indices of the unique values. Only provided if return_index is True.

:See also:
  numpy.lib.arraysetops has a number of other functions for performing set
  operations on arrays.

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 usage:
  p = x.argmax()
  idx = unravel_index(p,x.shape)
  x[idx] == x.max()

Note:  x.flat[p] == x.max()

  Thus, it may be easier to use flattened indexing than to re-map
  the index to a tuple.

vander(x, N=None)

 

X = vander(x,N=None)

The Vandermonde matrix of vector x. The i-th column of X is the the i-th power of x. N is the maximum power to compute; if N is None it defaults to len(x).

var(a, axis=None, dtype=None, out=None)

 

Compute the variance along the specified axis.

Returns the variance of the array elements, a measure of the spread of a distribution. The variance is computed for the flattened array by default, otherwise over the specified axis.

Parameters:

a : {array_like}
Array containing numbers whose variance is desired. If a is not an array, a conversion is attempted.
axis : {None, integer}, optional
Axis along which the variance is computed. The default is to compute the variance of the flattened array.
dtype : {None, dtype}, optional
Type to use in computing the variance. For arrays of integer type the default is float32, for arrays of float types it is the same as the array type.
out : {None, array}, optional
Alternative output array in which to place the result. It must have the same shape as the expected output but the type will be cast if necessary.

Returns:

variance : {array, scalar}, see dtype parameter above
If out=None, returns a new array containing the variance, otherwise a reference to the output array is returned.

See Also:

std : Standard deviation

mean : Average

Notes

The variance is the average of the squared deviations from the mean, i.e. var = mean((x - x.mean())**2). The computed variance is biased, i.e., the mean is computed by dividing by the number of elements, N, rather than by N-1.

Examples

>>> a = array([[1,2],[3,4]])
>>> var(a)
1.25
>>> var(a,0)
array([ 1.,  1.])
>>> var(a,1)
array([ 0.25,  0.25])

vdot(a, b)

 

Returns the dot product of 2 vectors (or anything that can be made into a vector).

Note: this is not the same as `dot`, as it takes the conjugate of its first argument if complex and always returns a scalar.

vsplit(ary, indices_or_sections)

 
Split ary into multiple rows of sub-arrays

Description:
    Split 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 sub-arrays equally sized, the
    operation throws a ValueError exception. See array_split and
    split for other options on indices_or_sections.
Arguments:
   ary -- N-D array.
      Array to be divided into sub-arrays.
   indices_or_sections -- integer or 1D array.
      If integer, defines the number of (close to) equal sized
      sub-arrays.  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 sub-array equal to the original
      array.
Returns:
    sequence of sub-arrays.  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?
Related:
    vstack, split, array_split, hsplit, dsplit.
Examples:
    import numpy
    >>> a = array([[1,2,3,4],
    ...            [1,2,3,4]])
    >>> numpy.vsplit(a,2)
    [array([[1, 2, 3, 4]]), array([[1, 2, 3, 4]])]

vstack(tup)

 
Stack arrays in sequence vertically (row wise)

Description:
    Take a sequence of arrays and stack 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:
    >>> import numpy
    >>> a = array((1,2,3))
    >>> b = array((2,3,4))
    >>> numpy.vstack((a,b))
    array([[1, 2, 3],
           [2, 3, 4]])
    >>> a = array([[1],[2],[3]])
    >>> b = array([[2],[3],[4]])
    >>> numpy.vstack((a,b))
    array([[1],
           [2],
           [3],
           [2],
           [3],
           [4]])

where(...)

 
where(condition, x, y) or where(condition)

Return elements from `x` or `y`, depending on `condition`.

*Parameters*:
    condition : array of bool
        When True, yield x, otherwise yield y.
    x,y : 1-dimensional arrays
        Values from which to choose.

*Notes*
    This is equivalent to

        [xv if c else yv for (c,xv,yv) in zip(condition,x,y)]

    The result is shaped like `condition` and has elements of `x`
    or `y` where `condition` is respectively True or False.

    In the special case, where only `condition` is given, the
    tuple condition.nonzero() is returned, instead.

*Examples*
    >>> where([True,False,True],[1,2,3],[4,5,6])
    array([1, 5, 3])

zeros(...)

 

zeros((d1,...,dn),dtype=float,order='C')

Return a new array of shape (d1,...,dn) and type typecode with all it's entries initialized to zero.

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.

Variables Details [hide private]

ScalarType

Value:
(<type 'int'>,
 <type 'float'>,
 <type 'complex'>,
 <type 'long'>,
 <type 'bool'>,
 <type 'str'>,
 <type 'unicode'>,
 <type 'buffer'>,
...

cast

Value:
{<type 'numpy.int64'>: <function <lambda> at 0x8544614>, <type 'numpy.\
int16'>: <function <lambda> at 0x854464c>, <type 'numpy.float32'>: <fu\
nction <lambda> at 0x8544684>, <type 'numpy.bool_'>: <function <lambda\
> at 0x85446bc>, <type 'numpy.uint8'>: <function <lambda> at 0x85446f4\
>, <type 'numpy.object_'>: <function <lambda> at 0x854472c>, <type 'nu\
mpy.float64'>: <function <lambda> at 0x854479c>, <type 'numpy.uint16'>\
: <function <lambda> at 0x854480c>, <type 'numpy.string_'>: <function \
<lambda> at 0x8544844>, <type 'numpy.int8'>: <function <lambda> at 0x8\
...

index_exp

Value:
<numpy.lib.index_tricks._index_expression_class object at 0x85f7aac>

nbytes

Value:
{<type 'numpy.int64'>: 8, <type 'numpy.int16'>: 2, <type 'numpy.float3\
2'>: 4, <type 'numpy.bool_'>: 1, <type 'numpy.uint8'>: 1, <type 'numpy\
.object_'>: 4, <type 'numpy.int32'>: 4, <type 'numpy.float64'>: 8, <ty\
pe 'numpy.int32'>: 4, <type 'numpy.uint16'>: 2, <type 'numpy.string_'>\
: 0, <type 'numpy.int8'>: 1, <type 'numpy.float96'>: 12, <type 'numpy.\
uint32'>: 4, <type 'numpy.complex192'>: 24, <type 'numpy.unicode_'>: 0\
, <type 'numpy.complex64'>: 8, <type 'numpy.uint32'>: 4, <type 'numpy.\
void'>: 0, <type 'numpy.complex128'>: 16, <type 'numpy.uint64'>: 8}

s_

Value:
<numpy.lib.index_tricks._index_expression_class object at 0x85f7aec>

sctypeDict

Value:
{0: <type 'numpy.bool_'>,
 1: <type 'numpy.int8'>,
 2: <type 'numpy.uint8'>,
 3: <type 'numpy.int16'>,
 4: <type 'numpy.uint16'>,
 5: <type 'numpy.int32'>,
 6: <type 'numpy.uint32'>,
 7: <type 'numpy.int32'>,
...

sctypeNA

Value:
{'?': 'Bool',
 'B': 'UInt8',
 'Bool': <type 'numpy.bool_'>,
 'Complex32': <type 'numpy.complex64'>,
 'Complex64': <type 'numpy.complex128'>,
 'Complex96': <type 'numpy.complex192'>,
 'D': 'Complex64',
 'F': 'Complex32',
...

sctypes

Value:
{'complex': [<type 'numpy.complex64'>,
             <type 'numpy.complex128'>,
             <type 'numpy.complex192'>],
 'float': [<type 'numpy.float32'>,
           <type 'numpy.float64'>,
           <type 'numpy.float96'>],
 'int': [<type 'numpy.int8'>,
         <type 'numpy.int16'>,
...

typeDict

Value:
{0: <type 'numpy.bool_'>,
 1: <type 'numpy.int8'>,
 2: <type 'numpy.uint8'>,
 3: <type 'numpy.int16'>,
 4: <type 'numpy.uint16'>,
 5: <type 'numpy.int32'>,
 6: <type 'numpy.uint32'>,
 7: <type 'numpy.int32'>,
...

typeNA

Value:
{'?': 'Bool',
 'B': 'UInt8',
 'Bool': <type 'numpy.bool_'>,
 'Complex32': <type 'numpy.complex64'>,
 'Complex64': <type 'numpy.complex128'>,
 'Complex96': <type 'numpy.complex192'>,
 'D': 'Complex64',
 'F': 'Complex32',
...

typecodes

Value:
{'All': '?bhilqpBHILQPfdgFDGSUVO',
 'AllFloat': 'fdgFDG',
 'AllInteger': 'bBhHiIlLqQpP',
 'Character': 'S1',
 'Complex': 'FDG',
 'Float': 'fdg',
 'Integer': 'bhilqp',
 'UnsignedInteger': 'BHILQP'}