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
interp1d
function from thescipy.interpolate
library and thenumpy
library asnp
- Creates
x
andy
arrays of data points - Uses the
interp1d
function to create a linear interpolation functionf
and 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 can I use Python and Numpy to parse XML data?
- How can I use Python Numpy to select elements from an array based on multiple conditions?
- How can I use Python and SciPy to find the zeros of a function?
- How do I create a zero matrix using Python and Numpy?
- How do I use Python Numpy to read and write Excel (.xlsx) files?
- How do I create an array of zeros with the same shape as an existing array using Python and NumPy?
- How can I use Python Scipy to zoom in on an image?
- How do I create a numpy array of zeros using Python?
- How do I use Scipy zeros in Python?
See more codes...