python-scipyHow do I use Python and SciPy for interpolation?
Python and SciPy can be used to interpolate data by fitting a function to the existing data points. The SciPy library provides many functions for interpolation such as interp1d, UnivariateSpline, and InterpolatedUnivariateSpline.
For example, to interpolate a linear function using interp1d, we can use the following code:
from scipy.interpolate import interp1d
import numpy as np
x = np.linspace(0, 10, num=11, endpoint=True)
y = np.cos(-x**2/9.0)
f = interp1d(x, y)
f2 = interp1d(x, y, kind='cubic')
xnew = np.linspace(0, 10, num=41, endpoint=True)
import matplotlib.pyplot as plt
plt.plot(x, y, 'o', xnew, f(xnew), '-', xnew, f2(xnew), '--')
plt.legend(['data', 'linear', 'cubic'], loc='best')
plt.show()
Output example

The code above:
- Imports the
interp1dfunction from thescipy.interpolatelibrary and thenumpylibrary asnp - Creates
xandyarrays of data points - Uses the
interp1dfunction to create a linear interpolation functionfand a cubic interpolation functionf2 - Creates a new array of data points
xnew - Plots the original data points, the linear interpolation, and the cubic interpolation
Helpful links
More of Python Scipy
- How do I create a 2D array of zeros using Python and NumPy?
- How do I use Python Numpy to read and write Excel (.xlsx) files?
- How can I use Python and SciPy to find the zeros of a function?
- How do I use Scipy zeros in Python?
- How can I check if a certain version of Python is compatible with SciPy?
- How can I install and use SciPy on Ubuntu?
- How can I use RK45 with Python and SciPy?
- How do I create a QQ plot using Python and SciPy?
- How do I use Python Scipy to perform a Z test?
- How do I create a zero matrix using Python and Numpy?
See more codes...