TExcelTAD
Home › SciPy › SciPy Interpolation

SciPy Interpolation

Interpolation estimates values between points you already know. A weather station records the temperature every three hours, but you want a value for 10:30; a sensor drops a reading and you want to fill the gap; a lookup table has entries for 10, 20 and 30 and you need 24. The scipy.interpolate module offers several ways to draw a curve through known points and evaluate it anywhere in between.

Linear interpolation with NumPy

The simplest approach joins neighbouring points with straight lines. NumPy already does this with np.interp(), which is a good baseline:

python · try it yourself
import numpy as np

hours = np.array([0, 3, 6, 9, 12])
temps = np.array([12.0, 10.5, 13.0, 18.5, 22.0])

print("10:30 ->", np.interp(10.5, hours, temps))
print("many  ->", np.interp([1, 4.5, 7], hours, temps))
10:30 -> 20.25
many  -> [11.5        11.75       14.83333333]

1-D interpolation with SciPy

interp1d was the classic SciPy tool, but it is now considered legacy. The recommended replacements are classes that build an interpolating function once, which you then call like a normal function:

Tool Curve between points Smoothness
make_interp_spline(x, y, k=1) straight segments kinks at each point
CubicSpline(x, y) piecewise cubic polynomials smooth slope and curvature
PchipInterpolator(x, y) shape-preserving cubic smooth slope, never overshoots
Akima1DInterpolator(x, y) local cubic smooth, resists wiggles
python · try it yourself
import numpy as np
from scipy.interpolate import CubicSpline, PchipInterpolator, make_interp_spline

hours = np.array([0, 3, 6, 9, 12])
temps = np.array([12.0, 10.5, 13.0, 18.5, 22.0])

linear = make_interp_spline(hours, temps, k=1)
cubic = CubicSpline(hours, temps)
pchip = PchipInterpolator(hours, temps)

for name, f in [("linear", linear), ("cubic", cubic), ("pchip", pchip)]:
    print(f"{name:6} at 10.5 h: {float(f(10.5)):.3f}")
linear at 10.5 h: 20.250
cubic  at 10.5 h: 20.875
pchip  at 10.5 h: 20.472

All three agree exactly at the known hours; they differ only in how they bend between them.

Comparing the curves

A plot makes the differences obvious. Notice how the cubic spline dips below the lowest data point between hours 0 and 6, while PCHIP stays within the range of its neighbours:

python · try it yourself
import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import CubicSpline, PchipInterpolator

hours = np.array([0, 3, 6, 9, 12])
temps = np.array([12.0, 10.5, 13.0, 18.5, 22.0])
fine = np.linspace(0, 12, 200)

cubic = CubicSpline(hours, temps)
pchip = PchipInterpolator(hours, temps)

plt.plot(hours, temps, "ko", label="measured")
plt.plot(fine, np.interp(fine, hours, temps), "--", label="linear")
plt.plot(fine, cubic(fine), label="cubic spline")
plt.plot(fine, pchip(fine), label="PCHIP")
plt.xlabel("hour")
plt.ylabel("temperature (C)")
plt.legend()
plt.show()

print(f"lowest cubic value : {cubic(fine).min():.3f}")
print(f"lowest PCHIP value : {pchip(fine).min():.3f}")
lowest cubic value : 10.469
lowest PCHIP value : 10.500

Derivatives and integrals for free

Spline objects know their own calculus. A CubicSpline can return its derivative and integrate itself, which is useful for rates of change and totals:

python · try it yourself
import numpy as np
from scipy.interpolate import CubicSpline

# Distance (m) of a cyclist measured every 10 s
t = np.array([0, 10, 20, 30, 40])
d = np.array([0, 55, 125, 210, 300])
pos = CubicSpline(t, d)
speed = pos.derivative()

print(f"position at 25 s : {float(pos(25)):.2f} m")
print(f"speed at 25 s    : {float(speed(25)):.2f} m/s")
print(f"mean position    : {pos.integrate(0, 40) / 40:.2f} m (over 0-40 s)")
position at 25 s : 166.09 m
speed at 25 s    : 8.55 m/s
mean position    : 134.17 m (over 0-40 s)

Filling gaps in data

A common use is repairing missing values. Mark the gaps with NaN, build the interpolator from the valid points only, and evaluate it at the gaps:

python · try it yourself
import numpy as np
from scipy.interpolate import PchipInterpolator

readings = np.array([5.0, 5.4, np.nan, np.nan, 7.1, 7.0, np.nan, 6.2])
idx = np.arange(len(readings))
ok = ~np.isnan(readings)

fill = PchipInterpolator(idx[ok], readings[ok])
repaired = readings.copy()
repaired[~ok] = fill(idx[~ok])
print("before:", readings)
print("after :", np.round(repaired, 2))
before: [5.  5.4 nan nan 7.1 7.  nan 6.2]
after : [5.   5.4  6.04 6.76 7.1  7.   6.71 6.2 ]

Extrapolation warning

Interpolators are reliable between known points. Outside that range (extrapolation) they simply extend the last polynomial piece, which can produce wild results:

python · try it yourself
import numpy as np
from scipy.interpolate import CubicSpline

x = np.array([0, 1, 2, 3])
y = np.array([0, 1, 0, 1])
f = CubicSpline(x, y)
print("inside  f(1.5) =", round(float(f(1.5)), 3))
print("outside f(6)   =", round(float(f(6)), 3))

g = CubicSpline(x, y, extrapolate=False)
print("disabled g(6)  =", g(6))
inside  f(1.5) = 0.5
outside f(6)   = 56.0
disabled g(6)  = nan

Tip: With extrapolate=False, points outside the data return nan, which makes accidental extrapolation easy to spot. For smoothing noisy data instead of passing exactly through it, see the Splines and 2D Interpolation lesson.

Test yourself

What is interpolation?

  1. Predicting values far outside the data range
  2. Estimating values between known data points
  3. Removing noise from data
  4. Sorting data by x

Which interpolator is shape-preserving and never overshoots its neighbouring points?

  1. CubicSpline
  2. PchipInterpolator
  3. np.polyfit
  4. interp1d with kind='cubic'

What does CubicSpline(x, y, extrapolate=False) return for points outside the data range?

  1. 0
  2. The nearest value
  3. nan
  4. An exception