Reputation: 36096
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
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
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
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