Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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:

  1. 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

  2. then slice the Y array (just one array) in the index range [lowest_index, highest_index]

  3. count the number of elements in my slice, having Yi's that are greater thanlower_limit_Yand less thanupper_limit_Y`.

share|improve this question
    
When you say "For each Xi", do you mean there are multiple rows of Y, or do you mean "for each unique value of Xi"? –  NPE Dec 6 '12 at 10:43
    
Not sure to undersand... Is there an Yi array for each Xi ? EDIT: okay, same kind of question than NPE actually –  Remy F Dec 6 '12 at 10:44

2 Answers 2

up vote 0 down vote accepted

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
share|improve this answer

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.