python步长值_如何在Python中使用类似步长的值插值和平滑数据?

我有数据在阶梯状在图中所示的方式,而我试图插值与Python与MWE,但我得到的错误:

错误

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中插值和平滑步阶值?这样我得到了一条平滑的曲线。

解决方案

可以简单地通过以下方式重现您的错误:

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 "", line 1, in

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)

此代码与您附加的数据文件配合良好。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值