Python : 如何对缺失率进行插值并绘制插值曲线与原始曲线进行比较?

Python : How to interpolate the missing rates and plot the interpolated curve to compare the original curve?

data = {'tenor_yrs': [.1, .2, .3, .5, 1, 3, 5, 10, 15, 20, 25, 30,40,50], 'rates': [NaN, NaN, NaN, NaN, 2.01, 3, 1.99, 2.05, 3.19, 1.99, 3.16, 2.54, 3.5, 2.79]}

df = pd.DataFrame(data)

请建议如何在 python 中插入缺失的年份率以使用线性插值构建此曲线并绘制相同的曲线。期限中的小数点数是月数。

可以设置tenor_years为索引,reindexinterpolate用线性插值来填充缺失值:

(df.set_index('tenor_yrs')
   .reindex(range(int(df.tenor_yrs.max())))
   .interpolate()
   .reset_index())

   tenor_yrs  rates
0          0    NaN
1          1  2.010
2          2  2.505
3          3  3.000
4          4  2.495
5          5  1.990
6          6  1.990
7          7  1.990
8          8  1.990
...

更新 -

要将小数位作为步长,请使用:

start = int(df.tenor_yrs.min())
end = int(df.tenor_yrs.max())
step = df.loc[df.tenor_yrs>0, 'tenor_yrs'].min()

import numpy as np

(df.set_index('tenor_yrs')
   .reindex(np.arange(start, end, step))
   .interpolate()
   .reset_index())