如何在Python中使用类似步骤的值插入和平滑数据?

时间:2016-04-26 13:57:46

标签: python numpy scipy interpolation

我有data步骤式的方式,如图所示,我试图用Python用MWE插入,但是我得到了错误:

enter image description here

错误

File "/usr/lib/python2.7/dist-packages/scipy/interpolate/polyint.py", line 54, in __call__ y = self._evaluate(x) File "/usr/lib/python2.7/dist-packages/scipy/interpolate/interpolate.py", line 448, in _evaluate out_of_bounds = self._check_bounds(x_new) File "/usr/lib/python2.7/dist-packages/scipy/interpolate/interpolate.py", line 478, in _check_bounds raise ValueError("A value in x_new is above the interpolation " ValueError: A value in x_new is above the interpolation range.

MWE

import numpy as np
from scipy import optimize, interpolate
from scipy.interpolate import interp1d
import time


with open('./pdf_data.dat', "r") as data:
    while True:
        line = data.readline()
        if not line.startswith('#'):
            break
    data_header = [i for i in line.strip().split('\t') if i]
    _data_ = np.genfromtxt(data, names = data_header, dtype = None, delimiter = '\t')
_data_.dtype.names = [j.replace('_', ' ') for j in _data_.dtype.names]


x = _data_['X']
y = _data_['Y']


interp_fn = interp1d(x, y)
x, index = np.unique(x, return_index = True)


pdf_interp = interp_fn(x)

如何在Python中插入和平滑类似步骤的值?这样我得到了平滑的曲线。

1 个答案:

答案 0 :(得分:0)

只需通过以下方式重现您的错误:

from scipy.interpolate import interp1d
f = interp1d([1,2,3,3,4],[1,2,3,4,5])
f([1,2,3,4])  # prints [1,2,3,5], note that the 3rd value is not as you may expect
f([1,2,3,4,5])

最后一个命令f([1,2,3,4,5])的错误消息:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\winPython\python-2.7.10.amd64\lib\site-packages\scipy\interpolate\polyint.py", line 79, in __call__
    y = self._evaluate(x)
  File "C:\winPython\python-2.7.10.amd64\lib\site-packages\scipy\interpolate\interpolate.py", line 497, in _evaluate
    out_of_bounds = self._check_bounds(x_new)
  File "C:\winPython\python-2.7.10.amd64\lib\site-packages\scipy\interpolate\interpolate.py", line 527, in _check_bounds
    raise ValueError("A value in x_new is above the interpolation "
ValueError: A value in x_new is above the interpolation range.

因此,请在脚本中打印出x值,看它是否包含超出范围的值。

由于您在代码中使用了np.unique,因此您似乎需要拨打interp_fn(equivalence_ratio)而不是interp_fn(x)

x1, index = np.unique(x, return_index = True)
y1 = [y[k] for k in index]
interp_fn = interp1d(x1, y1)
pdf_interp = interp_fn(x)

此代码适用于您附加的数据文件。