Skip to main content
 首页 » 编程设计

python之Pandas/Scipy中的具体插值方法

2025年05月04日14daizhj

首先创建数据:

import pandas as pd 
import numpy as np 
%matplotlib inline 
data = pd.DataFrame({'time':np.arange(10)}) 
data['sin_of_the_times']= np.sin(data.time) 
newdata = pd.DataFrame({'time': np.linspace(0,10,15)}) 
newdata['sin_of_the_times'] = np.NAN 
data['interpolated']=False 
newdata['interpolated']= True 
ultimatedata = pd.concat([data, newdata]) 
ultimatedata.sort_values('time', inplace=True) 

这给了你这个:

    time    sin_of_the_times    interpolated 
0   0.000000    0.000000    False 
0   0.000000    NaN         True 
1   0.714286    NaN         True 
1   1.000000    0.841471    False 
2   1.428571    NaN         True 
2   2.000000    0.909297    False 
... 

在不创建新函数的情况下 Python 中是否已经存在一种插值方法,它将采用:

  • 第一个 NaN 并说 time=0.0 是 time=0 和 time=1.0 之间的 0%,因此是 0 和 .8 之间的 0%,因此将为 0.0。
  • 第二个 NaN 将是 0 和 1 之间的 7/10(ish),因此是 0 到 0.841471 的 7/10,所以它将是 .5890297
  • 第三个 NaN 将是 1 和 2 之间的 4/10(ish),因此也是 0.841471 和 0.909297 之间的 4/10

这种插​​值方法有名称吗? (在本例中是上采样)插值方法似乎仅基于一列。

请您参考如下方法:

您仍然想进行线性插值;您只想指定点之间的距离取决于 time 而不是假设它们是均匀分布的。所以首先将索引设置为 time 然后使用 interpolate

df = df.set_index('time') 
df.sin_of_the_times.interpolate(method='index') 

输出:

time 
0.000000    0.000000 
0.000000    0.000000 
0.714286    0.601051 
1.000000    0.841471 
1.428571    0.870539 
2.000000    0.909297 
Name: sin_of_the_times, dtype: float64 

这是我的起点:df

       time  sin_of_the_times 
0  0.000000          0.000000 
0  0.000000               NaN 
1  0.714286               NaN 
1  1.000000          0.841471 
2  1.428571               NaN 
2  2.000000          0.909297