Search code examples
pythonnumpyoptimizationsudoku

Optimized coordinates selection in 2D numpy array


I have a numpy array of coordinates. I want to select those between Xmin and Xmax and between Ymin and Ymax.

Here is my code :

grid = np.random.randint(2, size=81).reshape(9,9)
List_of_coordinates = np.argwhere(grid == 0)
Xmin, Xmax, Ymin, Ymax = 0,3,6,9
List_of_coordinates = List_of_coordinates[List_of_coordinates[:, 1] >= Ymin]
List_of_coordinates = List_of_coordinates[List_of_coordinates[:, 1] < Ymax]
List_of_coordinates = List_of_coordinates[List_of_coordinates[:, 0] >= Xmin]
List_of_coordinates = List_of_coordinates[List_of_coordinates[:, 0] < Xmax]

Is there a faster way ?


Solution

  • Slice first the grid, you'll get indices relative to the beginning of the slice, then add the start of the slice to come back to the absolute coordinates:

    List_of_coordinates = (np.argwhere(grid[Xmin:Xmax,Ymin:Ymax] == 0)
                           +np.array([Xmin,Ymin]))
    

    Example

    grid:

    array([[0, 1, 0, 0, 0, 0, 0, 1, 1],
           [1, 0, 1, 0, 1, 0, 1, 0, 0],
           [0, 1, 0, 1, 0, 1, 0, 0, 1],
           [1, 1, 1, 1, 1, 1, 1, 1, 1],
           [0, 1, 1, 1, 0, 0, 1, 0, 0],
           [1, 0, 0, 0, 0, 1, 1, 0, 0],
           [0, 0, 0, 0, 0, 1, 1, 0, 1],
           [1, 1, 0, 1, 1, 1, 1, 1, 0],
           [1, 0, 1, 0, 1, 0, 1, 0, 0]])
    

    slice:

    array([[0, 1, 1],
           [1, 0, 0],
           [0, 0, 1]])
    

    coordinates of 0s:

    array([[0, 6],
           [1, 7],
           [1, 8],
           [2, 6],
           [2, 7]])