0
0
SciPydata~5 mins

interp1d for 1D interpolation in SciPy

Choose your learning style9 modes available
Introduction

We use interp1d to find values between known data points. It helps us guess missing or in-between values smoothly.

You have temperature readings every hour but want to know the temperature at half past the hour.
You know sales numbers for some days and want to estimate sales on days without data.
You have a few points of a curve and want to draw a smooth line connecting them.
You want to convert data sampled at one rate to another rate by estimating values in between.
Syntax
SciPy
from scipy.interpolate import interp1d

f = interp1d(x, y, kind='linear', fill_value='extrapolate')
y_new = f(x_new)

x and y are your known data points (arrays).

kind controls the interpolation type: 'linear' (default), 'nearest', 'cubic', etc.

Examples
Linear interpolation between points (1,1) and (2,4) gives 2.5 at 1.5.
SciPy
from scipy.interpolate import interp1d

x = [0, 1, 2]
y = [0, 1, 4]
f = interp1d(x, y)
print(f(1.5))
Cubic interpolation gives a smoother curve and a different value at 1.5.
SciPy
f_cubic = interp1d(x, y, kind='cubic')
print(f_cubic(1.5))
Nearest interpolation picks the closest known y value, here 1 at 1.5.
SciPy
f_nearest = interp1d(x, y, kind='nearest')
print(f_nearest(1.5))
Sample Program

This program creates a linear interpolation function from known points and finds values at new points between them.

SciPy
from scipy.interpolate import interp1d
import numpy as np

# Known data points
x = np.array([0, 1, 2, 3, 4])
y = np.array([0, 2, 4, 6, 8])

# Create interpolation function
f_linear = interp1d(x, y, kind='linear')

# New points to estimate
x_new = np.array([0.5, 1.5, 2.5, 3.5])

# Calculate interpolated values
y_new = f_linear(x_new)

print(y_new)
OutputSuccess
Important Notes

Input x must be increasing and 1-dimensional.

By default, fill_value='extrapolate' estimates values outside the range of x. Use bounds_error=True to raise an error instead.

Different kind values change smoothness and accuracy.

Summary

interp1d helps estimate values between known points.

Choose interpolation kind based on smoothness needed.

Use the created function to find new values easily.