Home > Software engineering >  Finding the locations of specific coordinates from an array of coordinates
Finding the locations of specific coordinates from an array of coordinates

Time:08-05

I have an array of coordinates as shown below:

import numpy as np
values_to_test = np.array([[1 , 0],[2 , 0],[2 , 0.5],[1 , 0.5],[0 , 0],[2 , 1], [0 , 0.5],[1 , 1],[0 , 1]])

As my ultimate goal, I need to choose the positions from the values_to_test that contain the specific coordinates of the following array:

specific_values=np.array([[1,0],[0,0],[1,1]])

Hence, I'm expecting a result like: [True,False,False,False,True,False,False,True,False]

I know if this was a 1D array I could use np.where but I cannot think about a way to handle this problem.
Appreciate your help

CodePudding user response:

You could make use of numpy.all and numpy.any like so:

>>> (values_to_test[:, None] == specific_values).all(axis=-1).any(axis=-1)
array([ True, False, False, False,  True, False, False,  True, False])

CodePudding user response:

This answer is a combination of using np.where, np.prod and list comprehension:

values_to_test = np.array([[1 , 0],[2 , 0],[2 , 0.5],
                           [1 , 0.5],[0 , 0],[2 , 1], 
                           [0 , 0.5],[1 , 1],[0 , 1]])
specific_values=np.array([[1,0],[0,0],[1,1]])

output = [np.where(np.prod(values_to_test == x, axis = -1)) for x in specific_values]

Output:

[(array([0], dtype=int64),),
 (array([4], dtype=int64),),
 (array([7], dtype=int64),)]

You can clean it up too with:

output = [np.where(np.prod(values_to_test == x, axis = -1))[0][0] for x in specific_values]

[0, 4, 7] #output

CodePudding user response:

import numpy as np
values_to_test = np.array([[1, 0], [2, 0], [2, 0.5], [1, 0.5], [
                          0, 0], [2, 1], [0, 0.5], [1, 1], [0, 1]])
specific_values = np.array([[1, 0], [0, 0], [1, 1]])

_1_j = np.array([[1], [1j]])

print([x in specific_values@_1_j for x in values_to_test@_1_j])
>>>[True, False, False, False, True, False, False, True, False]
  • Related