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
设置为索引,reindex
和interpolate
用线性插值来填充缺失的值:
(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())