I have two numpy arrays similar to these, which represent coordinates:
import numpy as np
x=np.array([1,3,2,4,6,5,4,1])
y=np.array([4,4,3,2,2,1,3,5])
I also have n
squares:
s1 -> x=0 to 3, y=0 to 3
s2 -> x=3 to 6, y=3 to 6
s3 -> ...
s4 -> ...
and I want to count the number of points falling within each square. This comes down to evaluating n
inequalities.
My approach is verbose and (probably) inefficient:
count1=0
count2=0
count3=0
count4=0
for j in range(0, len(x)):
#Square 1
if x[j]<=3 and y[j]<=3:
count1+=1
#Square 2
if x[j]<=3 and y[j]>3 and y[j]<=6:
count2+=1
#Square 3
if x[j]>3 and x[j]<=6 and y[j]<=3:
count3+=1
#Square 4
if x[j]>3 and x[j]<=6 and y[j]>3 and y[j]<=6:
count4+=1
Given my two arrays, this returns:
In[1]: count1, count2, count3, count4
Out[1]: (1, 3, 4, 0)
My real problems consists of a variable number of squares (it could be 6, it could be 36, etc.).
Is there a way I can automate both the generation of the count
variables, as well as the number and boundaries of the if
statements?
You don't list your whole code, so, it's not clear what exactly you are trying to do. In any case, you could describe each square by a tuple of tuples
square_n = ((x1, x2), (y1, y2))
and put them in a dictionary, where the key this tuple, and the value is the count. Then, something like
for square in squares_dict:
(x1, x2), (y1, y2) = square
if x1<a<x2 and y1<b<y2: # whatever criterion you have
squares_dict[square] += 1