5

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])

3 Answers 3

4

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

5 Comments

Directly using the mask would also work: d[i<d.size].
@Divakarm thanks, that is a bit nicer but that would give 10,11,12 no or am I misunderstanding something?
@Divakar, no worries, d.size is still nicer than len
I like that, nice and clean.
@And, it is the best I have to offer, there may well be better ways but I don't know them!
4

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.

1 Comment

Thanks for the hints about take. I found it after posting the question, but indeed there is no "ignore". Padraic Cunningham was first with the main idea though :)
0
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.

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.