Python array filtering out of bounds

I tried to do this in python, but I get an error:

import numpy as np
array_to_filter = np.array([1,2,3,4,5])
equal_array = np.array([1,2,5,5,5])
array_to_filter[equal_array]

and this leads to:

IndexError: index 5 is out of bounds for axis 0 with size 5

What gives? I thought I was doing the right operation here.

I expect if I do

array_to_filter[equal_array]

So that he returns

np.array([1,2,5])

If I'm not on the right track, how would I do it?

+4
source share
2 answers

In the last statement, the indexes for your array are 1,2,5,5 and 5. Index 5 refers to the 6th element of the array, while you have only 5 elements. array_to_filter[5]does not exist.

[i for i in np.unique(equal_array) if i in array_to_filter]

will return the answer you want. This returns each unique value in equal_array if it also exists in array_to_filter

0
source

array_to_filter , :

>>> array_to_filter[np.in1d(array_to_filter, equal_array)]
array([1, 2, 5])

: np.in1d python in 1- D . in1d(a, b) np.array([item in b for item in a]).

0

Source: https://habr.com/ru/post/1648314/


All Articles