使用SciPy插值不均匀数据

3
我一直在查看scipy.interpolate文档中的示例,但是我无法弄清楚如何对不均匀间隔的数据进行插值,因为所有的教程都使用等距空间。例如,我有一些数据分布如下:
[--1--4-----5-3-22---55-]

每个-代表一个缺失值。

我该如何使用scipy.interpolate拟合插值函数?


你尝试过将x向量设置为具有数据的索引,将y向量设置为这些索引处的值吗?我不确定这在你的情况下是否有效,但这是我想到的。 - Engineero
1个回答

4

interpolate.interp1d可以很好地处理不均匀间隔的数据。例如,

import re
import numpy as np
import scipy.interpolate as interpolate
import matplotlib.pyplot as plt

text = '--1--4-----5-3-22---55-'
parts = [c for c in re.split(r'(-|\d+)', text) if c]
data = np.array([(x, int(y)) for x, y in enumerate(parts) if y != '-'])
x, y = data.T
f = interpolate.interp1d(x, y, kind='cubic')

newx = np.linspace(x.min(), x.max())
newy = f(newx)
plt.plot(newx, newy)
plt.scatter(x, y, s=20)
plt.show()

产量 enter image description here


谢谢!作为后续,我是否可以将插值函数扩展到数据之外?当我尝试通过在linspace(0,some_number>x.max())上运行它来简单地执行此操作时,我会收到一个ValueError,指出x_new中有一个超出插值范围的值。 - zmjjmz
1
@zmjjmz,文档中有说明http://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.interp1d.html#scipy.interpolate.interp1d:只需添加 bounds_error=False - Stefano M

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接