5

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!

5
  • 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) Commented Sep 10, 2020 at 14:19
  • sorry, I have made a mistake in the question. Now corrected Commented Sep 10, 2020 at 14:21
  • i think you want: my_array[130:240, :610] (you shouldn't overwrite the std. lib's len function) Commented Sep 10, 2020 at 14:21
  • Yeah, but I don't want to put numbers there. Thanks for the help! Commented Sep 10, 2020 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. Commented Sep 10, 2020 at 15:39

1 Answer 1

7

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.