Store numpy array values ​​that satisfy two or more conditions

I want to save array values ​​that satisfy two or more conditions, for example:

a = np.array([1,3,5,6,4,6,7,8,9]) 

I want to save only values ​​that are greater than 3 and less than 7, my desired result is:

 array([5, 6, 4, 6]) 

I see one way to do this:

 a = a[(a > 3) * (a < 7)] 

But something about this multiplication seems redundant, and I think I don't have a built-in method for something like that.

+4
source share
1 answer

Just for fun: I fixed it to reflect the use of the numpy array.

 import timeit import numpy as np a =np.array([1,3,5,6,4,6,7,8,9]) t1= timeit.Timer('a[(a > 3) * (a < 7)]', 'from __main__ import a' ) t2= timeit.Timer('a[(a > 3) & (a < 7)]','from __main__ import a') t3 =timeit.Timer('[e for e in a if e < 7 and e > 3]','from __main__ import a') print t1.timeit(1000)/1000 print t2.timeit(1000)/1000 print t3.timeit(1000)/1000 >>> 1.01280212402e-05 1.23770236969e-05 1.51431560516e-05 

Second time launch

 1.06210708618e-05 1.16641521454e-05 1.76239013672e-05 
+3
source

All Articles