python索引超出范围怎么解决_索引超出范围(Python)

I have some data that I would like to aggregate, but I'm getting the index out of bounds error, and I can't seem to figure out why. Here's my code:

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

I only get the error if I make period day or month. Hour works just fine.

(The code is part of a function that takes in a tvec, data and period)

Traceback (most recent call last):

File "", line 1, in

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

EDIT: Fixed it, by writing minus 1 on the value from the tvec:

data_a[tvec[i,n]-1,:]=data_a[tvec[i,n]-1,:]+data[i,:]

解决方案

Since lists are 0-indexed, you can only go up to index 11 on a 12-element array.

Therefore while i <= np.size(tvec[:,0]) should probably be while i < np.size(tvec[:,0]).

Extra Note: The break is unnecessary because the while loop will stop once the condition is met anyway.