pythonipythonastronomy

How to solve Index out of bounds error?


I'm a bit confused on an error I keep running into. I didn't have it before, but at the same time my data was wrong so I had to re-write the code.

Running the following:

plt.figure(figsize=(20,10))
x = np.arange(1416, 1426, 0.009766)

gaverage = np.empty((21,1024), dtype = np.float64)

calibdata = open(pathc + 'calib_5m.dat').readlines()

#print(np.size(calibdata))     ||| Yields: 624
#print(np.size(calibdata)//16) ||| Yields: 39

calib = np.empty(shape=(np.size(calibdata)//16,1024), dtype=np.float64)
for i in range(0, np.size(calibdata)//4):
    calib[i] = calibdata[i*4+3].split()
caverage = np.average(calib[i] ,axis = 0)

Yields this:

---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-25-87f3f4739851> in <module>()
     11 calib = np.empty(shape=(np.size(calibdata)//16,1024), dtype=np.float64)
     12 for i in range(0, np.size(calibdata)//4):
---> 13     calib[i] = calibdata[i*4+3].split()
     14 caverage = np.average(calib[i] ,axis = 0)
     15 

IndexError: index 39 is out of bounds for axis 0 with size 39

Now what I'm trying to do here is basically take every 4th line in the file read in calibdata and write it to a new array, calib[i]. If the indices are the same size how are they out of bounds? I think there's some fundamentally flawed logic here on my part so if anyone can point out where I'm falling short, that would be great.


Solution

  • calib is initialized to size (39,n). But i iterator goes well beyond that:

    In [243]: for i in range(np.size(calibdata)//4):
         ...:     print(i, i*4+3)
         ...:     
    0 3
    1 7
    2 11
    3 15
    4 19
    5 23
    6 27
    7 31
    8 35
    ....
    147 591
    148 595
    149 599
    150 603
    151 607
    152 611
    153 615
    154 619
    155 623
    
    In [244]: calib=np.zeros((np.size(calibdata)//16),int)
    In [245]: calib.shape
    Out[245]: (39,)