Using python boolean operators when slicing a numpy array

I would like to perform slicing on a two-dimensional numpy array:

type1_c = type1_c[ (type1_c[:,10]==2) or (type1_c[:,10]==3) or (type1_c[:,10]==4) or (type1_c[:,10]==5) or (type1_c[:,10]==6) ] 

The syntax looks right; however, I received the following error message: "The truth value of an array with more than one element is ambiguous. Use a.any () or a.all () '

I really donโ€™t understand what is going wrong. Any idea?

+4
source share
1 answer

or is unique when it is between two scalars, but what is the correct vector generalization? if x == array([0, 0]) and y == array([0,1]) , must x or y be (1) False, because not all pairwise or -ed members together are True, (2 ) True, because at least one pairwise result of or (3) array([0, 1]) , because it is pairwise the result of or , (4) array([0, 0]) , because [0,0] or [0,1] will return [0,0] , because non-empty lists are true, and therefore should the array be?

Here you can use | and consider it as a bitwise problem:

 >>> import numpy as np >>> vec = np.arange(10) >>> vec[(vec == 2) | (vec == 7)] array([2, 7]) 

Explicitly use numpy vector boolean or:

 >>> np.logical_or(vec==3, vec==5) array([False, False, False, True, False, True, False, False, False, False], dtype=bool) >>> vec[np.logical_or(vec==3, vec==5)] array([3, 5]) 

or use in1d , which is much more efficient here:

 >>> np.in1d(vec, [2, 7]) array([False, False, True, False, False, False, False, True, False, False], dtype=bool) >>> vec[np.in1d(vec, [2, 7])] array([2, 7]) 
+7
source

All Articles