I have an array of ints
mypos = np.array([10, 20, 30, 40, 50])
and a list of start & end positions, like this:
mydelims = [[5, 12],
[15,31],
[12,16],
[22,69]]
I'd like to loop through mydelims
and count how many positions are within each pair. Instinctively, I would write it like this:
for mypair in mydelims:
print(sum(mypos>mypair[0] & mypos<mypair[1]))
However, python doesn't seem to handle this. I know mypos>42
will return an array of booleans, but what is the most efficient way to apply multiple comparisons to one array of ints?
CodePudding user response:
You were pretty close and looking for np.logical_and
:
import numpy as np
mypos = np.array([10, 20, 30, 40, 50])
mydelims = [[5, 12],
[15, 31],
[12, 16],
[22, 69]]
result = {
tuple(mypair): sum(np.logical_and(mypos > mypair[0], mypos < mypair[1]))
for mypair in mydelims
}
print(result)
Output:
{(5, 12): 1, (15, 31): 2, (12, 16): 0, (22, 69): 3}
Note that you're treating the delims as non-inclusive - which I assumed was intentional. I.e. neither 5
nor 12
fall within [5, 12]
.