When working with real-world data, it’s common to encounter situations where you need to estimate values between known data points. This is where interpolation comes in handy, and Python’s SciPy library offers powerful tools for this purpose.
Over my decade-plus journey as a Python developer, I’ve found SciPy’s interpolation functions to be invaluable for various projects, from analyzing stock market trends to processing climate data.
In this article, I’ll walk you through the most useful interpolation techniques in SciPy, with practical examples that you can apply to your projects right away. Let’s get in!
What is Interpolation and Why Use SciPy?
Interpolation is the process of finding new data points within the range of a discrete set of known data points. Think of it as filling in the gaps in your data.
SciPy’s interpolate module provides several methods to perform interpolation on 1D, 2D, and even multi-dimensional data. Some reasons I prefer SciPy for interpolation:
- Well-documented and maintained library
- A variety of interpolation techniques
- Seamless integration with NumPy arrays
- Optimized performance for numerical operations
Get Started with SciPy Interpolate
Before we dive into specific methods, let’s set up our environment:
import numpy as np
from scipy import interpolate
import matplotlib.pyplot as plt1D Interpolation with interp1d
The interp1d function is one of the most commonly used tools for one-dimensional interpolation.
Linear Interpolation
Let’s start with a simple example using temperature data from different hours of the day:
# Hours of the day
x = np.array([0, 4, 8, 12, 16, 20, 24])
# Temperature in Fahrenheit at those hours (New York summer day)
y = np.array([72, 68, 75, 90, 88, 79, 72])
# Create a linear interpolation function
f_linear = interpolate.interp1d(x, y)
# Create new x values for smooth plotting
x_new = np.linspace(0, 24, 100)
# Interpolate y values
y_new = f_linear(x_new)
# Plot the results
plt.figure(figsize=(10, 6))
plt.plot(x, y, 'o', label='Data points')
plt.plot(x_new, y_new, '-', label='Linear interpolation')
plt.title('Temperature Throughout the Day')
plt.xlabel('Hour')
plt.ylabel('Temperature (°F)')
plt.legend()
plt.grid(True)
plt.show()I executed the above example code and added the screenshot below.

This creates a linear interpolation of temperature values throughout the day. The function f_linear can now be used to estimate the temperature at any time point between 0 and 24 hours.
Read SciPy Stats
Different Kinds of Interpolation
SciPy offers various interpolation methods that you can specify using the kind parameter:
# Create different interpolation functions
f_linear = interpolate.interp1d(x, y, kind='linear')
f_cubic = interpolate.interp1d(x, y, kind='cubic')
f_quadratic = interpolate.interp1d(x, y, kind='quadratic')
# Plot comparison
plt.figure(figsize=(12, 7))
plt.plot(x, y, 'o', label='Data points')
plt.plot(x_new, f_linear(x_new), '-', label='Linear')
plt.plot(x_new, f_quadratic(x_new), '--', label='Quadratic')
plt.plot(x_new, f_cubic(x_new), '-.', label='Cubic')
plt.title('Comparison of Interpolation Methods')
plt.xlabel('Hour')
plt.ylabel('Temperature (°F)')
plt.legend()
plt.grid(True)
plt.show()I executed the above example code and added the screenshot below.

The different interpolation types produce varying results:
- Linear: Straight lines between points (fastest, but least smooth)
- Quadratic: Smoother curves using second-degree polynomials
- Cubic: Even smoother curves using third-degree polynomials (most common for natural-looking curves)
Check out SciPy Misc
Extrapolation with interp1d
By default, interp1d will raise an error if you try to interpolate outside the range of your input data. However, you can enable extrapolation:
# Enable extrapolation
f_extrapolate = interpolate.interp1d(x, y, kind='cubic',
fill_value='extrapolate')
# Create extended x range
x_extended = np.linspace(-4, 28, 200)
plt.figure(figsize=(10, 6))
plt.plot(x, y, 'o', label='Data points')
plt.plot(x_extended, f_extrapolate(x_extended), '-', label='Cubic with extrapolation')
plt.axvspan(-4, 0, alpha=0.2, color='r', label='Extrapolation zone')
plt.axvspan(24, 28, alpha=0.2, color='r')
plt.title('Temperature with Extrapolation')
plt.xlabel('Hour')
plt.ylabel('Temperature (°F)')
plt.legend()
plt.grid(True)
plt.show()I executed the above example code and added the screenshot below.

Use extrapolation with caution – it’s making predictions outside your known data range!
Spline Interpolation
Splines offer more control over the smoothness of the interpolation. The CubicSpline class is particularly useful:
# Create a cubic spline
cs = interpolate.CubicSpline(x, y)
plt.figure(figsize=(10, 6))
plt.plot(x, y, 'o', label='Data points')
plt.plot(x_new, cs(x_new), '-', label='CubicSpline')
plt.title('Temperature Using CubicSpline')
plt.xlabel('Hour')
plt.ylabel('Temperature (°F)')
plt.legend()
plt.grid(True)The advantage of CubicSpline over interp1d with kind='cubic' is that it gives you more control over boundary conditions.
2D Interpolation
Now let’s move to 2D interpolation, which is useful for surfaces like terrain data or heat maps.
Read SciPy Integrate
Use interp2d
Let’s create a 2D dataset representing temperature variations across latitude and longitude (a simplified weather map):
# Create a grid of points
x = np.linspace(30, 45, 10) # Latitudes (covering part of the US)
y = np.linspace(-120, -70, 12) # Longitudes
X, Y = np.meshgrid(x, y)
# Create some temperature data (in Fahrenheit)
Z = (X-37)**2 + (Y+95)**2
Z = 75 - Z/10 # Higher temperatures in the middle
# Create the interpolation function
f = interpolate.interp2d(x, y, Z.T, kind='cubic')
# Create a finer grid for interpolation
x_new = np.linspace(30, 45, 100)
y_new = np.linspace(-120, -70, 120)
# Interpolate on the new grid
Z_new = f(x_new, y_new)
# Plot the result
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(15, 6))
# Original data
c1 = ax1.contourf(X, Y, Z, 20, cmap='coolwarm')
ax1.set_title('Original Data')
ax1.set_xlabel('Latitude')
ax1.set_ylabel('Longitude')
plt.colorbar(c1, ax=ax1, label='Temperature (°F)')
# Interpolated data
X_new, Y_new = np.meshgrid(x_new, y_new)
c2 = ax2.contourf(X_new, Y_new, Z_new, 20, cmap='coolwarm')
ax2.set_title('Interpolated Data')
ax2.set_xlabel('Latitude')
ax2.set_ylabel('Longitude')
plt.colorbar(c2, ax=ax2, label='Temperature (°F)')Use RegularGridInterpolator
For more flexibility with multi-dimensional data, RegularGridInterpolator is my go-to choice:
from scipy.interpolate import RegularGridInterpolator
# Define the grid points
x = np.linspace(30, 45, 10)
y = np.linspace(-120, -70, 12)
z = np.linspace(0, 1000, 5) # Altitude in meters
# Create data values (temperature decreasing with altitude)
data = np.zeros((len(x), len(y), len(z)))
X, Y, Z = np.meshgrid(x, y, z, indexing='ij')
data = 75 - ((X-37)**2 + (Y+95)**2)/10 - Z/50
# Create the interpolator
interp = RegularGridInterpolator((x, y, z), data)
# Interpolate at specific points
points = np.array([
[35, -100, 200], # Point 1
[40, -90, 500], # Point 2
[37, -85, 800] # Point 3
])
# Get interpolated values
result = interp(points)
print("Interpolated temperatures at the specified points:")
for i, point in enumerate(points):
print(f"At coordinates {point}: {result[i]:.2f}°F")Check out SciPy Signal
Radial Basis Functions for Scattered Data
When your data points aren’t on a regular grid, radial basis functions (RBF) come to the rescue:
# Generate some scattered data points (weather stations)
np.random.seed(42)
n_samples = 100
x_scattered = np.random.uniform(30, 45, n_samples) # Latitudes
y_scattered = np.random.uniform(-120, -70, n_samples) # Longitudes
# Generate temperature values with some noise
z_scattered = 75 - ((x_scattered-37)**2 + (y_scattered+95)**2)/10
z_scattered += np.random.normal(0, 2, n_samples) # Add some noise
# Create the RBF interpolator
rbf = interpolate.Rbf(x_scattered, y_scattered, z_scattered, function='thin_plate')
# Create a grid for evaluation
grid_x, grid_y = np.meshgrid(np.linspace(30, 45, 100),
np.linspace(-120, -70, 100))
grid_z = rbf(grid_x, grid_y)
# Plot the results
plt.figure(figsize=(10, 8))
plt.scatter(x_scattered, y_scattered, c=z_scattered, cmap='coolwarm',
edgecolors='k', s=50, label='Weather stations')
plt.contourf(grid_x, grid_y, grid_z, 20, cmap='coolwarm', alpha=0.5)
plt.colorbar(label='Temperature (°F)')
plt.title('RBF Interpolation of Scattered Weather Station Data')
plt.xlabel('Latitude')
plt.ylabel('Longitude')
plt.legend()The Rbf class supports various radial basis functions like:
- ‘multiquadric’
- ‘inverse’
- ‘gaussian’
- ‘linear’
- ‘cubic’
- ‘quintic’
- ‘thin_plate’
Read SciPy Convolve
Advanced Example: Stock Price Interpolation
Let’s look at a more real-world example, interpolating missing stock prices:
# Sample stock data (AAPL closing prices, with some days missing)
dates = np.array([0, 3, 4, 7, 10, 12, 14]) # Days since start
prices = np.array([150.25, 152.30, 149.80, 155.20, 157.90, 156.75, 160.10])
# Create a cubic interpolation function
stock_interp = interpolate.interp1d(dates, prices, kind='cubic')
# Create a continuous timeline
all_days = np.arange(0, 15)
interpolated_prices = stock_interp(all_days)
# Plot the results
plt.figure(figsize=(12, 6))
plt.plot(dates, prices, 'ro', markersize=8, label='Actual closing prices')
plt.plot(all_days, interpolated_prices, 'b-', label='Interpolated prices')
plt.title('AAPL Stock Price Interpolation')
plt.xlabel('Days since start')
plt.ylabel('Price ($)')
plt.grid(True)
plt.legend()
plt.xticks(all_days)Polynomial Interpolation with polyfit
For simpler cases, NumPy’s polyfit function can be used for polynomial interpolation:
# Fit a 3rd degree polynomial
coeffs = np.polyfit(dates, prices, 3)
poly_func = np.poly1d(coeffs)
# Evaluate the polynomial at the desired points
poly_prices = poly_func(all_days)
# Plot the comparison
plt.figure(figsize=(12, 6))
plt.plot(dates, prices, 'ro', markersize=8, label='Actual closing prices')
plt.plot(all_days, interpolated_prices, 'b-', label='Cubic spline interpolation')
plt.plot(all_days, poly_prices, 'g--', label='Polynomial fit')
plt.title('Comparison of Interpolation Methods for Stock Prices')
plt.xlabel('Days since start')
plt.ylabel('Price ($)')
plt.grid(True)
plt.legend()While polyfit is technically a fitting function rather than an interpolator; it’s useful to compare its results with true interpolation methods.
Check out SciPy’s Ndimage Rotate
Real-World Applications
Interpolation isn’t just a mathematical concept – it has practical applications across various domains:
- Finance: Estimating continuous yield curves from discrete bond prices
- Geospatial: Creating topographic maps from elevation samples
- Meteorology: Generating weather maps from station measurements
- Engineering: Reconstructing signals from sampled data
- Image processing: Resizing or transforming images
Performance Considerations
When working with large datasets, performance becomes important:
- For 1D data with many points,
CubicSplineis typically faster thaninterp1d - For multidimensional data,
RegularGridInterpolatoris more efficient thaninterpnd - RBF interpolation can be computationally expensive for large datasets
- Consider downsampling your data if interpolation is too slow
SciPy’s interpolation functions are well-optimized, but for extremely large datasets, you might need specialized libraries or custom implementations.
I’ve found these tools indispensable in my data analysis projects, and I hope this guide helps you apply them effectively in your work. Remember that interpolation is both an art and a science – the choice of method can significantly impact your results, so experiment with different approaches to find what works best for your specific data.
If you’re new to Python data analysis, mastering interpolation is a valuable skill that will serve you well across many domains and applications.
You may like to read:

I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.