![](/img/trans.png)
[英]How can I interpolate unsorted 2D numpy arrays in Python and compare the interpolated values to the original one?
[英]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
设置为索引、 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())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.