Andrzej Pronobis
Andrzej Pronobis

Reputation: 36096

Indexing a numpy array with another array containing out of bounds values

Given the following data array:

d=np.array([10,11,12,13,14]) 

and another indexing array:

i=np.array([0, 2, 3, 6])

What is a good way of indexing d with i (d[i]) so that instead of index out of bounds error for 6, I would get:

np.array([10, 12, 13])

Upvotes: 5

Views: 4912

Answers (3)

Padraic Cunningham
Padraic Cunningham

Reputation: 180411

Maybe use i[i < d.size]] to get the elements that are less than the length of d:

print(d[i[i < d.size]])
[10 12 13]

Upvotes: 4

hpaulj
hpaulj

Reputation: 231395

It is easy to cleanup i before using it:

In [150]: d[i[i<d.shape[0]]]
Out[150]: array([10, 12, 13])

np.take has several modes for dealing with out of bounds indices, but 'ignore' is not one of them.

Upvotes: 4

user2357112
user2357112

Reputation: 280778

valid_indices = i[(i >= 0) & (i < len(d))]
selected_items = d[valid_indices]

NumPy doesn't seem to provide an error-handling mode that skips invalid indices, probably because skipping them doesn't make much sense when the result array is multidimensional. Instead, just select the elements of i in the valid range and index with those elements.

Upvotes: 0

Related Questions