numpy
| Use Case | Command | Description |
|---|---|---|
| Create array from list | np.array([1,2,3]) | π¦ Create a NumPy array from a Python list |
| Array of zeros | np.zeros((3,4)) | βΏ Create an array filled with zeros |
| Array of ones | np.ones((2,2)) | 1οΈβ£ Create an array filled with ones |
| Evenly spaced values | np.arange(0,10,2) | π’ Generate evenly spaced values within a range |
| Linear spacing | np.linspace(0,1,5) | π Generate linearly spaced numbers |
| Random numbers | np.random.rand(3,3) | π² Generate random numbers (uniform) |
| Matrix multiplication | np.dot(a,b) or a@b | βοΈ Matrix multiplication (dot product) |
| Elementβwise operations | np.add(a,b) or a+b | β Add arrays elementβwise |
| Reshape array | np.reshape(a,(2,3)) | π Change the shape of an array |
| Statistical summary | np.mean(a, axis=0) | π Compute mean along an axis |
| Linear algebra | np.linalg.inv(a) | β‘ Compute matrix inverse |
| Fast Fourier Transform | np.fft.fft(a) | π Compute 1βD FFT |
NumPy β Provides an array object of arbitrary homogeneous items, fast mathematical operations over arrays, Linear Algebra, Fourier Transforms, Random Number Generation.
Documentation is available in two forms: docstrings provided with the code, and a loose standing reference guide, available from the NumPy homepage.
We recommend exploring the docstrings using IPython, an advanced Python shell with TAB-completion and introspection capabilities.
The docstring examples assume that numpy has been imported as np:
>>> import numpy as np
Code snippets are indicated by three greaterβthan signs:
>>> x = 42
>>> x = x + 1
Use the builtβin help function to view a function's docstring:
>>> help(np.sort)
... # doctest: +SKIP
For some objects, np.info(obj) may provide additional help. This is particularly true if you see the line "Help on ufunc object:" at the top of the help() page.
To search for documents containing a keyword, do:
>>> np.lookfor('keyword')
... # doctest: +SKIP
Generalβpurpose documents like a glossary and help on the basic concepts of numpy are available under the doc subβmodule:
>>> from numpy import doc
>>> help(doc)
... # doctest: +SKIP
doc β Topical documentation on broadcasting, indexing, etc.lib β Basic functions used by several subβpackages.random β Core Random Toolslinalg β Core Linear Algebra Toolsfft β Core FFT routinespolynomial β Polynomial toolstesting β NumPy testing toolsf2py β Fortran to Python Interface Generator.distutils β Enhancements to distutils with support for Fortran compilers support and more.test β Run numpy unittestsshow_config β Show numpy build configurationdual β Overwrite certain functions with highβperformance SciPy tools. Deprecated.matlib β Make everything matrices.__version__ β NumPy version stringStart IPython with the NumPy profile (ipython -p numpy), which will import numpy under the alias np. Then use the cpaste command to paste examples into the shell. To see which functions are available in numpy, type np.<TAB>, or use np.*cos*?<ENTER> to narrow down the list. To view the docstring for a function, use np.cos?<ENTER> (to view the docstring) and np.cos??<ENTER> (to view the source code).
Most of the functions in numpy return a copy of the array argument (e.g., np.sort). Inβplace versions of these functions are often available as array methods, i.e. x = np.array([1,2,3]); x.sort(). Exceptions to this rule are documented.
__config__
_distributor_init
_globals
_pytesttester
_version
compat (package)
conftest
core (package)
ctypeslib
distutils (package)
doc (package)
dual
f2py (package)
fft (package)
lib (package)
linalg (package)
ma (package)
matlib
matrixlib (package)
polynomial (package)
random (package)
setup
testing (package)
tests (package)
typing (package)
version
_mat
char
emath
rec
Axis supplied was invalid.
__init__(self, axis, ndim=None, msg_prefix=None) β Initialize self.__weakref__ β list of weak references to the object (if defined)The warning raised when casting a complex dtype to a real dtype.
__weakref__ β list of weak references to the object (if defined)DataSource(destpath='.')
A generic data source file (file, http, ftp, β¦).
__init__(self, destpath='.') β Create a DataSource with a local path.abspath(self, path) β Return absolute path of file in the DataSource directory.exists(self, path) β Test if path exists.open(self, path, mode='r', encoding=None, newline=None) β Open and return fileβlike object.Diagnosing machine parameters.
__init__(self, float_conv=float, int_conv=int, float_to_float=float, float_to_str=..., title='Python floating point number') β Initialize self.__str__(self) β Return str(self).Module deprecation warning.
Issued by polyfit when the Vandermonde matrix is rank deficient.
Raised when a computation is too hard (e.g., in shares_memory).
Visible deprecation warning.
Boolean type (True or False), stored as a byte.
__and__(self, value, /) β Return self&value.__bool__(self, /) β True if self else False__eq__(self, value, /) β Return self==value.__ge__(self, value, /) β Return self>=value.__gt__(self, value, /) β Return self>value.__hash__(self, /) β Return hash(self).Produce an object that mimics broadcasting.
__iter__(self, /) β Implement iter(self).__next__(self, /) β Implement next(self).reset(...) β Reset the broadcasted result's iterator(s).index β current index in broadcasted resultiters β tuple of iterators along componentsnd β Number of dimensions of broadcasted resultndim β Alias for ndnumiter β Number of iteratorsshape β Shape of broadcasted resultsize β Total sizeA business day calendar object.
__init__(self, /, *args, **kwargs) β Initialize self.holidays β A copy of the holiday array.weekmask β A copy of the sevenβelement boolean mask indicating valid days.Create a data type object.
__bool__(self, /) β True if self else False__eq__(self, value, /) β Return self==value.newbyteorder(...) β Return a new dtype with a different byte order.alignment, base, byteorder, char, descr, fields, flags, hasobject, isalignedstruct, isbuiltin, isnative, itemsize, kind, metadata, name, names, ndim, num, shape, str, subdtype, typeContext manager for floatingβpoint error handling.
__init__(self, *, call=..., **kwargs) β Initialize self.__enter__(self)__exit__(self, *exc_info)Machine limits for floating point types.
__repr__(self)__str__(self)bits, eps, epsneg, iexp, machar, machep, max, maxexp, min, minexp, negep, nexp, nmant, precision, resolution, tinyFlat iterator object to iterate over arrays.
__array__(...) β Get array from iteratorcopy(...) β Get a copy of the iterator as a 1βD array.base β A reference to the array that is iterated over.coords β An Nβdimensional tuple of current coordinates.index β Current flat index into the array.Class to convert formats, names, titles description to a dtype.
Base class for numpy scalar types.
__abs__, __add__, __array__, all, any, argmax, argmin, argsort, astype, byteswap, choose, clip, compress, conj, conjugate, copy, cumprod, cumsum, diagonal, dump, dumps, fill, flatten, getfield, item, itemset, max, mean, min, newbyteorder, nonzero, prod, ptp, put, ravel, repeat, reshape, resize, round, searchsorted, setfield, setflags, sort, squeeze, std, sum, swapaxes, take, tobytes, tofile, tolist, tostring, trace, transpose, var, viewT, __array_interface__, __array_priority__, __array_struct__, base, data, dtype, flags, flat, imag, itemsize, nbytes, ndim, real, shape, size, stridesMachine limits for integer types.
__init__(self, int_type)__repr__(self)__str__(self)max, minAn array object represents a multidimensional, homogeneous array of fixedβsize items.
__abs__, __add__, __array__, all, any, argmax, argmin, argpartition, argsort, astype, byteswap, choose, clip, compress, conj, copy, cumprod, cumsum, diagonal, dot, dump, dumps, fill, flatten, getfield, item, itemset, max, mean, min, newbyteorder, nonzero, partition, prod, ptp, put, ravel, repeat, reshape, resize, round, searchsorted, setfield, setflags, sort, squeeze, std, sum, swapaxes, take, tobytes, tofile, tolist, tostring, trace, transpose, var, viewT, __array_finalize__, __array_interface__, __array_priority__, __array_struct__, base, ctypes, data, dtype, flags, flat, imag, itemsize, nbytes, ndim, real, shape, size, stridesMultidimensional index iterator.
__init__(self, arr)__iter__(self)__next__(self) β Returns the index tuple and array value.An Nβdimensional iterator object to index arrays.
__init__(self, *shape)__iter__(self)__next__(self) β Returns a tuple of indices.ndincr(self) β Increment the multiβdimensional index by one (deprecated).Efficient multiβdimensional iterator object to iterate over arrays.
__init__(self, /, *args, **kwargs)close(...) β Resolve all writeback semantics.copy(...) β Get a copy of the iterator in its current state.debug_print(...) β Print the current state.enable_external_loop(...) β Modify the iterator to behave as if the flag was specified.iternext(...) β Perform a single internal iteration.remove_axis(...) β Removes axis i.remove_multi_index(...) β Remove the multi_index flag.reset(...) β Reset the iterator to its initial state.dtypes, finished, has_delayed_bufalloc, has_index, has_multi_index, index, iterationneedsapi, iterindex, iterrange, itersize, itviews, multi_index, ndim, nop, operands, shape, valueA oneβdimensional polynomial class.
__init__(self, c_or_r, r=False, variable=None)deriv(self, m=1) β Return a derivative.integ(self, m=1, k=0) β Return an antiderivative.o, order, r, roots, variable, c, coef, coefficients, coeffsFunctions that operate element by element on whole arrays.
__call__(self, /, *args, **kwargs)accumulate(...) β Accumulate the result of applying the operator.at(...) β Performs unbuffered in place operation.outer(...) β Apply the ufunc to all pairs.reduce(...) β Reduces array's dimension by one.reduceat(...) β Performs a (local) reduce with specified slices.identity, nargs, nin, nout, ntypes, signature, typesGeneralized function class.
__init__(self, pyfunc, otypes=None, doc=None, excluded=None, cache=False, signature=None)__call__(self, *args, **kwargs) β Return arrays with the results of pyfunc broadcast.chararray β Provides a convenient view on arrays of string and unicode values.matrix β A specialized 2βD array that retains its 2βD nature through operations.memmap β Create a memoryβmap to an array stored in a binary file on disk.recarray β Construct an ndarray that allows field access using attributes.float64, int32, complex128, etc.)Each numeric type has its own class with methods for arithmetic and type conversion. Full list: bool_, int8, int16, int32, int64, uint8, uint16, uint32, uint64, float16, float32, float64, float128, complex64, complex128, complex256, datetime64, timedelta64, bytes_, str_, void, object_, record, etc.
array(object, dtype=None, *, copy=True, order='K', subok=False, ndmin=0, like=None) β Create an array.zeros(shape, dtype=float, order='C', *, like=None) β Return a new array of given shape and type, filled with zeros.ones(shape, dtype=None, order='C', *, like=None) β Return a new array of given shape and type, filled with ones.full(shape, fill_value, dtype=None, order='C', *, like=None) β Return a new array of given shape and type, filled with fill_value.empty(shape, dtype=float, order='C', *, like=None) β Return a new array of given shape and type, without initializing entries.arange([start,] stop[, step,], dtype=None, *, like=None) β Return evenly spaced values within a given interval.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None, axis=0) β Return evenly spaced numbers over a specified interval.logspace(start, stop, num=50, endpoint=True, base=10.0, dtype=None, axis=0) β Return numbers spaced evenly on a log scale.reshape(a, newshape, order='C') β Gives a new shape to an array without changing its data.ravel(a, order='C') β Return a contiguous flattened array.concatenate((a1, a2, ...), axis=0, out=None, dtype=None, casting="same_kind") β Join a sequence of arrays along an existing axis.stack(arrays, axis=0, out=None) β Join a sequence of arrays along a new axis.split(ary, indices_or_sections, axis=0) β Split an array into multiple subβarrays as views.dot(a, b, out=None) β Dot product of two arrays.matmul(x1, x2, /, out=None, ...) β Matrix product of two arrays.sum(a, axis=None, dtype=None, out=None, keepdims=False, initial=0, where=True) β Sum of array elements over a given axis.mean(a, axis=None, dtype=None, out=None, keepdims=False, *, where=True) β Compute the arithmetic mean along the specified axis.std(a, axis=None, dtype=None, out=None, ddof=0, keepdims=False, *, where=True) β Compute the standard deviation along the specified axis.var(a, axis=None, dtype=None, out=None, ddof=0, keepdims=False, *, where=True) β Compute the variance along the specified axis.min(a, axis=None, out=None, keepdims=False, initial=..., where=...) β Return the minimum of an array or minimum along an axis.max(a, axis=None, out=None, keepdims=False, initial=..., where=...) β Return the maximum of an array or maximum along an axis.argmax(a, axis=None, out=None) β Returns the indices of the maximum values along an axis.argmin(a, axis=None, out=None) β Returns the indices of the minimum values along an axis.where(condition, [x, y]) β Return elements chosen from x or y depending on condition.nonzero(a) β Return the indices of the elements that are nonβzero.sort(a, axis=-1, kind=None, order=None) β Return a sorted copy of an array.argsort(a, axis=-1, kind=None, order=None) β Returns the indices that would sort an array.unique(ar, return_index=False, return_inverse=False, return_counts=False, axis=None) β Find the unique elements of an array.transpose(a, axes=None) β Reverse or permute the axes of an array.swapaxes(a, axis1, axis2) β Interchange two axes of an array.moveaxis(a, source, destination) β Move axes of an array to new positions.flip(m, axis=None) β Reverse the order of elements in an array along the given axis.fliplr(m) β Reverse the order of elements along axis 1 (left/right).flipud(m) β Reverse the order of elements along axis 0 (up/down).rot90(m, k=1, axes=(0,1)) β Rotate an array by 90 degrees in the plane specified by axes.pad(array, pad_width, mode='constant', **kwargs) β Pad an array.meshgrid(*xi, copy=True, sparse=False, indexing='xy') β Return coordinate matrices from coordinate vectors.mgrid, ogrid β nd_grid instances for creating dense/open multidimensional grids.ix_(*args) β Construct an open mesh from multiple sequences.einsum(subscripts, *operands, out=None, optimize=False) β Evaluates the Einstein summation convention.einsum_path(*operands, optimize='greedy') β Evaluates the lowest cost contraction order.histogram(a, bins=10, range=None, normed=None, weights=None, density=None) β Compute the histogram of a dataset.histogram2d(x, y, bins=10, range=None, normed=None, weights=None, density=None) β Compute the biβdimensional histogram.histogramdd(sample, bins=10, range=None, normed=None, weights=None, density=None) β Compute the multidimensional histogram.digitize(x, bins, right=False) β Return the indices of the bins to which each value in input array belongs.interp(x, xp, fp, left=None, right=None, period=None) β Oneβdimensional linear interpolation.gradient(f, *varargs, axis=None, edge_order=1) β Return the gradient of an Nβdimensional array.trapz(y, x=None, dx=1.0, axis=-1) β Integrate along the given axis using the composite trapezoidal rule.diff(a, n=1, axis=-1, prepend=..., append=...) β Calculate the nβth discrete difference.cumsum(a, axis=None, dtype=None, out=None) β Return the cumulative sum of the elements along a given axis.cumprod(a, axis=None, dtype=None, out=None) β Return the cumulative product of elements along a given axis.nansum, nanprod, nancumsum, nancumprod, nanmean, nanvar, nanstd, nanmin, nanmax, nanargmin, nanargmax, nanmedian, nanpercentile, nanquantile β NaNβignoring versions of corresponding functions.loadtxt(fname, dtype=float, comments='#', delimiter=None, converters=None, skiprows=0, usecols=None, unpack=False, ndmin=0, encoding='bytes', max_rows=None, *, like=None) β Load data from a text file.genfromtxt(fname, dtype=float, comments='#', delimiter=None, ...) β Load data from a text file with missing values handled.save(file, arr, allow_pickle=True, fix_imports=True) β Save an array to a binary file in .npy format.load(file, mmap_mode=None, allow_pickle=False, fix_imports=True, encoding='ASCII') β Load arrays or pickled objects from .npy, .npz or pickled files.savez, savez_compressed β Save several arrays into a single file in .npz format.polyfit, polyval, poly, roots, polyint, polyder, polyadd, polysub, polymul, polydiv β Old polynomial API.linalg.inv, linalg.det, linalg.eig, linalg.svd, etc. β Linear algebra operations (provided by numpy.linalg).fft.fft, fft.ifft, fft.fft2, etc. β Fast Fourier Transform routines (provided by numpy.fft).random.rand, random.randn, random.randint, random.seed, etc. β Random number generation (provided by numpy.random).ALLOW_THREADS = 1BUFSIZE = 8192CLIP = 0ERR_CALL = 3ERR_DEFAULT = 521ERR_IGNORE = 0ERR_LOG = 5ERR_PRINT = 4ERR_RAISE = 2ERR_WARN = 1FLOATING_POINT_SUPPORT = 1FPE_DIVIDEBYZERO = 1FPE_INVALID = 8FPE_OVERFLOW = 2FPE_UNDERFLOW = 4False_ = FalseInf = infInfinity = infMAXDIMS = 32MAY_SHARE_BOUNDS = 0MAY_SHARE_EXACT = -1NAN = nanNINF = -infNZERO = -0.0NaN = nanPINF = infPZERO = 0.0RAISE = 2SHIFT_DIVIDEBYZERO = 0SHIFT_INVALID = 9SHIFT_OVERFLOW = 3SHIFT_UNDERFLOW = 6ScalarType = (<class 'int'>, <class 'float'>, <class 'complex'>, ...)True_ = TrueUFUNC_BUFSIZE_DEFAULT = 8192UFUNC_PYVALS_NAME = 'UFUNC_PYVALS'WRAP = 1_UFUNC_API = <capsule object NULL>__NUMPY_SETUP__ = False__all__, __deprecated_attrs__, __expired_functions__, __git_version__absolute, add, arccos, arccosh, arcsin, arcsinh, arctan, arctan2, arctanh, bitwise_and, bitwise_not, bitwise_or, bitwise_xor, cbrt, ceil, conj, conjugate, copysign, cos, cosh, deg2rad, degrees, divide, divmod, equal, exp, exp2, expm1, fabs, float_power, floor, floor_divide, fmax, fmin, fmod, frexp, gcd, greater, greater_equal, heaviside, hypot, invert, isfinite, isinf, isnan, isnat, lcm, ldexp, left_shift, less, less_equal, log, log10, log1p, log2, logaddexp, logaddexp2, logical_and, logical_not, logical_or, logical_xor, matmul, maximum, minimum, mod, modf, multiply, negative, nextafter, not_equal, positive, power, rad2deg, radians, reciprocal, remainder, right_shift, rint, sign, signbit, sin, sinh, spacing, sqrt, square, subtract, tan, tanh, trunc, true_dividee, euler_gamma, inf, nan, pi, newaxis, c_, r_, s_, index_exp, mgrid, ogrid, cast, nbytes, sctypeDict, sctypes, typecodes, tracemalloc_domain, little_endian1.21.5
/usr/lib/python3/dist-packages/numpy/__init__.py
```Generated by phpman v4.9.27 · Markdown · JSON · MCP Author: Che Dong Under GNU General Public License
2026-07-19 19:01 @216.73.216.114
CrawledBy Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; ClaudeBot/1.0; +claudebot@anthropic.com)
Enhanced by LLM: deepseek-v4-flash / taotoken.net / www.chedong.com - original format