m_amber
m_amber

Reputation: 757

IndexError in numpy array

I have a code which looks like this

 for a in range(0,128):
      for b in range(0,128):
           A = np.zeros((1,3))
           B = np.zeros((1,3))
           for i in range(0,3):
                A[i] = I[a,b,i]

However, it gives me the following error

 A[i] = I[a,b,i]
 IndexError: index 1 is out of bounds for axis 0 with size 1

Thank You, in advance.

Upvotes: 0

Views: 4096

Answers (1)

jonrsharpe
jonrsharpe

Reputation: 122024

np.zeros((1, 3)) creates an array with one "row" and three "columns":

array([[ 0.,  0.,  0.]]) # note "list of lists"

If you want to index straight into the columns, you can simply create the array as:

A = np.zeros(3)

and get

array([ 0.,  0.,  0.])

Then your loop will work as currently written.

Alternatively, you will need to index into the row first:

for index in range(3):
    A[0, index] = ...

Upvotes: 4

Related Questions