python - pandas.Series 中的加权插值

标签 python pandas scipy

让我们考虑一系列值:

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)

下面是已知点的图,线性插值和加权插值

Example

关于python - pandas.Series 中的加权插值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33555786/

相关文章:

pandas - Github 在 Pull Request 之前或之后合并对 Master 的更改

python - 问题导入 scikit-learn : module 'scipy' has no attribute '_lib'

python - RegEx Python - 我想编写 RegEx,通过它我可以将 { expression } 替换为 {% print expression %}

python - 如何从 PySpark 的 SQLite 数据库文件加载表?

python - Pylint 无效的函数名

python - 填充 Pandas 中缺失的 bool 行

python - OpenCV HoughCircles 偶尔会返回 [0. 0. 0.]

Pandas 索引名称、轴标签和级别

python - 偏微分方程中的时空参数 - 使用 Python 中的线法求解

python - numpy complex128 转换