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:
d
i
d[i]
6
np.array([10, 12, 13])
Perhaps use i[i < d.size]]to get elements that are shorter than length d:
i[i < d.size]]
print(d[i[i < d.size]]) [10 12 13]
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.
np.take
modes
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.