interpolate.splev错误:'第一个三个参数的长度(x,y,w)必须相等

2 投票
1 回答
1019 浏览
提问于 2025-04-18 18:18

我正在尝试使用scipy.interpolate来进行最小二乘拟合,方法如下:

from scipy import interpolate
xnew = np.arange(min(l_bins), max(l_bins))
list1=l_bins
list1.remove(l_bins[0])
list1.remove(l_bins[-1])
tck = interpolate.splrep(l_bins,l_hits,k=3,task=-1,t=list1)
fnew = interpolate.splev(xnew, tck, der=0)
plt.plot(xnew, fnew, 'b-')

当我运行这段代码时,出现了这个错误:

TypeError: Lengths of the first three arguments (x,y,w) must be equal

我该如何解决这个问题呢?

1 个回答

1

问题可能出在这里:

list1=l_bins
list1.remove(l_bins[0])
list1.remove(l_bins[-1])

当你写 list1=l_bins 时,list1 实际上指向的是和 l_bins 一样的对象。这并不是一个复制品。所以当你用 remove 方法直接从 list1 中删除元素时,其实也在修改 l_bins。举个例子;注意直接修改 b 也会修改 a

In [17]: a = [10, 20, 30]

In [18]: b = a

In [19]: b.remove(10)

In [20]: b
Out[20]: [20, 30]

In [21]: a
Out[21]: [20, 30]

要解决这个问题,list1 应该是 l_bins 的一个 复制品。看起来 l_bins 是一个 Python 列表。在这种情况下,你可以这样写:

list1 = l_bins[:]

不过,看起来你想从 list1 中删除 l_bins 的第一个和最后一个元素。在这种情况下,你可以把这个:

list1 = l_bins[:]
list1.remove(l_bins[0])
list1.remove(l_bins[-1])

替换为:

list1 = l_bins[1:-1]

撰写回答