0
0
SciPydata~5 mins

2D interpolation (interp2d, griddata) in SciPy

Choose your learning style9 modes available
Introduction

2D interpolation helps you estimate values between known points on a flat surface. It fills gaps in data smoothly.

You have temperature readings at scattered locations and want to estimate temperature at other spots.
You want to create a smooth surface from a few measured heights on a map.
You need to fill missing pixels in an image based on nearby pixel values.
You want to predict values on a grid from irregularly spaced sensor data.
Syntax
SciPy
from scipy.interpolate import interp2d, griddata

# interp2d:
f = interp2d(x, y, z, kind='linear')
zi = f(xi, yi)

# griddata:
zi = griddata(points, values, (xi, yi), method='linear')

interp2d works with regular grids and returns a function to estimate values.

griddata works with scattered points and directly returns interpolated values.

Examples
Using interp2d to estimate value at (1.5, 1.5) on a regular grid.
SciPy
from scipy.interpolate import interp2d
import numpy as np

x = np.array([0, 1, 2])
y = np.array([0, 1, 2])
z = np.array([[0, 1, 4], [1, 2, 5], [4, 5, 6]])

f = interp2d(x, y, z, kind='linear')
zi = f(1.5, 1.5)
print(zi)
Using griddata to interpolate at point (0.5, 0.5) from scattered data.
SciPy
from scipy.interpolate import griddata
import numpy as np

points = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
values = np.array([0, 1, 1, 2])

xi = np.array([0.5])
yi = np.array([0.5])

zi = griddata(points, values, (xi, yi), method='linear')
print(zi)
Sample Program

This program shows how to use both interp2d and griddata to estimate values between known points.

SciPy
from scipy.interpolate import interp2d, griddata
import numpy as np

# Data on a regular grid
x = np.array([0, 1, 2])
y = np.array([0, 1, 2])
z = np.array([[0, 1, 4], [1, 2, 5], [4, 5, 6]])

# Create interp2d function
f = interp2d(x, y, z, kind='linear')

# Interpolate at new points
zi_interp2d = f(1.5, 1.5)

# Data as scattered points
points = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
values = np.array([0, 1, 1, 2])

# Points to interpolate
xi = np.array([0.5])
yi = np.array([0.5])

# Use griddata
zi_griddata = griddata(points, values, (xi, yi), method='linear')

print(f"interp2d result at (1.5,1.5): {zi_interp2d[0]}")
print(f"griddata result at (0.5,0.5): {zi_griddata[0]}")
OutputSuccess
Important Notes

interp2d is best for data on a regular grid but is deprecated in newer SciPy versions; consider RectBivariateSpline or RegularGridInterpolator for advanced use.

griddata works well with scattered data but can be slower for large datasets.

Choose interpolation method ('linear', 'nearest', 'cubic') based on smoothness and speed needs.

Summary

2D interpolation estimates values between known points on a surface.

interp2d works with regular grids and returns a function.

griddata works with scattered points and returns values directly.