Skip to content
Advertisement

seperate array from large array in numpy by column condition

check if values of a,b are 1 ,2 and c,d are 3,4 then print it

JavaScript

what i am currently doing is

JavaScript

but it prints all the rows where the 1st column is 1

Advertisement

Answer

You can slice your array and then use row equality checks:

JavaScript

BTW, it is always a good idea to make an example that can be reproduced by simple copy/paste. It took me more time to adapt your example than to figure out the answer (each sub-minute, so we are good).

Reproducible setup

JavaScript

Explanation

Slice/index the array to retain just the columns you want to check against:

JavaScript

Note that, in your case, the four columns are consecutive. What if they weren’t? Say we want to check that (d,a,c,b) == (4,1,3,2)? In that case, specify the selection as a tuple on the second dimension:

JavaScript

Comparison of the rows of the selected columns to your desired target, by using broadcasting of the == operator:

JavaScript

But we want all values (on each row) to match, so:

JavaScript

From that point, you can just select a[mask] and get your subset array where all the selected columns match your desired target.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement