</>
Skip to content
SciPy lessons (9/25)

SciPy — Interpolation

Linear 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])

f = interp1d(x, y)
print(f"Value at 1.5 = {f(1.5):.2f}")
print(f"Value at 2.5 = {f(2.5):.2f}")

Cubic interpolation

f_cubic = interp1d(x, y, kind='cubic')
print(f"Cubic at 1.5 = {f_cubic(1.5):.2f}")

2D interpolation

from scipy.interpolate import griddata
import numpy as np

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

# Create grid
xi = np.linspace(0, 1, 10)
yi = np.linspace(0, 1, 10)
XI, YI = np.meshgrid(xi, yi)

# Interpolate
ZI = griddata((x, y), z, (XI, YI), method='cubic')

Spline interpolation

from scipy.interpolate import UnivariateSpline
import numpy as np

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

spline = UnivariateSpline(x, y)
print(f"Spline at 2.5 = {spline(2.5):.2f}")

RBF interpolation

from scipy.interpolate import RBFInterpolator
import numpy as np

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

rbf = RBFInterpolator(points, values)
print(f"Value at (0.5, 0.5) = {rbf([[0.5, 0.5]])[0]:.2f}")

Extrapolation

f = interp1d(x, y, fill_value='extrapolate')
print(f"Extrapolated at 6 = {f(6):.2f}")

Mini Practice

  1. Interpolate 1D data
  2. Use cubic splines
  3. Interpolate 2D data
  4. Compare interpolation methods

Up Next

Continue with Integration - Numerical integration.

Related Topics

Frequently Asked Questions about Interpolation

What is Interpolation in SciPy?

Interpolation is a fundamental concept in SciPy. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Interpolation?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Interpolation.

Why is Interpolation important in SciPy?

Interpolation is essential for SciPy development. Understanding this concept will help you write better code and solve real-world problems more effectively.