python-scipyHow do I use Python and SciPy to perform spline interpolation?
Spline interpolation is a method of constructing new data points within the range of a discrete set of known data points. Python and SciPy provide a convenient set of functions for performing spline interpolation.
Example code
import numpy as np
from scipy.interpolate import interp1d
# Create a set of data points
x = np.linspace(0, 10, num=11, endpoint=True)
y = np.cos(-x**2/9.0)
# Create a linear interpolation function
f = interp1d(x, y)
# Interpolate at new points
xnew = np.linspace(0, 10, num=41, endpoint=True)
ynew = f(xnew)
The code above creates a set of data points x and y and then creates a linear interpolation function f using interp1d. The function f is then used to interpolate at new points xnew and ynew.
Code explanation
import numpy as np: imports the NumPy library asnpfrom scipy.interpolate import interp1d: imports theinterp1dfunction from the SciPy libraryx = np.linspace(0, 10, num=11, endpoint=True): creates a set of data pointsxbetween 0 and 10 with 11 pointsy = np.cos(-x**2/9.0): creates a set of data pointsyfor eachxpoint using the cosine functionf = interp1d(x, y): creates a linear interpolation functionfusinginterp1dxnew = np.linspace(0, 10, num=41, endpoint=True): creates a set of new pointsxnewbetween 0 and 10 with 41 pointsynew = f(xnew): uses the linear interpolation functionfto interpolate at the new pointsxnewand creates a set of new pointsynew
Helpful links
More of Python Scipy
- How can I use Python Numpy to select elements from an array based on multiple conditions?
- How do I create a 2D array of zeros using Python and NumPy?
- How do I create a zero matrix using Python and Numpy?
- How do I use the scipy ttest_ind function in Python?
- How can I use Python and SciPy to generate a Voronoi diagram?
- How do I calculate variance using Python and SciPy?
- How do I create a numpy array of zeros using Python?
- How can I use Python and SciPy to find the zeros of a function?
- How to use Python, XML-RPC, and NumPy together?
- How do I use Python Numpy to read and write Excel (.xlsx) files?
See more codes...