Index out of bounds (Python)

点点圈 提交于 2020-01-05 07:31:29

问题


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 "<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

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,:]

回答1:


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.



来源:https://stackoverflow.com/questions/43775448/index-out-of-bounds-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!