Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

extracting specific rows of Nx3 array whereby each column satisfies condition

Suppose I have an array which is Nx3, and I want elements which satisfy say:

4 < col1 < 13, 5 > col2 >  3, 10 > col3 > 6

i.e. apply this to:

1,2,3
4,5,6
9,4,7

Then it will provide a Mx3 array which contains only the rows which satisfy all three conditions. For the above example, it outputs

9,4,7

I thought of doing a loop but I figured numpy or something similar must have something which is much faster (e.g. np.where?)

like image 824
Griff Avatar asked Oct 22 '22 07:10

Griff


1 Answers

You build a boolean array for each column:

cond1 = (my_array[:, 0] > 4) & (my_array[:, 0] < 13)
cond2 = (my_array[:, 1] > 3) & (my_array[:, 1] < 5)
cond3 = (my_array[:, 2] > 6) & (my_array[:, 2] < 10)

You then and your three conditions together:

cond = cond1 & cond2 & cond3

And you finally use that to select the rows from your array:

out = my_array[cond]
like image 130
Jaime Avatar answered Oct 27 '22 11:10

Jaime