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

API reference

SciPy API reference

SciPy scientific & numerical computing

Identifiers
114
With full guides
112
Types
3

Topics covered

  • Optimization
  • Integration
  • Statistics
  • Linear algebra
  • Signal processing
  • Sparse matrices
  • Interpolation
  • FFT

Class

NameWhat it does
interp1dCreates a callable interpolator for one-dimensional sampled data. It supports linear, nearest-neighbor, spline-based, and directional interpolation with configurable axis and out-of-range behavior.
normComputes vector and matrix norms, choosing among norm definitions with ord. It also supports norms over selected axes and batched matrices.
sparse.csr_matrixscipy.sparse.csr_matrix represents a matrix in compressed sparse row format. It supports construction from dense data, another sparse matrix, dimensions, coordinate triples, or the three arrays used by CSR storage.
sparse.csc_matrixscipy.sparse.csc_matrix creates compressed sparse column matrices. It accepts dense, sparse, coordinate-form, shape-only, and explicit compressed-storage inputs.
sparse.coo_matrixConstructs a sparse matrix in coordinate (COO), also called ijv or triplet, format. It accepts dense or sparse input, an empty shape, or value arrays paired with row and column indices.
sparse.lil_matrixscipy.sparse.lil_matrix is a row-based sparse matrix class suited to incremental construction. It accepts dense or sparse input, or a shape for creating an empty matrix.
spatial.KDTreeKDTree indexes k-dimensional points for fast nearest-neighbor and related spatial queries. It supports exact or approximate searches, radius-based searches, pair counting, and periodic domains.
spatial.ConvexHullConvexHull computes the convex hull enclosing points in N-dimensional space. It returns an object with hull indices, facets, geometric measures, and optional incremental-update methods.
spatial.Delaunayscipy.spatial.Delaunay computes a Delaunay tessellation in N dimensions from point coordinates. It supports furthest-site and incremental construction plus custom Qhull options.
spatial.VoronoiConstructs an N-dimensional Voronoi diagram from point coordinates. Options support furthest-site diagrams, incremental construction, and custom Qhull settings.

Function

NameWhat it does
minimizeMinimizes a scalar function of one or more variables using a selectable optimization method. It supports derivatives, bounds, constraints, tolerances, callbacks, and method-specific options.
curve_fitFits a callable model to measured data using nonlinear least squares. It returns optimized parameters and an approximate covariance matrix, with options for uncertainty weighting, bounds, optimization methods, and diagnostics.
quadNumerically computes a definite integral over finite or infinite bounds using QUADPACK. It returns the estimated integral and an absolute-error estimate, with options for tolerances, break points, weighting, diagnostics, and complex-valued functions.
fftComputes a one-dimensional discrete Fourier Transform using the Fast Fourier Transform algorithm. You can control output length, transformed axis, normalization, and optional parallel execution.
solveSolves the square-matrix system a @ x = b. Structure hints, batching, transpose solving, overwrite options, and finite-value checking are supported.
odeintIntegrates first-order ordinary differential-equation systems from an initial state over specified time points. It supports stiff and non-stiff systems and can pass extra arguments or solver/Jacobian options.
stats.normscipy.stats.norm represents a normal continuous random variable. Its loc and scale parameters control the mean and standard deviation, and its inherited distribution methods support common probability calculations.
stats.binomscipy.stats.binom is a binomial discrete random variable for modeling success counts across n trials with per-trial success probability p. It provides standard discrete-distribution methods and supports shifting with loc.
stats.poissonscipy.stats.poisson represents a Poisson discrete random variable. Provide a nonnegative mu and use its distribution methods to evaluate probabilities, compute statistics, or generate random counts.
stats.exponscipy.stats.expon is SciPy's exponential continuous distribution object. Its standard density is exp(-x) for x ≥ 0, with loc and scale available for shifting and scaling.
stats.uniformscipy.stats.uniform represents a continuous uniform distribution. Its standard support is [0, 1]; loc shifts the lower endpoint and scale sets the interval width.
stats.tscipy.stats.t represents a continuous Student’s t random variable. Set its positive degrees of freedom with df, and use inherited methods for densities, probabilities, quantiles, and sampling.
stats.chi2scipy.stats.chi2 is SciPy’s central chi-squared continuous distribution, parameterized by degrees of freedom (df). It provides the standard continuous-distribution methods for probabilities, quantiles, moments, and random sampling.
stats.gammascipy.stats.gamma is SciPy’s continuous gamma random-variable object. Provide a positive shape a, optionally shift with loc and scale with scale, then evaluate probabilities or generate samples.
stats.betascipy.stats.beta provides a beta continuous random variable parameterized by positive shape parameters a and b. Its distribution methods support evaluation, probability calculations, statistics, and sampling, with optional location and scale transformations.
stats.ttest_indTests whether two independent samples have identical expected means. It returns a t-statistic, p-value, and degrees of freedom, with optional Welch, one-sided, trimming, NaN-handling, and resampling-related controls.
stats.ttest_relTests whether two related or repeated samples have different means. It returns a TtestResult containing the t-statistic, p-value, and degrees of freedom.
stats.ttest_1sampTests whether the mean of one sample equals a specified population mean under a one-sample t-test. It supports axis-wise computation, configurable NaN handling, alternative hypotheses, and dimension-preserving output.
stats.pearsonrComputes the Pearson correlation coefficient between two datasets and tests the null hypothesis of non-correlation. It returns the coefficient and a p-value for the selected alternative hypothesis.
stats.spearmanrComputes Spearman rank-order correlation and its associated p-value. It measures monotonic association and supports one- or two-dimensional array-like inputs.
stats.kendalltauComputes Kendall’s tau, an ordinal association measure for two rankings. It supports tau-b and tau-c, handles ties and missing values, and returns the statistic with a hypothesis-test p-value.
stats.chi2_contingencyTests independence among variables in a contingency table by comparing observed frequencies with frequencies expected under independence. It returns the test statistic, p-value, degrees of freedom, and expected frequencies.
stats.shapiroPerforms the Shapiro-Wilk test for normality. It returns the test statistic and p-value, with options for axis-wise computation, NaN handling, and dimension preservation.
stats.kstestPerforms a one-sample or two-sample Kolmogorov–Smirnov test. It compares a sample with a continuous reference distribution or compares two independent continuous samples.
stats.mannwhitneyuPerforms the Mann–Whitney U rank test on two independent samples. It tests whether the distributions underlying the samples are the same and returns a statistic with a p-value.
stats.wilcoxonPerforms the Wilcoxon signed-rank test for paired measurements or supplied paired differences. It returns a signed-rank statistic and p-value for the selected alternative hypothesis and calculation method.
stats.kruskalComputes the Kruskal-Wallis H-test for two or more independent samples. It tests whether all groups have equal population medians and supports unequal sample sizes.
stats.normaltestTests whether a sample differs from a normal distribution using D’Agostino and Pearson’s omnibus test, which combines skewness and kurtosis. It returns the test statistic and a two-sided p-value.
stats.linregressCalculates a linear least-squares regression for two measurement sets. The result provides line coefficients, correlation, slope-test significance, and standard-error information.
stats.zscoreComputes standardized scores for sample values by comparing each with the sample mean and standard deviation. The axis, degrees-of-freedom correction, and NaN policy are configurable.
stats.semComputes the standard error of the mean for an array, either overall or along a chosen axis. It supports degrees-of-freedom adjustment, NaN policies, and dimension preservation.
stats.skewComputes the sample skewness of a dataset along a chosen axis. It supports bias correction, configurable NaN handling, and optional retention of reduced dimensions.
stats.kurtosisComputes dataset kurtosis along an axis, using Fisher’s excess-kurtosis convention or Pearson’s convention. It can optionally correct statistical bias and control NaN handling.
stats.bootstrapComputes a bootstrap confidence interval for a statistic by repeatedly resampling input data with replacement. The default BCa method can account for bias and skew in the bootstrap distribution.
stats.gaussian_kdescipy.stats.gaussian_kde constructs a non-parametric probability-density estimate from observations using Gaussian kernels. It supports univariate and multivariate data, automatic bandwidth selection, optional weights, and callable evaluation.
optimize.minimizescipy.optimize.minimize minimizes a scalar function of one or more variables. Choose a solver and optionally provide derivatives, bounds, constraints, tolerances, callbacks, and solver-specific options.
optimize.minimize_scalarFind a local minimum of a scalar function of one variable. Select a bracketing-based solver or bounded minimization and receive an OptimizeResult.
optimize.curve_fitFits a callable model to data by nonlinear least squares and returns the optimized parameters with an estimated covariance matrix. Bounds, measurement uncertainties, optimization methods, and solver options can be supplied.
optimize.rootFind a zero of a vector-valued function from an initial guess. The function supports multiple solver methods, optional Jacobians, callbacks, and solver-specific options.
optimize.fsolveFinds roots of scalar or vector nonlinear equations from an initial estimate. It can use a supplied Jacobian or estimate one numerically, with optional convergence diagnostics.
optimize.least_squaresSolves nonlinear least-squares problems, optionally with variable bounds and robust losses. It returns an OptimizeResult describing the fitted parameters, residuals, convergence, and local optimality.
optimize.linprogSolves a linear program by minimizing a linear objective subject to linear equality and inequality constraints. It supports variable bounds, selectable HiGHS algorithms, and integrality constraints with HiGHS methods.
optimize.brentqFinds a zero of a continuous function inside a sign-changing interval using Brent’s method. It combines bracketing, bisection, and inverse quadratic interpolation.
optimize.newtonFinds a zero of a real or complex scalar function with Newton-Raphson, secant, or Halley iteration. The selected method depends on whether first- and second-derivative callables are supplied.
optimize.differential_evolutionFinds a global minimum of a bounded multivariate function using stochastic, derivative-free differential evolution. It evolves a population of candidates and can optionally polish the best candidate.
optimize.dual_annealingFinds a global minimum of a bounded objective with dual annealing, optionally followed by local refinement. It returns an OptimizeResult describing the best point and termination state.
optimize.nnlsSolves a least-squares fit with the constraint that every element of the solution is nonnegative. It returns the fitted vector and the residual 2-norm.
integrate.quadNumerically compute a one-dimensional definite integral of a callable over finite or infinite bounds. quad returns the integral estimate and an absolute-error estimate, with options for tolerances, weighting, and diagnostics.
integrate.dblquadNumerically computes a definite double integral of func(y, x), with x integrated from a to b and y bounded by gfun(x) and hfun(x). It returns the integral estimate together with an error estimate.
integrate.simpsonEstimates an integral from sampled data with the composite Simpson rule. Provide x for sample coordinates or use dx for uniform spacing, and choose the integration dimension with axis.
integrate.trapezoidNumerically integrates sampled values with the composite trapezoidal rule. It can use explicit sample points or uniform spacing and integrates along a selected axis.
integrate.solve_ivpNumerically integrates an initial-value problem for a system of ordinary differential equations. It supports multiple solver methods, requested output times, dense interpolation, and event detection.
integrate.odeintIntegrates first-order ODE systems from an initial condition across requested time points, handling stiff and non-stiff problems. The derivative callback may use either (y, t, ...) or (t, y, ...) argument order.
integrate.cumulative_trapezoidcumulative_trapezoid computes running integrals of sampled data with the composite trapezoidal rule. It supports explicit coordinates or uniform spacing and can preserve the input length with initial=0.
interpolate.interp1dFunction
interpolate.griddataInterpolates unstructured data in multiple dimensions at specified query points. Choose linear, nearest, or cubic interpolation and optionally rescale coordinates or provide an exterior fill value.
interpolate.CubicSplineCubicSpline builds a piecewise cubic interpolant through data samples with twice-continuous derivatives. It returns a callable PPoly representation for evaluating the fitted curve.
interpolate.UnivariateSplineFits a one-dimensional smoothing spline to ordered x-y samples. The smoothing factor s balances fidelity against smoothness, while k selects the spline degree.
interpolate.RBFInterpolatorRBFInterpolator builds a radial-basis-function model for scattered data in one or more dimensions. Configure its kernel, smoothing, polynomial degree, and optional nearest-neighbor localization, then call the instance at new coordinates.
linalg.invComputes the inverse of a square matrix and returns it as an ndarray. It validates finite inputs by default and reports invalid shapes or singular matrices through exceptions.
linalg.detComputes the determinant of a square matrix or each square matrix in a stacked array. Singular matrices yield zero, and stacked inputs return one scalar per matrix slice.
linalg.solveSolves the square linear system a @ x = b. Known matrix structures can be supplied to choose a dedicated solver, and leading batch dimensions are supported.
linalg.eigSolves ordinary or generalized eigenvalue problems for square matrices. It returns eigenvalues and, optionally, left and normalized right eigenvectors.
linalg.eighSolves standard or generalized eigenvalue problems for complex Hermitian or real symmetric matrices. It returns ascending eigenvalues and, unless disabled, corresponding normalized eigenvectors.
linalg.svdComputes the singular value decomposition of a matrix, returning singular values and optionally the corresponding unitary factors. It supports full or reduced factors and selectable LAPACK drivers.
linalg.luComputes a pivoted LU decomposition of an array. It returns separate permutation, lower, and upper factors by default, or a pre-permuted lower factor when requested.
linalg.qrComputes the QR decomposition of a matrix, expressing it as an orthogonal/unitary factor Q and an upper-triangular factor R. Modes select full, reduced, R-only, or raw outputs, and pivoting supports rank-revealing factorization.
linalg.choleskyComputes a Cholesky factor for a Hermitian positive-definite matrix. It returns an upper-triangular factor by default or a lower-triangular factor when lower=True.
linalg.expmComputes the matrix exponential of a square array, including arrays with leading batch dimensions. It uses a variable-order Padé approximation and returns an array shaped like the input.
linalg.pinvComputes the Moore–Penrose pseudo-inverse of a matrix using an economy-mode singular-value decomposition. Singular values below atol + rtol * s are treated as insignificant, and the effective rank can optionally be returned.
linalg.lstsqComputes a least-squares solution to a @ x = b by minimizing the residual 2-norm. It also returns residuals, effective rank, and singular values.
signal.convolveConvolve two N-dimensional arrays using selectable output sizing and computation methods. The result is a requested subset of their discrete linear convolution.
signal.correlateComputes the discrete linear cross-correlation of two N-dimensional arrays. The mode selects the output region, and method selects direct, FFT, or automatic computation.
signal.find_peaksFinds local maxima in a one-dimensional signal and optionally filters them by height, spacing, prominence, width, threshold, or plateau size. It returns peak indices together with the properties calculated for the selected peaks.
signal.butterDesigns an Nth-order digital or analog Butterworth filter. It supports low-pass, high-pass, band-pass, and band-stop designs and returns coefficients as polynomials, zero-pole-gain values, or second-order sections.
signal.filtfiltApplies a digital filter forward and backward to produce zero-phase filtering. It supports configurable edge handling through padding or Gustafsson’s method.
signal.welchEstimate a signal’s power spectral density with Welch’s method by averaging modified periodograms from overlapping segments. The function can also return a squared-magnitude spectrum.
signal.spectrogramComputes a spectrogram by applying consecutive Fourier transforms to windowed segments of a time series. It returns frequency bins, segment times, and the resulting spectral representation.
signal.savgol_filterApplies a one-dimensional Savitzky–Golay filter to an array, optionally computing a derivative. For multidimensional input, filtering occurs along the selected axis.
signal.resampleResamples an array to a requested number of samples using Fourier-domain processing. It supports arbitrary integer upsampling or downsampling, optional spectral windowing, and optional output sample positions.
signal.hilbertComputes the analytic signal of a real-valued input using an FFT-based Hilbert transform. The result is complex, with the original signal in the real part and its Hilbert transform in the imaginary part.
fft.fftComputes a one-dimensional discrete Fourier transform using the fast Fourier transform algorithm. It transforms the selected axis, optionally changing its length and normalization.
fft.ifftComputes the one-dimensional inverse discrete Fourier transform. It can select the transform axis, adjust its length by cropping or zero-padding, and choose a normalization convention.
fft.fft2Computes a two-dimensional discrete Fourier transform with SciPy's FFT implementation. It can operate on selected axes of an M-D array and supports configurable sizes and normalization.
fft.rfftComputes the one-dimensional discrete Fourier transform of real-valued input using an efficient FFT algorithm. It returns the nonredundant complex spectrum along the selected axis.
fft.fftfreqReturns the discrete Fourier transform’s sample-frequency bins for a window of length n. Frequencies are scaled by the sample spacing, start at zero, and include negative-frequency bins.
fft.dctComputes a discrete cosine transform of a sequence or array along a selected axis. It supports four DCT types, configurable length and normalization, and optional parallel execution.
ndimage.gaussian_filterApplies a multidimensional Gaussian filter to an array. It can smooth data, compute Gaussian derivatives, and control boundary handling and kernel size.
ndimage.median_filterCalculates a multidimensional median filter over an input array. The neighborhood can be rectangular via size or selectively defined with a boolean footprint, with configurable boundaries and output handling.
ndimage.labelLabels connected nonzero features in an array and counts them. Connectivity is controlled by an optional structuring element.
ndimage.rotateRotates an array in the plane defined by two axes using spline interpolation. The angle is given in degrees, with controls for output shape, interpolation, boundary behavior, and destination storage.
special.gammaComputes the gamma function for real or complex scalar and array-like inputs. It generalizes factorials and optionally stores results in a supplied output array.
special.erfComputes the error function for real or complex arguments. It is a universal function that returns values elementwise for array inputs and can optionally use a supplied output array.
special.factorialComputes the factorial of a number or array of numbers. It can use exact integer arithmetic or a faster floating-point approximation.
special.combComputes the number of ways to choose k elements from N items, optionally allowing repetition. It can return a floating-point result or an exact integer for integer inputs.
special.expitscipy.special.expit computes the logistic sigmoid element-wise: 1/(1+exp(-x)). It returns a scalar or same-shaped ndarray and supports an optional output array.
special.softmaxComputes softmax by exponentiating input values and dividing by the sum of exponentials along a selected axis. The output has the same shape as the input and sums to 1 along that axis.
special.logsumexpComputes the logarithm of a sum of exponentials in a numerically stable way. It supports axis reduction, broadcastable weights, singleton-dimension preservation, and optional sign output.

Module

NameWhat it does
scipy.integrateModule
scipy.optimizescipy.optimize provides numerical routines for minimization, global optimization, least-squares fitting, curve fitting, and root solving. It includes methods for scalar, multivariate, constrained, unconstrained, and equation-system problems.
scipy.statsscipy.stats is SciPy’s broad statistics module, combining probability distributions with summary statistics, correlations, tests, density estimation, masked-array tools, and quasi-Monte Carlo functionality. It supports both continuous and discrete univariate distributions.
scipy.linalgscipy.linalg is SciPy's module for linear algebra. Its documented routines cover matrix inverses, linear systems, banded systems, and ordinary or generalized eigenvalue problems.
scipy.signalscipy.signal is SciPy’s signal-processing module. It provides convolution, correlation, filtering, spectral-analysis, waveform-generation, and related signal-processing functions.
scipy.sparsescipy.sparse provides sparse-array formats that store data efficiently when most positions are empty. Its formats support different construction, arithmetic, slicing, linear-algebra, and graph-computation workloads.

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

Start learning