How to make boolean index in numpy for multiple integer types without loop

I would like to create a logical index of an array that has true values ​​whenever any integers in a given list appear in the array. Right now I am doing this by sorting through a list of test integers and creating a separate Boolean mask for each of which I am bitwise ortogether like this:

boolean_mask = original_array == list_of_codes[0]
for code in list_of_codes[1::]:
    boolean_mask = boolean_mask | (original_array == code)

Is there a numpy abbreviation for executing the equivalent without a loop?

+4
source share
2 answers

You have np.in1d:

boolean_mask = np.in1d(original_array, list_of_codes)

must do it. Note that np.in1daligns both arrays, so if yours original_arrayis multi-dimensional, you will have to reformat it, for example:

boolean_mask = boolean_mask.reshape(original_array.shape)
+5

, broadcasting :

boolean_mask = (original_array == list_of_codes)

, , , , .

0

All Articles