如何在长熊猫系列上应用三次样条插值?

Cro*_*lle 6 python interpolation pandas

我需要使用三次样条插值替换pandas系列中的缺失数据.我发现我可以使用这个pandas.Series.interpolate(method='cubic')方法,如下所示:

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')
Run Code Online (Sandbox Code Playgroud)

虽然这种方法适用于小型系列(size = 50),但它似乎会导致程序冻结较大的(size = 5000).有解决方法吗?

chr*_*isb 8

pandas呼唤scipy插值程序,我不知道为什么'cubic'内存饥饿和缓慢.

作为一种解决方法,您可以使用method='spline'(scipy ref here),它具有正确的参数,基本上(似乎是一些浮点差异?)给出相同的结果并且速度更快.

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
Run Code Online (Sandbox Code Playgroud)

  • @MuhammadYasirroni “s”的文档位于 https://docs.scipy.org/doc/scipy/reference/ generated/scipy.interpolate.splrep.html#scipy.interpolate.splrep - 基本上,较高的 s 值会导致更平滑的样条线。 (2认同)