我正在嘗試編寫一段代碼來將過濾器應用於數據集。該濾波器有兩個關鍵位數據,波長和吞吐量。數據文件還有兩個關鍵的數據位,波長和通量。不幸的是,過濾器文件和數據文件中的波長並不總是匹配。下面的代碼旨在使用y=mx+c
在數據點之間進行插值,因此獲得通過濾波器的通量的近似值,其波長不等於濾波器文件中的波長。Python:如何修復插值例程
def openfilterfile(filterfile):
throughput=[]
filterwavelength=[]
text_file2 = open(filterfile, "r")
lines2 = text_file2.read()
#print lines2
text_file2.close()
b = [float(y) for y in lines2.split()]
b1=0
b2=1
while b1<len(b):
filterwavelength.append(b[b1])
throughput.append(b[b2])
b1+=2
b2+=2
print len(filterwavelength), len(throughput)
f=scipy.interpolate.interp1d(filterwavelength, throughput, kind='linear')
xnew = filterwavelength
ynew = f(xnew)
pylab.plot(filterwavelength, throughput, xnew, ynew)
pylab.xlim(0, 25000)
pylab.show()
return filterwavelength, throughput
def accountforfilter(wavelength, flux, filterwavelength, throughput):
filteredwavelength=[]
filteredflux=[]
for i in range(len(wavelength)):
for j in range(len(wavelength)):
if wavelength[i]==filterwavelength[j]:
j=filterwavelength.index(wavelength[i])
filteredwavelength.append(wavelength[i])
filteredflux.append(flux[i]*throughput[j])
elif wavelength[i]<filterwavelength[j]<wavelength[i+1]:
filteredwavelength.append(wavelength[i])
filteredflux.append(flux[i]*f(wavelength[i]))
elif wavelength[i]<filterwavelength[j]:
i+=1
elif wavelength[i]>filterwavelength[j+1]:
j+=1
return filteredwavelength, filteredflux
當我運行它,我得到錯誤信息:
Traceback (most recent call last):
File "C:\Python27\05.12.2014.py", line 103, in <module>
filteredwavelength, filteredflux = accountforfilter(wavelength, flux, filterwavelength, throughput)
File "C:\Python27\05.12.2014.py", line 87, in accountforfilter
if wavelength[i]==filterwavelength[j]:
IndexError: list index out of range
如果我改變它,這樣j
是在range(filterwavelength)
,然後程序繼續運行,但我認爲這是遍歷每個我的所有j,永遠都是。有沒有更好的寫作方式?