1
我有一些我想要聚合的數據,但是我得到索引超出界限的錯誤,我似乎無法弄清楚爲什麼。這裏是我的代碼:索引超出界限(Python)
if period == "hour":
n=3
tvec_a=np.zeros([24,6])
tvec_a[:,3]=np.arange(0,24)
data_a=np.zeros([24,4])
elif period == "day":
n=2
tvec_a=np.zeros([31,6])
tvec_a[:,2]=np.arange(1,32)
data_a=np.zeros([31,4])
elif period == "month":
n=1
tvec_a=np.zeros([12,6])
tvec_a[:,1]=np.arange(1,13)
data_a=np.zeros([12,4])
elif period == "hour of the day":
tvec_a=np.zeros([24,6])
tvec_a[:,3]=np.arange(0,24)
data_a=np.zeros([24,4])
i=0
if period == "hour" or period == "day" or period == "month":
while i <= np.size(tvec[:,0]):
data_a[tvec[i,n],:]=data_a[tvec[i,n],:]+data[i,:]
i=i+1
if i > np.size(tvec[:,0]):
break
我只會得到錯誤,如果我讓日期或月。小時工作得很好。 (的代碼是發生在一個tvec,數據和週期的函數的一部分)
Traceback (most recent call last):
File "<ipython-input-23-7fb910c0f29b>", line 1, in <module>
aggregate_measurements(tvec,data,"month")
File "C:/Users/Julie/Documents/DTU - design og innovation/4. semester/Introduktion til programmering og databehandling (Python)/Projekt 2 electricity/agg_meas.py", line 33, in aggregate_measurements
data_a[tvec[i,n],:]=data_a[tvec[i,n],:]+data[i,:]
IndexError: index 12 is out of bounds for axis 0 with size 12
編輯:固定它,通過從tvec上的值寫入減去1:
data_a[tvec[i,n]-1,:]=data_a[tvec[i,n]-1,:]+data[i,:]
你可以發佈完整的回溯? – syntonym
我想'data_a [tvec [i,n],:] = data_a [tvec [i,n],:] + data [i,:]'是你得到錯誤的地方,你可以嘗試打印'tvec [i ,n]'在你的那一行之前的值? – Rafalon
嗯嘗試用'<'替換'<='在你的時間? **編輯**哈! @Karin也回答了這個問題 – Rafalon