這是我在StackOverflow中的第三個線程。 我想我已經通過在這裏閱讀主題並清除了我的疑惑而學會了很多。不明確的索引錯誤python
我想在我自己的python腳本中轉換一個excel表。我做了這麼多,現在我幾乎要完成腳本了,我收到了一條我不能理解的Err消息。這裏是我的代碼:(我試着給儘可能多的信息可能!)
def _sensitivity_analysis(datasource):
#datasource is a list with data that may be used for HBV_model() function;
datasource_length = len(datasource) #returns tha size of the data time series
sense_param = parameter_vector #collects the parameter data from the global vector (parameter_vector);
sense_index = np.linspace(0, 11, 12) #Vector that reflects the indexes of parameters that must be analyzed (0 - 11)
sense_factor = np.linspace(0.5, 2, 31) #Vecor with the variance factors that multiply the original parameter value;
ns_sense = [] #list that will be filled with Nasch-Sutcliff values (those numbers will be data for sensitivity analysis)
for i in range(sense_factor.shape[0]): #start column loop
ns_sense.append([]) #create column in ns_sense matrix
for j in range(sense_index.shape[0]): #start row loop
aux = sense_factor[i]*sense_param[j] #Multiplies the param[j] value by the factor[i] value
print(i,j,aux) #debug purposes
sense_param[j] = aux #substitutes the original parameter value by the modified one
hbv = _HBV_model(datasource, sense_param) #run the model calculations (works awesomely!)
sqrdiff = _square_diff() #does square-difference calculations for Nasch-Sutcliff;
average = _qcalc_qmed() #does square-difference calculations for Nasch-Sutcliff [2];
nasch = _nasch_sutcliff(sqrdiff, average) #Returns the Nasch-Sutcliff calculation value
ns_sense[i].insert(j, nasch) #insert the value into ns_sense(i, j) for further uses;
sense_param = np.array([np.float64(catchment_area), np.float64(thresh_temp),
np.float64(degreeday_factor), np.float64(field_capacity),
np.float64(shape_coeficient), np.float64(model_paramC),
np.float64(surfaceflow_param), np.float64(thresh_surface_level),
np.float64(interflow_param), np.float64(baseflow_param),
np.float64(percolation_param), np.float64(soilmoist_param)]) #restores sense_param to original values
for i in range(len(datasource)): #HBV_model() transforms original data (index = 5) in a fully calculated data (index 17)
for j in range(12): #in order to return it to original state before a new loop
datasource[i].pop() #data is popped out;
print(ns_sense) #debug purposes
所以,當我運行_sensitivity_analysis(數據源)我收到此消息:
File "<ipython-input-47-c9748eaba818>", line 4, in <module>
aux = sense_factor[i]*sense_param[j]
IndexError: index 3652 is out of bounds for axis 0 with size 31;
我完全知道它正在討論一個不可訪問的索引,因爲它不存在。
解釋我的情況,數據源是一個索引[3652]的列表。但是我看不到控制檯試圖訪問索引3652,因爲我沒有要求它這樣做。我試圖訪問這個值的唯一的一點是在最後一個循環:
for i in range(len(datasource)):
我真的迷路了。如果你能幫助我的話,我真的很高興!如果你需要更多信息,我可以給你。
放線'打印(我,j)'在出現錯誤的行之前。它打印什麼? – Barmar
根據sense_factor的定義,預期的樣本數爲31,但是您循環遍歷整個3652個索引,錯誤開始發生在第32個循環。你只能看到3652,因爲這是最後一個索引。 sense_factor均勻分佈31個樣本空間並調用索引3562超出範圍。 sense_factor只有31個採樣(均勻間隔),而循環則是3652次。 – deaspo
是的,deaspo!我在k和l的最後循環中更改了i和j。現在事情變得清晰了。 –