Skip to content Skip to sidebar Skip to footer

Numpy Array Indexing With Other Arrays Yields Broadcasting Error

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

Solution 1:

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)

Post a Comment for "Numpy Array Indexing With Other Arrays Yields Broadcasting Error"