I'm not entirely sure what you're trying to do, but the easiest way to do conditions in numpy
is to just apply them to the whole array to get a mask:
mask = (z >= 0.3) & (z < 0.6)
Then you can use, e.g., extract
or ma
if necessary—but in this case, I think you can just rely on the fact that True==1
and False==0
and do this:
zm = z * mask
After all, if all you're doing is summing things up, 0
is the same as not there, and you can just replace len
with count_nonzero
.
For example:
In [588]: z=np.random.rand(10)
In [589]: z
Out[589]:
array([ 0.33335522, 0.66155206, 0.60602815, 0.05755882, 0.03596728,
0.85610536, 0.06657973, 0.43287193, 0.22596789, 0.62220608])
In [590]: mask = (z >= 0.3) & (z < 0.6)
In [591]: mask
Out[591]: array([ True, False, False, False, False, False, False, True, False, False], dtype=bool)
In [592]: z * mask
Out[592]:
array([ 0.33335522, 0. , 0. , 0. , 0. ,
0. , 0. , 0.43287193, 0. , 0. ])
In [593]: np.count_nonzero(z * mask)
Out[593]: 2
In [594]: np.extract(mask, z)
Out[594]: array([ 0.33335522, 0.43287193])
In [595]: len(np.extract(mask, z))
Out[595]: 2