4

I have two indexing arrays.

elim=range(130,240)
tlim=range(0,610)

The array to be indexed, I, has originally shape of (299, 3800)

When I try to index it as follow

I[elim,tlim]

I got the following error message.

shape mismatch: indexing arrays could not be broadcast together with shapes (110,) (610,)

I didn't expect such errors. Could someone explain what is happening here?

Thanks!

yatu
  • 86,083
  • 12
  • 84
  • 139
  • 1
    Well how are you expecting to index up to row 610 if the array has 299 rows? (although the error is caused by something else) – yatu Sep 10 '20 at 14:19
  • sorry, I have made a mistake in the question. Now corrected – Habtamu Wubie Sep 10 '20 at 14:21
  • i think you want: `my_array[130:240, :610]` (you shouldn't overwrite the std. lib's `len` function) – Paul H Sep 10 '20 at 14:21
  • Yeah, but I don't want to put numbers there. Thanks for the help! – Habtamu Wubie Sep 10 '20 at 14:23
  • With advanced indexing (lists or arrays), the index arrays `broadcast` against each other. A (n,) array will work with a (n,) producing (n,) result. A (n,1) will work with a (1,m) to produce a (n,m) result. Same broadcasting rules as when adding or multiplying arrays. – hpaulj Sep 10 '20 at 15:39

1 Answers1

4

Let's reproduce the example with a random array of the specified shape:

elim=range(0,610)
tlim=range(130,240)
a = np.random.rand(299, 3800)

a[tlim, elim]

IndexError: shape mismatch: indexing arrays could not be broadcast together with shapes (110,) (610,)

This raises an error because you're using arrays of integer indexes to index the array, and hence advanced indexing rules will apply. You should use slices for this example

a[130:240,0:610].shape
# (110, 610)

See Understanding slice notation (NumPy indexing, is just an extension of the same concept up to ndimensional arrays.

For the cases in which you have a list of indices, not necessarily expressable as slices, you have np.ix_. For more on numpy indexing, this might help

a[np.ix_(tlim, elim)].shape
# (110, 610)
yatu
  • 86,083
  • 12
  • 84
  • 139