2D interpolation helps you estimate values between known points on a flat surface. It fills gaps in data smoothly.
2D interpolation (interp2d, griddata) in 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.
interp2d to estimate value at (1.5, 1.5) on a regular grid.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)
griddata to interpolate at point (0.5, 0.5) from scattered data.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)
This program shows how to use both interp2d and griddata to estimate values between known points.
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]}")
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.
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.