简体   繁体   中英

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM