Skip to content
masterclassBuddyTech Buzz5 fresh blogs · 5:00 AM IST

API reference

NumPy API reference

NumPy numerical computing with ndarrays

Identifiers
113
With full guides
92
Types
5

Topics covered

  • ndarray basics
  • Array creation
  • Indexing & slicing
  • Broadcasting
  • Vectorised math
  • Linear algebra
  • Random sampling
  • Reshaping & stacking

Class

NameWhat it does
ndarraynumpy.ndarray is a multidimensional, homogeneous array whose elements have a fixed-size representation described by a dtype. Its constructor exposes shape, storage, strides, offset, and memory-order controls, but ordinary arrays should usually be created with array, zeros, or empty.
dtypenumpy.dtype creates a data type object that describes how homogeneous ndarray elements are interpreted. It captures properties such as value kind, storage size, byte order, and structured layout.

Function

NameWhat it does
np.arrayCreates an ndarray from an array-like object, such as a nested sequence or compatible array object. Optional arguments control dtype, copying, memory order, subclass handling, and dimensions.
np.zerosCreates a new NumPy array with a specified shape and type, initializing every element to zero. The shape, dtype, memory order, implementation reference, and device can be selected.
np.onesCreates a new NumPy array of a specified shape, filled with ones. By default it uses float64 values; dtype and memory order can be selected.
np.arangeFunction
np.linspaceGenerates a chosen number of evenly spaced NumPy samples between two boundaries. The upper boundary is included by default and can be excluded.
np.reshapeFunction
np.concatenateJoins a sequence of arrays along an existing axis. Inputs must match in every other dimension; axis=None flattens them before joining.
np.dotComputes dot products for scalar, vector, matrix, and higher-dimensional array combinations. Its exact operation depends on operand dimensionality, and an optional output array can receive the result.
np.matmulFunction
np.meanComputes the arithmetic mean of array elements, either across the flattened input or along selected axes. Optional controls set the calculation dtype, output destination, retained dimensions, and included elements.
np.sumSums elements of an array over the whole input or selected axes. It supports dtype control, dimension preservation, conditional selection, an initial value, and an optional output array.
np.stdComputes the standard deviation of array elements, measuring distribution spread. It reduces the flattened input by default or operates along specified axes.
np.whereFunction
np.transposeReorders the axes of an array. Without axes it reverses their order; with a permutation, it applies the specified output-axis order.
np.argmaxReturns the integer indices of maximum values in an array, either globally or along a chosen axis. Ties select the first occurrence, and keepdims can preserve reduced dimensions.
np.uniqueFinds the distinct elements of an array and returns them sorted by default. Optional outputs provide source positions, reconstruction indices, and occurrence counts.
np.saveSaves array-like data to NumPy’s binary .npy format. It accepts paths or file objects and optionally permits pickle serialization for object arrays.
np.vstackStack arrays vertically by concatenating along axis 0. One-dimensional inputs are first treated as single rows, producing an output with at least two dimensions.
np.emptyFunction
np.fullReturns a new NumPy array with a specified shape, filled with a chosen value. Optional dtype, memory order, device, and like arguments control how the array is created.
np.logspaceGenerates values evenly spaced in logarithmic space. It samples exponents from start to stop and raises base to those exponents.
np.eyeCreates a 2-D array containing ones on a chosen diagonal and zeros elsewhere. The result can be square or rectangular, with configurable diagonal offset, dtype, memory order, and array-creation dispatch.
np.identityCreates an n-by-n identity array: ones on the main diagonal and zeros elsewhere. The optional dtype selects the output type, while like can enable compatible non-NumPy array creation.
np.zeros_likeCreates a new array filled with zeros, using an input array-like object's shape and data type by default. Optional arguments can override the dtype, layout, subclass handling, shape, or device.
np.ones_likeCreates an array filled with ones, using a supplied array-like object to determine the default shape and data type. Optional arguments can change the dtype, memory order, subclass handling, shape, or device.
np.full_likeFunction
np.meshgridFunction
np.diagExtract a selected diagonal from a 2-D array or build a 2-D diagonal array from 1-D values. Use k to choose an offset from the main diagonal.
np.random.randFunction
np.random.randnDraw samples from the standard normal distribution. With dimensions, np.random.randn returns an array of that shape; without dimensions, it returns one float.
np.random.randintGenerates random integers from a discrete uniform distribution over a half-open interval. Supply one bound for values in [0, low), or two bounds for values in [low, high).
np.random.choiceGenerates a random sample from a one-dimensional array-like population or from the range np.arange(a). You can control output shape, replacement, and per-item probabilities.
np.random.normalDraws random samples from a normal (Gaussian) distribution. Set loc for the mean, scale for the standard deviation, and size for the output shape.
np.random.seedReseeds NumPy’s shared legacy RandomState used by module-level random functions. Prefer a dedicated Generator for new code.
np.random.default_rngCreates a NumPy Generator using the default PCG64 BitGenerator. An optional seed initializes its state for reproducible sequences; without one, operating-system entropy is used.
np.ravelFlatten an array-like input into a contiguous one-dimensional array. The reading order is configurable, and copying occurs only when needed.
np.swapaxesInterchanges two axes of an array. It is useful for changing dimension order while leaving the data values unchanged.
np.stackStacks a sequence of equally shaped arrays along a new axis. Use axis to choose where that dimension appears, and optionally provide an output buffer, dtype, and casting policy.
np.hstackFunction
np.dstackFunction
np.splitSplits an ndarray into multiple sub-arrays along a chosen axis. It supports equal-count splitting or explicit sorted boundaries, and returns views of the original array.
np.hsplitSplits an array into multiple horizontal sub-arrays. It uses axis 1 for multidimensional arrays and axis 0 for one-dimensional arrays.
np.vsplitSplits an array into multiple sub-arrays row-wise. It always operates along the first axis and accepts either an equal-section count or explicit split positions.
np.tileConstructs an array by repeating an input along its axes according to reps. NumPy aligns the input rank and repetition specification by adding leading dimensions or leading repetition counts of one.
np.repeatRepeats array elements a specified number of times. Use axis to repeat along a dimension, or omit it to flatten the input first.
np.expand_dimsAdds one or more singleton dimensions to an array at specified axis positions. The result is an ndarray view, and a tuple of axes can insert multiple dimensions.
np.squeezeRemoves axes of length one from an array. Use axis to restrict removal to specific singleton dimensions.
np.moveaxisMoves selected axes of an array to new positions while preserving the relative order of axes that are not moved. The result is a view of the input array.
np.flipFunction
np.rollnp.roll cyclically shifts array elements along one or more axes, wrapping values that cross an edge back to the opposite side. Without an axis, it rolls the flattened array and restores the original shape.
np.appendAppends values to an array and returns a new ndarray. Without axis, both inputs are flattened; with axis, values must have compatible dimensions.
np.insertInserts values before selected indices in an array, optionally along a specified axis. It returns a new array rather than modifying the input.
np.deleteReturns a new array with selected elements or sub-arrays removed. Use axis to control the dimension, or leave it as None to delete from the flattened input.
np.sortReturns a sorted copy of an array. It can sort along an axis, flatten before sorting, choose an algorithm, preserve equal-value order, and optionally sort descending.
np.argsortFunction
np.nonzeroReturns the indices of non-zero elements as one index array per input dimension. It also works with boolean conditions to locate entries where a predicate is true.
np.searchsortedFind insertion positions in a sorted array so added values preserve its order. Choose left or right placement for duplicates, and optionally provide sort indices for an array that is not physically sorted.
np.clipClips array elements to an interval by replacing values below the lower bound or above the upper bound with the corresponding boundary. Bounds may be scalar or array-like and can be broadcast across the input.
np.addAdds two inputs element by element. Compatible shapes are broadcast, and the result is an array or scalar depending on the inputs.
np.subtractSubtracts two operands element by element, following NumPy broadcasting rules. It returns an ndarray for array inputs and a scalar when both inputs are scalars.
np.multiplyMultiplies two inputs element by element, applying NumPy broadcasting when needed. It returns the product, with optional controls for output storage, selection, casting, dtype, layout, and subclasses.
np.divideFunction
np.powerFunction
np.sqrtComputes the non-negative square root element-wise for array-like input. Real negative values produce nan, while complex input produces complex square roots.
np.expComputes the natural exponential of each element in scalar or array-like input. It supports broadcasting, optional output storage, and selective computation with where.
np.logComputes the natural logarithm, base e, element-wise. It accepts scalars and array-like inputs and exposes standard NumPy ufunc options for masking, output storage, casting, and dtype control.
np.log2Computes the base-2 logarithm of each input value. It is a NumPy ufunc that supports scalar and array inputs, with standard controls for output storage, masking, casting, dtype, and subclasses.
np.log10Computes the base-10 logarithm element-wise for array-like input. Negative real values produce NaN, and scalar input produces a scalar result.
np.sinComputes the trigonometric sine element-wise for angles expressed in radians. It accepts scalar or array-like input and supports standard ufunc options such as output placement and masking.
np.cosFunction
np.tanComputes tangent element-wise for array-like input, using radians. It returns corresponding tangent values and supports NumPy ufunc options such as output reuse and conditional computation.
np.signReturns the sign of each input element. Real values become -1, 0, or 1; complex values are divided by their magnitude, and NaN inputs remain NaN.
np.floorReturns the mathematical floor of input values element-wise: the greatest integer less than or equal to each value. It returns an ndarray for array input and a scalar for scalar input.
np.ceilReturns the ceiling of an input element-wise: each value becomes the smallest integer greater than or equal to it. Scalar inputs produce scalars; array inputs produce floating-point arrays.
np.prodReturns the product of array elements over a selected axis or axes. It can reduce all elements, preserve reduced dimensions, control accumulation dtype, mask inputs, and write into a supplied output array.
np.cumsumComputes cumulative sums along an axis of an array. By default, multidimensional input is flattened before accumulation.
np.cumprodReturns running products of array elements along a selected axis. Without axis, it flattens the input; dtype controls multiplication and output types, and out can reuse an existing array.
np.medianComputes the median of array elements along selected axes. It averages the two central values for even-sized data and can preserve reduced dimensions for broadcasting.
np.varComputes variance, the spread measured by the average squared deviation from the mean. It reduces the flattened input by default or operates along specified axes.
np.argminReturns the indices of minimum values in an array, either globally or along a chosen axis. It can preserve reduced dimensions and optionally write into a supplied output array.
np.crossComputes the cross product of two vectors or arrays of vectors in R^3. By default, it treats the last axis of each input as the vector-component axis and returns the resulting vector cross product(s).
np.einsumEvaluates Einstein summation expressions over array-like operands. Repeated labels contract dimensions, while explicit output labels control the result’s dimensions and order.
np.linalg.invComputes the inverse of a square matrix, returning a result that multiplies with the input to form the identity. It raises LinAlgError when the input is nonsquare or inversion fails.
np.linalg.detComputes determinants for square arrays, including stacks of matrices. Each trailing M×M matrix yields one determinant.
np.linalg.eigComputes the eigenvalues and right eigenvectors of a square array. It returns paired eigenvalues and normalized eigenvectors, including support for batched square matrices.
np.linalg.svdComputes the singular value decomposition of an array, returning singular values and optionally the corresponding left and right singular-vector factors. It supports both individual matrices and stacks of matrices.
np.linalg.solveSolves a square, full-rank linear system a x = b and returns x. It also supports multiple right-hand sides and broadcastable leading dimensions.
np.linalg.normComputes vector or matrix norms for an array-like input. The norm type and dimensions being reduced are controlled by ord and axis.
np.linalg.qrComputes the QR factorization of an array, expressing it as an orthonormal factor Q and an upper-triangular factor R. The mode selects reduced, complete, R-only, or raw Householder output.
np.linalg.choleskyComputes the Cholesky factorization of a square Hermitian positive-definite matrix, returning a lower-triangular factor by default or an upper-triangular factor when requested.
np.linalg.matrix_rankReturns the rank of an array using an SVD-based method. It supports vectors, matrices, and stacks of matrices, with optional tolerance and Hermitian optimization.
np.linalg.pinvComputes the Moore–Penrose pseudo-inverse of a matrix or stack of matrices using singular-value decomposition. Small singular values are discarded according to a cutoff.

Type Alias

NameWhat it does
np.int32np.int32 is NumPy's fixed-width 32-bit integer type. Use it for integer scalars or as an array dtype when a 32-bit representation is required.
np.int64Type Alias
np.float32np.float32 is an alias for NumPy’s single scalar type. It represents a 32-bit single-precision floating-point value compatible with C float.
np.float64Type Alias
np.bool_np.bool_ is NumPy’s Boolean dtype and scalar type, representing True or False with byte-sized storage. Use it to declare Boolean arrays or convert array data explicitly.
np.complex128np.complex128 is NumPy's alias for cdouble, a complex scalar made from two 64-bit floating-point components. It is compatible with Python's built-in complex type and can be used as an array dtype.
np.uint8np.uint8 is NumPy’s unsigned 8-bit integer type. It represents nonnegative integer data and is commonly used as an array dtype for byte-sized values.
np.datetime64np.datetime64 is NumPy’s scalar for ISO 8601 dates and date-times. It can also be built from an integer offset from the Unix epoch with an explicit time unit.
np.dtypenp.dtype creates a NumPy data-type object from a type description. It describes array element representation and can also define structured fields, alignment, copying, and metadata.

Module

NameWhat it does
np.randomnumpy.random provides pseudo-random number generators and distribution sampling for NumPy. The modern workflow is to create a Generator with default_rng, optionally seed it for reproducible results, and call its sampling methods.
np.linalgnumpy.linalg is NumPy's linear algebra namespace for standard matrix and vector computations. Its routines include solving systems, decompositions, eigenvalue calculations, norms, inverses, and matrix products.

Pipe

NameWhat it does
ndarray.shapendarray.shape gives an array's dimensions as a tuple. Direct assignment can request an in-place reshape, but ndarray.reshape is the preferred approach.
ndarray.dtypePipe
ndarray.ndimPipe
ndarray.sizendarray.size gives the total number of elements in an array. It equals the product of the array’s dimensions and returns a standard arbitrary-precision Python integer.
ndarray.TPipe
ndarray.flatPipe
ndarray.realReturns the real part of an ndarray. It usually provides a view into the source array, while object arrays use each element’s .real value.
ndarray.imagndarray.imag gives the imaginary component of an array. It returns a view for complex arrays, zeros with the same dtype for non-complex arrays, and elementwise values for object arrays.

Search across every package and filter by type in your dashboard.

Start learning