简体   繁体   中英

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

My code:

import numpy as np
num_people = 2
x = np.zeros((1,75,1,1792,num_people))
for i in range(num_people):
  x[1,:,:,:,i]=np.arange(75,1,1792)

Error:

IndexError                                Traceback (most recent call last)
<ipython-input-17-941de32daec2> in <module>()
      1 for i in range(num_people):
----> 2   x[1,:,:,:,i]=np.arange(75,1,1792)

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

The answer lies in Python's GOLDEN RULE - everything starts with zero. You made -

x = np.zeros((1,75,1,1792,num_people))

which says that x will have a shape of (1, 75, 1, 1792, 2) and the first axis will only have 1 item, but while in for a loop when say -

x[1,:,:,:,i] you are asking for a 2nd item which doesn't even exist in the first axis,

So replacex[1,:,:,:,i] with x[0,:,:,:,i]

It would be really helpful if you understand the difference between shape and accessing the dimension. So shape 1 means you have only 1 item, but while accessing it you need to say give me 0th value(as everything starts from zero)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM