我正在尝试使用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
如何解决这个问题?
问题可能在这里:
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]