0

I have a rectangular 2D numpy array self.rho. For reasons of averaging I need an array containing the first 3 elements of self.rho[:][3]. I tried self.rho[0:3][3]. This however gives me List index out of range error, despite

print(self.rho[0][3])
print(self.rho[1][3])
print(self.rho[2][3])
print(self.rho[3][3])

working perfectly. If I do self.rho[0:100][3], no problem occures.

  • what is `self.rho.shape`? – alani Sep 30 '20 at 13:37
  • Anyway, you are trying to obtain a slice of the first 3 rows and then extract the 4th row of your slice. That is not going to work. – alani Sep 30 '20 at 13:38
  • The end of a slice is not included in python. `self.rho[0:4][3]` will work – yatu Sep 30 '20 at 13:38
  • 1
    I'd recommend you to check [understanding-slice-notation](https://stackoverflow.com/questions/509211/understanding-slice-notation) – yatu Sep 30 '20 at 13:40
  • @alani The shape is (1024, 100). I want first three elements of the 4th row – Ondra Janoška Sep 30 '20 at 13:55
  • @yatu that wouldn't give „Index out of range“ error, just print fewer elements than I wanted – Ondra Janoška Sep 30 '20 at 13:56
  • "I want first three elements of the 2nd row" - that would be `self.rho[1,:3]`. In any case, note the two-dimensional indexing. Indexing one dimension at a time is not recommended because it unnecessarily creates temporary arrays. – alani Sep 30 '20 at 13:57
  • @alani I don't understand the difference between using [1,3] and [3][1]. Also I made an error in the last message, edited now – Ondra Janoška Sep 30 '20 at 13:59
  • Numpy supports multidimensional indexing and slicing. You shoulnd't be doing array `[1:3][2]`, you should be doing `array[1:3,2]` (just an example) – yatu Sep 30 '20 at 13:59
  • `I don't understand the difference between using [1,3] and [3][1]`. Then read https://numpy.org/doc/stable/reference/arrays.indexing.html – yatu Sep 30 '20 at 13:59
  • This is basic numpy indexing – yatu Sep 30 '20 at 13:59
  • @alani even if it creates unnecesarry arrays, it shouldn't give out of range error – Ondra Janoška Sep 30 '20 at 14:03
  • @yatu Your basic point is valid, but your example above is not correct: `[1:3][2]` is not equivalent to `[1:3,2]`, for reasons which I suspect will be obvious to you as soon as you re-read what you wrote. – alani Sep 30 '20 at 14:16
  • I'm not saying they are equivalent... I'm just saying that one should use multidim indexing or slicing in numpy, not chained indexing. It was just an example... @alani – yatu Sep 30 '20 at 14:33

0 Answers0