How to find values ​​in an array that satisfy two conditions using Python

I have an array

a=[1,2,3,4,5,6,7,8,9] 

and I want to find the indices of s satisfying two conditions: i.e.

 a>3 and a<8 ans=[3,4,5,6] a[ans]=[4,5,6,7] 

I can use numpy.nonzero(a>3) or numpy.nonzero(a<8) but there is no numpy.nonzero(a>3 and a<8) , which gives an error:

 ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() 

When I try to use any or all , I get the same error. Is it possible to combine two conditional tests to get ans?

+19
python numpy find
Jul 14 '10 at 16:55
source share
3 answers
 numpy.nonzero((a > 3) & (a < 8)) 

& makes the element logically boolean and.

+23
Jul 14 '10 at 17:03
source share

An alternative (which I used) is numpy.logical_and :

 choice = numpy.logical_and(np.greater(a, 3), np.less(a, 8)) numpy.extract(choice, a) 
+3
Oct 22 '14 at 15:34
source share

if you use a numpy array, you can directly use ' & ' instead of ' and '.

 a=array([1,2,3,4,5,6,7,8,9]) a[(a>3) & (a<8)] ans=array([3,4,5,6]) 
0
Jun 14 '17 at 14:59
source share



All Articles