3. numpy.lib

Basic functions used by several sub-packages and useful to have in the main name-space.

3.1. Type Handling

iscomplexobj Test for complex object, scalar result
isrealobj Test for real object, scalar result
iscomplex Test for complex elements, array result
isreal Test for real elements, array result
imag Imaginary part
real Real part
real_if_close Turns complex number with tiny imaginary part to real
isneginf Tests for negative infinity, array result
isposinf Tests for positive infinity, array result
isnan Tests for nans, array result
isinf Tests for infinity, array result
isfinite Tests for finite numbers, array result
isscalar True if argument is a scalar
nan_to_num Replaces NaN’s with 0 and infinities with large numbers
cast Dictionary of functions to force cast to each type
common_type Determine the minimum common type code for a group of arrays
mintypecode Return minimal allowed common typecode.

3.2. Index Tricks

mgrid Method which allows easy construction of N-d ‘mesh-grids’
r_ Append and construct arrays: turns slice objects into ranges and concatenates them, for 2d arrays appends rows.
index_exp Konrad Hinsen’s index_expression class instance which can be useful for building complicated slicing syntax.

3.3. Useful Functions

select Extension of where to multiple conditions and choices
extract Extract 1d array from flattened array according to mask
insert Insert 1d array of values into Nd array according to mask
linspace Evenly spaced samples in linear space
logspace Evenly spaced samples in logarithmic space
fix Round x to nearest integer towards zero
mod Modulo mod(x,y) = x % y except keeps sign of y
amax Array maximum along axis
amin Array minimum along axis
ptp Array max-min along axis
cumsum Cumulative sum along axis
prod Product of elements along axis
cumprod Cumluative product along axis
diff Discrete differences along axis
angle Returns angle of complex argument
unwrap Unwrap phase along given axis (1-d algorithm)
sort_complex Sort a complex-array (based on real, then imaginary)
trim_zeros Trim the leading and trailing zeros from 1D array.
vectorize A class that wraps a Python function taking scalar arguments into a generalized function which can handle arrays of arguments using the broadcast rules of numerix Python.

3.4. Shape Manipulation

squeeze Return a with length-one dimensions removed.
atleast_1d Force arrays to be > 1D
atleast_2d Force arrays to be > 2D
atleast_3d Force arrays to be > 3D
vstack Stack arrays vertically (row on row)
hstack Stack arrays horizontally (column on column)
column_stack Stack 1D arrays as columns into 2D array
dstack Stack arrays depthwise (along third dimension)
stack Stack arrays along a new axis
split Divide array into a list of sub-arrays
hsplit Split into columns
vsplit Split into rows
dsplit Split along third dimension

3.5. Matrix (2D Array) Manipulations

fliplr 2D array with columns flipped
flipud 2D array with rows flipped
rot90 Rotate a 2D array a multiple of 90 degrees
eye Return a 2D array with ones down a given diagonal
diag Construct a 2D array from a vector, or return a given diagonal from a 2D array.
mat Construct a Matrix
bmat Build a Matrix from blocks

3.6. Polynomials

poly1d A one-dimensional polynomial class
poly Return polynomial coefficients from roots
roots Find roots of polynomial given coefficients
polyint Integrate polynomial
polyder Differentiate polynomial
polyadd Add polynomials
polysub Substract polynomials
polymul Multiply polynomials
polydiv Divide polynomials
polyval Evaluate polynomial at given argument

3.7. Import Tricks

ppimport Postpone module import until trying to use it
ppimport_attr Postpone module import until trying to use its attribute
ppresolve Import postponed module and return it.

3.8. Machine Arithmetics

machar_single Single precision floating point arithmetic parameters
machar_double Double precision floating point arithmetic parameters

3.9. Threading Tricks

ParallelExec Execute commands in parallel thread.

3.10. 1D Array Set Operations

Set operations for 1D numeric arrays based on sort() function.

ediff1d Array difference (auxiliary function).
unique Unique elements of an array.
intersect1d Intersection of 1D arrays with unique elements.
setxor1d Set exclusive-or of 1D arrays with unique elements.
in1d Test whether elements in a 1D array are also present in another array.
union1d Union of 1D arrays with unique elements.
setdiff1d Set difference of 1D arrays with unique elements.

3.11. Functions

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.
add_newdoc_ufunc(ufunc, new_docstring) Replace the docstring for a ufunc with new_docstring.
angle(z[, deg]) Return the angle of the complex argument.
append(arr, values[, axis]) Append values to the end of an array.
apply_along_axis(func1d, axis, arr, *args, ...) Apply a function to 1-D slices along the given axis.
apply_over_axes(func, a, axes) Apply a function repeatedly over multiple axes.
array_split(ary, indices_or_sections[, axis]) Split an array into multiple sub-arrays.
asarray_chkfinite(a[, dtype, order]) Convert the input to an array, checking for NaNs or Infs.
asfarray(a[, dtype]) Return an array converted to a float type.
asscalar(a) Convert an array of size 1 to its scalar equivalent.
average(a[, axis, weights, returned]) Compute the weighted average along the specified axis.
bartlett(M) Return the Bartlett window.
bincount(x[, weights, minlength]) Count number of occurrences of each value in array of non-negative ints.
blackman(M) Return the Blackman window.
broadcast_arrays(*args, **kwargs) Broadcast any number of arrays against each other.
broadcast_to(array, shape[, subok]) Broadcast an array to a new shape.
byte_bounds(a) Returns pointers to the end-points of an array.
column_stack(tup) Stack 1-D arrays as columns into a 2-D array.
common_type(*arrays) Return a scalar type which is common to the input arrays.
copy(a[, order]) Return an array copy of the given object.
corrcoef(x[, y, rowvar, bias, ddof]) Return Pearson product-moment correlation coefficients.
cov(m[, y, rowvar, bias, ddof, fweights, ...]) Estimate a covariance matrix, given data and weights.
delete(arr, obj[, axis]) Return a new array with sub-arrays along an axis deleted.
deprecate(*args, **kwargs) Issues a DeprecationWarning, adds warning to old_name‘s docstring, rebinds old_name.__name__ and returns the new function object.
deprecate_with_doc(msg)
diag(v[, k]) Extract a diagonal or construct a diagonal array.
diag_indices(n[, ndim]) Return the indices to access the main diagonal of an array.
diag_indices_from(arr) Return the indices to access the main diagonal of an n-dimensional array.
diagflat(v[, k]) Create a two-dimensional array with the flattened input as a diagonal.
diff(a[, n, axis]) Calculate the n-th order discrete difference along given axis.
digitize(x, bins[, right]) Return the indices of the bins to which each value in input array belongs.
disp(mesg[, device, linefeed]) Display a message on a device.
dsplit(ary, indices_or_sections) Split array into multiple sub-arrays along the 3rd axis (depth).
dstack(tup) Stack arrays in sequence depth wise (along third axis).
ediff1d(ary[, to_end, to_begin]) The differences between consecutive elements of an array.
expand_dims(a, axis) Expand the shape of an array.
extract(condition, arr) Return the elements of an array that satisfy some condition.
eye(N[, M, k, dtype]) Return a 2-D array with ones on the diagonal and zeros elsewhere.
fill_diagonal(a, val[, wrap]) Fill the main diagonal of the given array of any dimensionality.
fix(x[, y]) Round to nearest integer towards zero.
fliplr(m) Flip array in the left/right direction.
flipud(m) Flip array in the up/down direction.
fromregex(file, regexp, dtype) Construct an array from a text file, using regular expression parsing.
fv(rate, nper, pmt, pv[, when]) Compute the future value.
genfromtxt(fname[, dtype, comments, ...]) Load data from a text file, with missing values handled as specified.
get_array_wrap(*args) Find the wrapper for the array with the highest priority.
get_include() Return the directory that contains the NumPy *.h header files.
gradient(f, *varargs, **kwargs) Return the gradient of an N-dimensional array.
hamming(M) Return the Hamming window.
hanning(M) Return the Hanning window.
histogram(a[, bins, range, normed, weights, ...]) Compute the histogram of a set of data.
histogram2d(x, y[, bins, range, normed, weights]) Compute the bi-dimensional histogram of two data samples.
histogramdd(sample[, bins, range, normed, ...]) Compute the multidimensional histogram of some data.
hsplit(ary, indices_or_sections) Split an array into multiple sub-arrays horizontally (column-wise).
i0(x) Modified Bessel function of the first kind, order 0.
imag(val) Return the imaginary part of the elements of the array.
in1d(ar1, ar2[, assume_unique, invert]) Test whether each element of a 1-D array is also present in a second array.
info([object, maxwidth, output, toplevel]) Get help information for a function, class, or module.
insert(arr, obj, values[, axis]) Insert values along the given axis before the given indices.
interp(x, xp, fp[, left, right, period]) One-dimensional linear interpolation.
intersect1d(ar1, ar2[, assume_unique]) Find the intersection of two arrays.
ipmt(rate, per, nper, pv[, fv, when]) Compute the interest portion of a payment.
irr(values) Return the Internal Rate of Return (IRR).
iscomplex(x) Returns a bool array, where True if input element is complex.
iscomplexobj(x) Check for a complex type or an array of complex numbers.
isneginf(x[, y]) Test element-wise for negative infinity, return result as bool array.
isposinf(x[, y]) Test element-wise for positive infinity, return result as bool array.
isreal(x) Returns a bool array, where True if input element is real.
isrealobj(x) Return True if x is a not complex type or an array of complex numbers.
issubclass_(arg1, arg2) Determine if a class is a subclass of a second class.
issubdtype(arg1, arg2) Returns True if first argument is a typecode lower/equal in type hierarchy.
issubsctype(arg1, arg2) Determine if the first argument is a subclass of the second argument.
iterable(y) Check whether or not an object can be iterated over.
ix_(*args) Construct an open mesh from multiple sequences.
kaiser(M, beta) Return the Kaiser window.
kron(a, b) Kronecker product of two arrays.
load(file[, mmap_mode, allow_pickle, ...]) Load arrays or pickled objects from .npy, .npz or pickled files.
loads loads(string) – Load a pickle from the given string
loadtxt(fname[, dtype, comments, delimiter, ...]) Load data from a text file.
lookfor(what[, module, import_modules, ...]) Do a keyword search on docstrings.
mafromtxt(fname, **kwargs) Load ASCII data stored in a text file and return a masked array.
mask_indices(n, mask_func[, k]) Return the indices to access (n, n) arrays, given a masking function.
median(a[, axis, out, overwrite_input, keepdims]) Compute the median along the specified axis.
meshgrid(*xi, **kwargs) Return coordinate matrices from coordinate vectors.
mintypecode(typechars[, typeset, default]) Return the character for the minimum-size type to which given types can be safely cast.
mirr(values, finance_rate, reinvest_rate) Modified internal rate of return.
msort(a) Return a copy of an array sorted along the first axis.
nan_to_num(x) Replace nan with zero and inf with finite numbers.
nanargmax(a[, axis]) Return the indices of the maximum values in the specified axis ignoring NaNs.
nanargmin(a[, axis]) Return the indices of the minimum values in the specified axis ignoring NaNs.
nanmax(a[, axis, out, keepdims]) Return the maximum of an array or maximum along an axis, ignoring any NaNs.
nanmean(a[, axis, dtype, out, keepdims]) Compute the arithmetic mean along the specified axis, ignoring NaNs.
nanmedian(a[, axis, out, overwrite_input, ...]) Compute the median along the specified axis, while ignoring NaNs.
nanmin(a[, axis, out, keepdims]) Return minimum of an array or minimum along an axis, ignoring any NaNs.
nanpercentile(a, q[, axis, out, ...]) Compute the qth percentile of the data along the specified axis, while ignoring nan values.
nanprod(a[, axis, dtype, out, keepdims]) Return the product of array elements over a given axis treating Not a Numbers (NaNs) as zero.
nanstd(a[, axis, dtype, out, ddof, keepdims]) Compute the standard deviation along the specified axis, while ignoring NaNs.
nansum(a[, axis, dtype, out, keepdims]) Return the sum of array elements over a given axis treating Not a Numbers (NaNs) as zero.
nanvar(a[, axis, dtype, out, ddof, keepdims]) Compute the variance along the specified axis, while ignoring NaNs.
ndfromtxt(fname, **kwargs) Load ASCII data stored in a file and return it as a single array.
nper(rate, pmt, pv[, fv, when]) Compute the number of periodic payments.
npv(rate, values) Returns the NPV (Net Present Value) of a cash flow series.
packbits(myarray[, axis]) Packs the elements of a binary-valued array into bits in a uint8 array.
pad(array, pad_width[, mode]) Pads an array.
percentile(a, q[, axis, out, ...]) Compute the qth percentile of the data along the specified axis.
piecewise(x, condlist, funclist, *args, **kw) Evaluate a piecewise-defined function.
place(arr, mask, vals) Change elements of an array based on conditional and input values.
pmt(rate, nper, pv[, fv, when]) Compute the payment against loan principal plus interest.
poly(seq_of_zeros) Find the coefficients of a polynomial with the given sequence of roots.
polyadd(a1, a2) Find the sum of two polynomials.
polyder(p[, m]) Return the derivative of the specified order of a polynomial.
polydiv(u, v) Returns the quotient and remainder of polynomial division.
polyfit(x, y, deg[, rcond, full, w, cov]) Least squares polynomial fit.
polyint(p[, m, k]) Return an antiderivative (indefinite integral) of a polynomial.
polymul(a1, a2) Find the product of two polynomials.
polysub(a1, a2) Difference (subtraction) of two polynomials.
polyval(p, x) Evaluate a polynomial at specific values.
ppmt(rate, per, nper, pv[, fv, when]) Compute the payment against loan principal.
pv(rate, nper, pmt[, fv, when]) Compute the present value.
rate(nper, pmt, pv, fv[, when, guess, tol, ...]) Compute the rate of interest per period.
ravel_multi_index(multi_index, dims[, mode, ...]) Converts a tuple of index arrays into an array of flat indices, applying boundary modes to the multi-index.
real(val) Return the real part of the elements of the array.
real_if_close(a[, tol]) If complex input returns a real array if complex parts are close to zero.
recfromcsv(fname, **kwargs) Load ASCII data stored in a comma-separated file.
recfromtxt(fname, **kwargs) Load ASCII data from a file and return it in a record array.
roots(p) Return the roots of a polynomial with coefficients given in p.
rot90(m[, k]) Rotate an array by 90 degrees in the counter-clockwise direction.
row_stack(tup) Stack arrays in sequence vertically (row wise).
safe_eval(source) Protected string evaluation.
save(file, arr[, allow_pickle, fix_imports]) Save an array to a binary file in NumPy .npy format.
savetxt(fname, X[, fmt, delimiter, newline, ...]) Save an array to a text file.
savez(file, *args, **kwds) Save several arrays into a single file in uncompressed .npz format.
savez_compressed(file, *args, **kwds) Save several arrays into a single file in compressed .npz format.
select(condlist, choicelist[, default]) Return an array drawn from elements in choicelist, depending on conditions.
setdiff1d(ar1, ar2[, assume_unique]) Find the set difference of two arrays.
setxor1d(ar1, ar2[, assume_unique]) Find the set exclusive-or of two arrays.
sinc(x) Return the sinc function.
sort_complex(a) Sort a complex array using the real part first, then the imaginary part.
source(object[, output]) Print or write to a file the source code for a Numpy object.
split(ary, indices_or_sections[, axis]) Split an array into multiple sub-arrays.
tile(A, reps) Construct an array by repeating A the number of times given by reps.
trapz(y[, x, dx, axis]) Integrate along the given axis using the composite trapezoidal rule.
tri(N[, M, k, dtype]) An array with ones at and below the given diagonal and zeros elsewhere.
tril(m[, k]) Lower triangle of an array.
tril_indices(n[, k, m]) Return the indices for the lower-triangle of an (n, m) array.
tril_indices_from(arr[, k]) Return the indices for the lower-triangle of arr.
trim_zeros(filt[, trim]) Trim the leading and/or trailing zeros from a 1-D array or sequence.
triu(m[, k]) Upper triangle of an array.
triu_indices(n[, k, m]) Return the indices for the upper-triangle of an (n, m) array.
triu_indices_from(arr[, k]) Return the indices for the upper-triangle of arr.
typename(char) Return a description for the given data type code.
union1d(ar1, ar2) Find the union of two arrays.
unique(ar[, return_index, return_inverse, ...]) Find the unique elements of an array.
unpackbits(myarray[, axis]) Unpacks elements of a uint8 array into a binary-valued output array.
unravel_index(indices, dims[, order]) Converts a flat index or array of flat indices into a tuple of coordinate arrays.
unwrap(p[, discont, axis]) Unwrap by changing deltas between values to 2*pi complement.
vander(x[, N, increasing]) Generate a Vandermonde matrix.
vsplit(ary, indices_or_sections) Split an array into multiple sub-arrays vertically (row-wise).
who([vardict]) Print the Numpy arrays in the given dictionary.

3.12. Classes

DataSource([destpath]) A generic data source file (file, http, ftp, ...).
NumpyVersion(vstring) Parse and compare numpy version strings.
Tester alias of NoseTester
ndenumerate(arr) Multidimensional index iterator.
ndindex(*shape) An N-dimensional iterator object to index arrays.
poly1d(c_or_r[, r, variable]) A one-dimensional polynomial class.
vectorize(pyfunc[, otypes, doc, excluded, cache]) Generalized function class.

3.13. Exceptions

RankWarning Issued by polyfit when the Vandermonde matrix is rank deficient.