How to Perform Linear Interpolation in Python (With Example)

Linear interpolation in Python is a method of calculating the value of a function between two points on a line. It can be used to estimate values for a function based on known values at two points. To perform linear interpolation in Python, one can use the interp1d function from the scipy.interpolate module. This function takes two arrays, the x and y values of a known data set, and returns an interpolated function that can be used to find the y value for any given x value. An example of linear interpolation in Python is provided below.


Linear interpolation is the process of estimating an unknown value of a function between two known values.

Given two known values (x1, y1) and (x2, y2), we can estimate the y-value for some point x by using the following formula:

y = y1 + (x-x1)(y2-y1)/(x2-x1)

We can use the following basic syntax to perform linear interpolation in Python:

import scipy.interpolate

y_interp = scipy.interpolate.interp1d(x, y)

#find y-value associated with x-value of 13
print(y_interp(13))

The following example shows how to use this syntax in practice.

Example: Linear Interpolation in Python

Suppose we have the following two lists of values in Python:

x = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
y = [4, 7, 11, 16, 22, 29, 38, 49, 63, 80]

We can create a quick plot x vs. y:

import matplotlib.pyplot as plt

#create plot of x vs. y
plt.plot(x, y, '-ob')

Now suppose that we’d like to find the y-value associated with a new x-value of 13.

We can use the following code to do so:

import scipy.interpolate
y_interp = scipy.interpolate.interp1d(x, y)

#find y-value associated with x-value of 13 
print(y_interp(13))

33.5

The estimated y-value turns out to be 33.5.

If we add the point (13, 33.5) to our plot, it appears to match the function quite well:

import matplotlib.pyplot as plt

#create plot of x vs. y
plt.plot(x, y, '-ob')

#add estimated y-value to plot
plt.plot(13, 33.5, 'ro')

We can use this exact formula to perform linear interpolation for any new x-value.

The following tutorials explain how to fix other common errors in Python:

x