Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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])
like image 365
Andrzej Pronobis Avatar asked Jun 02 '15 20:06

Andrzej Pronobis


2 Answers

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]
like image 182
Padraic Cunningham Avatar answered Oct 04 '22 03:10

Padraic Cunningham


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.

like image 44
hpaulj Avatar answered Oct 04 '22 04:10

hpaulj