# Spline Interpolation in Python

This tutorial will demonstrate using the scipy module and perform spline interpolation in Python.

In Python, we use interpolation to deal with massive data sets and efficiently use different data processing techniques. It makes the data curve smooth by adding discrete data points and helping in filling missing values.

The scipy module is used to perform different scientific computations and implement other technical algorithms. It also provides a wide range of functions to interpolate on a dataset.

Spline interpolation is used when the interpolant is a piecewise polynomial called a spline.

This method requires less computation and provides a high accuracy rate in data.

## Use `splrep()`

and `splev()`

to Perform Spline Interpolation in Python

The steps to perform spline interpolation are divided into two parts. This is mainly to improve computational efficiency.

Different spline interpolation techniques are available in the `scipy.interpolation`

module. We can use the `splrep()`

and `splev()`

functions to evaluate the spline curve and perform cubic spline interpolation for one-dimensional data in Python.

The coefficients for the spline curve are calculated using the `splrep()`

function. Then, the `splev()`

function evaluates the data points from these coefficients.

See the code below.

```
from scipy import interpolate
x_pts = [0, 1, 2, 3, 4, 5]
y_pts = [10,15,21,38,55,76]
x2 = [i for i in range(0,10)]
tck = interpolate.splrep(x_pts, y_pts)
y_res = interpolate.splev(x2, tck)
plt.plot(x_pts, y_pts, 'o', x2, y_res)
```

Output:

In the above example, we compute the coefficients for a given data and increase the data points. We create a new set of elements for the x-axis.

We make the new data points from these coefficients for the y-axis corresponding to the elements at the x-axis.

These new points are plotted in the orange color as shown in the above figure.

There are other methods also available for spline interpolation. To calculate the bivariate B-spline interpolation curve for a surface (calculating two variables), we can use the `bisplrep()`

and `bisplev()`

function.

There are also classes in the scipy module for calculating spline interpolation.

The `BivariateSpline`

is the base class for bivariate splines. This is not instantiated directly but acts as a subclass for other classes like `SmoothBivariateSpline`

, `LSQBivariateSpline`

, or `RectBivariateSpline`

.

**Manav Narula**

Manav is a IT Professional who has a lot of experience as a core developer in many live projects. He is an avid learner who enjoys learning new things and sharing his findings whenever possible.

LinkedIn