让我们考虑一系列值:
s = pandas.Series([0, np.nan, np.nan, 1])
和一系列权重:
w = pandas.Series([np.nan, 1, 0, 1])
经典的线性插值会给我:
>>> s.interpolate()
0 0.000000
1 0.333333
2 0.666667
3 1.000000
dtype: float64
我需要一个 weighted_interpolate 方法,它考虑 w[i] ~ s[i] - s[-1]
并且应该返回:
>>> weighted_interpolate(s, w)
0 0.000000
1 0.500000
2 0.500000
3 1.000000
dtype: float64
我怎样才能做到这一点?我找到了 piecewise_polynomial
方法,但我不知道如何让它工作。
最佳答案
Michael 给了我所需的提示。这是一个仅使用 ufunc(例如 numpy 函数)的加权插值示例。
将 pandas 导入为 pd 将 numpy 导入为 np
s = pd.Series([0, np.nan, np.nan, 1, np.nan, np.nan, np.nan, 2])
w = pd.Series([0, 1, 0, 1, 1, 2, 0, 1])
print(s.interpolate())
sb = s.fillna(method='ffill')
se = s.fillna(method='bfill')
cw = w.cumsum()
w2 = pd.Series(None, index=s.index)
w2[~np.isnan(s)] = cw[~np.isnan(s)]
wb = w2.fillna(method='ffill')
we = w2.fillna(method='bfill')
cw = (cw - wb) / (we - wb)
r = sb + cw * (se - sb)
r.update(s)
print(r)
下面是已知点的图,线性插值和加权插值
关于python - pandas.Series 中的加权插值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33555786/