Home > Software design >  Find x, y coordinates in two np arrays containing X and Y
Find x, y coordinates in two np arrays containing X and Y

Time:11-02

I can't seem to find an efficient way to do this. The question is this: If I do coords = np.where(A==0), where A is a numpy 2d array, I get a tuple of two np arrays, an array containing the x coordinates (of the points that satisfy the condition) and an array of y coordinates, e.g., (array([0, 0, 0, 0, 1, 1, 2, 2, 2, 2, 3, 3, 3]), array([0, 1, 2, 3, 0, 1, 0, 1, 2, 3, 0, 1, 3])). How do I know if a given point, say (0,0) exists in this tuple (without having to change the tuple into another structure)?

CodePudding user response:

Don't use np.where if you don't want the two arrays of indexes. A==0 will return a boolean array, which may be exactly what you want, if you need to check specific indexes to see if the check is true or not.

mask = A==0
if mask[x,y]: # where x and y are set somewhere above...
   # do stuff

Of course, if the stuff you're doing is numpy related, checking one index at a time is likely to be less efficient than some kind of broader check that lets you do a broadcast operation. For instance, you could change all the 0 values in the array to 1 with this code:

A[mask] = 1

Or this, which does the equivalent of abs (it would be more efficient to save the mask as a separate variable, but I'm not doing that in this example to show how it's not strictly necessary):

A[A < 0] = -A[A < 0]

CodePudding user response:

You can use argwhere instead of where even if it is not optimal (read the answer of @Blccknght)

>>> (np.argwhere(A == 0) == [0, 0]).all(1).any()
True
  • Related