为什么scipy的插值平均值不超过并置值?

2024-04-26 20:44:58 发布

您现在位置:Python中文网/ 问答频道 /正文

如果我运行以下代码:

>>> from scipy.interpolate import interpolate
>>> import numpy as np
>>> data = np.arange(10)
>>> times = np.r_[np.arange(5),np.arange(5)]
>>> new_times = np.arange(5)
>>> f = interpolate.interp1d(times,data)
>>> interp_data = f(new_times)

我很天真地希望:

^{pr2}$

基于同位值的平均值和插值中相应加权的假设。但事实上,结果是:

>>> interp_data               
array([ 0.,  6.,  7.,  8.,  9.])

是什么导致了这种行为,如何纠正?在


Tags: 代码fromimportnumpynewdataasnp
3条回答

不,interp1d不会为您加权、平均或对数据做任何其他操作。在

它希望对数据进行排序。如果你的scipy是最新的(0.14或更高版本),它有assume_sorted关键字,你可以将其设置为False,然后它会为你排序。未排序数据的精确行为未定义。在

来自interp1d文档:

assume_sorted : bool, optional If False, values of x can be in any order and they are sorted first. If True, x has to be an array of monotonically increasing values.

我只能通过明确地强制assume_sortedTrue得到你得到的结果:

>>> f = interpolate.interp1d(times,data, assume_sorted=True)
>>> interp_data = f(new_times)
>>> interp_data
array([ 0.,  6.,  7.,  8.,  9.])

从代码中可以看出,assume_sorted默认为True,这给出了您意想不到的答案。在

如果显式地将其设置为False,根据文档,interp1d会自动对其排序,然后进行插值,得到

^{pr2}$

与文件相符。在

我不确定你到底想要什么,但看来interp可能不是实现这一目标的最佳方式。插值函数f应将单个输入与单个输出相关联,即

from scipy.interpolate import interpolate
import numpy as np
data = np.arange(2.,8.)
times = np.arange(data.shape[0])
new_times = np.arange(0.5,5.,1.)
f = interpolate.interp1d(times,data)
interp_data = f(new_times)

或者,可以这样回答: Get sums of pairs of elements in a numpy array 可能是你想要的?在

相关问题 更多 >