Search code examples
pythonnumpyappendindices

IndexError when trying to append with for loop


This might be a foolish question, I am trying to append values to a new empty array using a for loop and the values from a previously defined 3 dimensional array called data_train_normalized, which contains floats.

The objective is to end up with an array called xthat has the value from the data_train_normalized in each value of the iteration. For example, x[0] should be the value data_train_normalized[1,1,1]

This sample code summarizes what I am trying to do:

x=np.array([])
for z in range(1,4):
  for x in range(1,4):
    for y in range(1,4):
      x = np.append(x,data_train_normalized[z][x][y])

And this throws:

IndexError                                Traceback (most recent call last)
<ipython-input-43-b0e7b7ab30e9> in <module>()
      3   for x in range(1,4):
      4     for y in range(1,4):
----> 5       x = np.append(x,data_train_normalized[z][x][y])
      6 #      print(data_train_normalized[z][x][y], z, x, y)

IndexError: arrays used as indices must be of integer (or boolean) type

Solution

  • The indices returned to that 3 dimensional array by x,y,z are floats! Whereas Python only supports integer and Boolean for indices of arrays (The error mentions this).

    IndexError: arrays used as indices must be of integer (or boolean) type.
    

    You can try converting x , y and z into int before passing them as indices simply using x=int(x) , y = int(y)

    Also if you want to start the range from 1 only , then range(4) will do the work! Refer to this for more info: Python range ()