Interpolation and splines

SciPy · Practical · 10 min

Resampling signals, filling grids and building smooth curves from measurements all need interpolation.

Interpolation builds a function that passes through known points so you can evaluate it in between.

For 1-D data the main options are:

  • np.interp(x_new, x, y): piecewise linear, fast, fine for many purposes.
  • interpolate.CubicSpline(x, y): smooth (continuous second derivative), can overshoot between points; bc_type controls the ends, and the object has .derivative() and .integrate(a, b).
  • interpolate.PchipInterpolator(x, y) and Akima1DInterpolator: smooth but shape-preserving, no overshoot. Use them for monotonic data such as cumulative curves or concentrations that cannot go negative.
  • interpolate.make_interp_spline(x, y, k=3): a B-spline of chosen degree.

These objects are callable: cs(x_new). The older interp1d class is legacy and should not be used in new code.

Interpolation is not smoothing. With noisy data an interpolant reproduces the noise; use a smoothing spline such as make_smoothing_spline(x, y) instead.

Beyond 1-D: RegularGridInterpolator for data on a grid, griddata or RBFInterpolator for scattered points.

Extrapolation outside the data range is risky: splines extrapolate their last polynomial piece, which can go wild. Prefer extrapolate=False (returns NaN) unless you have a reason.

Example

import numpy as np
from scipy import interpolate

x = np.array([0, 1, 2, 3, 4], dtype=float)
y = np.array([0, 0, 1, 1, 1], dtype=float)     # a step-like, monotonic curve

cs = interpolate.CubicSpline(x, y)
pc = interpolate.PchipInterpolator(x, y)
xs = np.array([0.5, 2.5])
print(cs(xs).round(3))          # [-0.297  1.109] (overshoots below 0 and above 1)
print(pc(xs).round(3))          # [0.  1.] (stays within the data range)
print(np.interp(xs, x, y))      # [0. 1.]

print(round(float(cs.integrate(0, 4)), 3))  # 2.333 (area under the spline)
print(pc(5.0), interpolate.PchipInterpolator(x, y, extrapolate=False)(5.0))  # 1.0 nan

Remember

  • Use CubicSpline for smooth curves, PchipInterpolator to avoid overshoot
  • Interpolants are callable and support derivatives and integrals
  • Use smoothing splines for noisy data; avoid extrapolating

Watch out for

  • Using the legacy interp1d in new code.

Check yourself

  1. You interpolate a cumulative distribution that must never decrease. Which interpolator is safest?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: docs.scipy.org/doc/scipy/tutorial/interpolate.html

Builds on

Unlocks

Nothing builds on this yet.