Reputation: 1790
I have a 2D array in the following form:
[[X1, X2, ..., XN]
[Y1, Y2, ..., YN]]
For each Xi
greater than lower_limit_X
and less than upper_limit_X
, I would like to get the number of Yi
's that are greater than lower_limit_Y
and less than upper_limit_Y
.
I hope there is an efficient way of doing this in Numpy apart from indexing one by one.
EDIT: So I have a 2xN array. The first row has ordered values of N X's and second row has ordered values of N Y's. What I would like to get is:
get a the lowest_index
and highest_index
index of X, that have a value that is greater than lower_limit_X
and less than upper_limit_X
then slice the Y array (just one array) in the index range [lowest_index
, highest_index
]
count the number of elements in my slice, having Yi's that are greater than
lower_limit_Yand less than
upper_limit_Y`.
Upvotes: 1
Views: 3148
Reputation: 25833
Here are two ways you could do this, the more strait forward way is probably,
mask = ((lower_x_limit < array[0]) & (array[0] < upper_x_limit) &
(lower_y_limit < array[1]) & (array[1] < upper_y_limit))
count = sum(mask)
If your array is very large and both x and y are sorted you could use searchsorted
instead,
start = array[0].searchsorted(lower_x_limit, 'right')
end = array[0].searchsorted(upper_x_limit, 'left')
temp = array[1, start:end]
start = temp.searchsorted(lower_y_limit, 'right')
end = temp.searchsorted(upper_y_limit, 'left')
count = end - start
Upvotes: 0
Reputation: 187
Try numpy.logical_and.
numpy.logical_and(array1 > lower_x_limt, array1 < upper_x_limit)
this will do elementwise comparison and return a boolean list at indices which have your values.
Upvotes: 1