Scipy Interpolation

Data ScienceSciPyFree Lesson

Advertisement

Introduction

SciPy provides interpolation functions for 1D and multi-dimensional data, enabling smooth reconstruction of functions from discrete points.

1D Interpolation

from scipy.interpolate import interp1d
import numpy as np

x = np.array([0, 1, 2, 3, 4])
y = np.array([0, 2, 1, 3, 2])

# Different interpolation types
linear = interp1d(x, y)
cubic = interp1d(x, y, kind='cubic')
nearest = interp1d(x, y, kind='nearest')

# Interpolate at new points
x_new = np.linspace(0, 4, 100)
y_linear = linear(x_new)
y_cubic = cubic(x_new)

Spline Interpolation

from scipy.interpolate import UnivariateSpline, splrep, splev
import numpy as np

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

# Smooth spline
spline = UnivariateSpline(x, y, s=0.5)

# Spline representation
tck = splrep(x, y, k=3)  # Cubic spline
y_spline = splev(x_new, tck)

2D Interpolation

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

# Scattered data points
x = np.random.rand(100) * 4
y = np.random.rand(100) * 4
z = np.sin(x) * np.cos(y)

# Grid points for interpolation
xi = np.linspace(0, 4, 50)
yi = np.linspace(0, 4, 50)
xi_grid, yi_grid = np.meshgrid(xi, yi)

# Interpolate using different methods
zi_linear = griddata((x, y), z, (xi_grid, yi_grid), method='linear')
zi_cubic = griddata((x, y), z, (xi_grid, yi_grid), method='cubic')

Radial Basis Function

from scipy.interpolate import RBFInterpolator
import numpy as np

x = np.array([0, 1, 2, 3])
y = np.array([1, 3, 2, 1])

# RBF interpolation
rbf = RBFInterpolator(x.reshape(-1, 1), y, kernel='linear', smoothing=0)
x_new = np.linspace(0, 3, 100)
y_new = rbf(x_new.reshape(-1, 1))

Practice Problems

  1. Use interp1d for different interpolation methods
  2. Create smooth spline with specified smoothing
  3. Interpolate 2D scattered data on a grid
  4. Compare linear vs cubic interpolation accuracy
  5. Use RBF for irregularly spaced data

Advertisement

Need Expert Python Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement