Interpolation in Python: np.interp and CubicSpline
Estimate values between measured points with linear interpolation, or draw a smooth curve through them with a cubic spline.
- Linear interpolation with np.interp
- What happens outside the data range
- Smooth curves with scipy CubicSpline
- 13.75
- straight line
- 13.20
- smooth curve
Filling in between the points
The problem
Measurements come at fixed times, every 3 hours or every metre, but you need the value in between: the temperature at 4:30, or a table value that is not listed. Interpolation estimates it from the neighbouring points.
Think of it like this
Linear interpolation is like joining dots on graph paper with a ruler and reading a value off the line. A cubic spline is like bending a flexible strip through the dots, so the curve is smooth instead of having corners.
hours, temps📍 The dots on the papernp.interp(4.5, hours, temps)📏 Join the dots with a rulerCubicSpline(hours, temps)〰️ Bend a flexible strip through the dotsnp.interp(15, ...)🛑 Past the last dot the ruler stopsInterpolation estimates values between known data points. np.interp(x, xp, fp) uses straight lines between the points; scipy.interpolate.CubicSpline uses smooth cubic curves.
Key points
np.interp(4.5, hours, temps)gives 13.75, halfway between 12.5 and 15.0.- The x values
xpmust be in increasing order. - Outside the range,
np.interpreturns the first or last value instead of extrapolating. CubicSplinegives a smooth curve, so 4.5 h becomes 13.20 instead of 13.75.
When should you use it?
- Reading values between rows of a data table.
- Resampling measurements to regular times.
- Smooth curves for animation and plotting.
When not to use it
- Noisy data: a fitted curve (
np.polyfit,curve_fit) is better than passing through every point. - Predicting far outside the data: interpolation is not a forecast.
Example code
import numpy as np
from scipy.interpolate import CubicSpline
# Temperature measured every 3 hours
hours = np.array([0, 3, 6, 9, 12])
temps = np.array([14.0, 12.5, 15.0, 21.0, 24.5])
# Linear interpolation: straight lines between the points
print(f"np.interp at 4.5 h: {np.interp(4.5, hours, temps):.2f}")
print("np.interp at [1, 7, 10]:", np.interp([1, 7, 10], hours, temps).round(2).tolist())
# Outside the range np.interp repeats the end values
print("np.interp at 15:", float(np.interp(15, hours, temps)))
# Cubic spline: a smooth curve through the same points
spline = CubicSpline(hours, temps)
print(f"CubicSpline at 4.5 h: {float(spline(4.5)):.2f}")
print("CubicSpline at [1, 7, 10]:", spline([1, 7, 10]).round(2).tolist())
Result of running the code
np.interp at 4.5 h: 13.75
np.interp at [1, 7, 10]: [13.5, 17.0, 22.17]
np.interp at 15: 24.5
CubicSpline at 4.5 h: 13.20
CubicSpline at [1, 7, 10]: [13.11, 16.82, 22.81]
Code explanation
np.interp(4.5, hours, temps) looks between the readings at 3 h (12.5) and 6 h (15.0) and returns 13.75, the value halfway along the straight line. It also accepts a list of x values. At 15 h, outside the measured range, np.interp just repeats the last value 24.5 instead of extrapolating. CubicSpline(hours, temps) builds a smooth curve through the same points, so its values differ a little, for example 13.20 at 4.5 h.
Change the values and run the program in the CodeUtility online Python compiler without installing Python locally.
Practice exercises
Modify the runnable example with the exercises below to build understanding beyond copying the result.
- Change the function or the data and predict the result before running.
- Compare the numerical answer with the exact one from SymPy or a hand calculation.
- Plot the result with Matplotlib to see what the numbers mean.
Common mistakes
Unsorted x values
np.interp assumes xp increases; unsorted data gives wrong answers without an error.
np.interp(4.5, [6, 0, 3], [15.0, 14.0, 12.5])
np.interp(4.5, [0, 3, 6], [14.0, 12.5, 15.0])
Swapping the arguments
The order is the new x, then the known x, then the known y.
np.interp(hours, temps, 4.5)
np.interp(4.5, hours, temps)
Finished this lesson?
Mark it as learned to track your progress.
Tools for this lesson
- Graph Plotter Online: Plot Points and FunctionsPlot points, a pasted table or functions like sin(x) online and download the graph as a PNG. Free graph maker that also gives you the Python Matplotlib code.
- How to Plot a Graph in Python Online (Matplotlib Examples)Plot a graph in Python online with Matplotlib: lines, functions like sin(x), data from a CSV, bar and pie charts. Run each example in your browser.
- NumPy Online: Run NumPy Code in Your BrowserA NumPy playground with no install: arrays, statistics, linear algebra, random numbers and broadcasting. NumPy 2, pandas and SciPy ready to import.