How to apply cubic spline interpolation over a long Pandas series?

I need to replace missing data in a pandas series using cubic spline interpolation. I realized that I can use a method pandas.Series.interpolate(method='cubic')that looks like this:

import numpy as np
import pandas as pd

# create series
size = 50
x = np.linspace(-2, 5, size)
y = pd.Series(np.sin(x))

# deleting data segment
y[10:30] = np.nan

# interpolation
y = y.interpolate(method='cubic')

Although this method is great for small series ( size = 50), it seems that the program freezes for larger ( size = 5000) ones. Is there a workaround?

+4
source share
1 answer

pandascalls scipyinterpolation procedures, I'm not sure why it is 'cubic'so hungry and slow.

method='spline' (scipy ref ), (, ?) .

In [104]: # create series
     ...: size = 2000
     ...: x = np.linspace(-2, 5, size)
     ...: y = pd.Series(np.sin(x))
     ...: 
     ...: # deleting data segment
     ...: y[10:30] = np.nan
     ...: 

In [105]: %time cubic = y.interpolate(method='cubic')
Wall time: 4.94 s

In [106]: %time spline = y.interpolate(method='spline', order=3, s=0.)
Wall time: 1 ms

In [107]: (cubic == spline).all()
Out[107]: False

In [108]: pd.concat([cubic, spline], axis=1).loc[5:35, :]
Out[108]: 
           0         1
5  -0.916444 -0.916444
6  -0.917840 -0.917840
7  -0.919224 -0.919224
8  -0.920597 -0.920597
9  -0.921959 -0.921959
10 -0.923309 -0.923309
11 -0.924649 -0.924649
12 -0.925976 -0.925976
13 -0.927293 -0.927293
+4

Source: https://habr.com/ru/post/1606772/


All Articles