Indexing a numpy array with another array containing border values

Given the following data array:

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

and another index array:

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

What is a good way to index dusing i( d[i]), so instead of an index error outside the error for, 6I would get:

np.array([10, 12, 13])
+4
source share
3 answers

Perhaps use i[i < d.size]]to get elements that are shorter than length d:

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

Easy to clean ibefore using it:

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

np.takehas several modesfor processing indices outside the bounds, but ignoring is not one of them.

+4
source
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 indexes, perhaps because skipping them doesn't make much sense when the result array is multidimensional. Instead, simply select the elements iin the valid range and index with these elements.

0
source

All Articles