jeudi 30 août 2018

Python: automating the generation of a variable number of if statements

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?

Aucun commentaire:

Enregistrer un commentaire