python-3.xlistnumpy-ndarray

List of points [ (x,y), …] to np.array()


I have a list of points such as [(x, y), …]
I want to convert it in a numpy.array() such as [[0,0,1,…], …], 1 representing a point of the list.
According that np.array().shape is : ( max(x)-min(x)+1, max(y)-min(y)+1 )

I can easily find the shape and so create a zeros array.
But how to fill it with the points of the list without iterate in a loop ?
Is there a better method/way to do that ?

Thanks

Edit: Example and corrected an error on the shape above
Get the zeros array :

l = [(0, 5), (1, 6), (2, 7)]
l = np.array(l)
l_zeros = np.zeros(l.max(0) - l.min(0) + 1)

Now, I expected a canonical filled np.array() such as :

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

Solution

  • You can achieve this efficiently using NumPy’s advanced indexing without any loops.

    import numpy as np
    
    # Your list of points
    points = np.array([(0, 5), (1, 6), (2, 7)])
    
    # Shift the coordinates to start from (0, 0)
    offset = points.min(axis=0)
    shifted = points - offset
    
    # Define shape: (max_x - min_x + 1, max_y - min_y + 1)
    shape = points.max(axis=0) - points.min(axis=0) + 1
    arr = np.zeros(shape, dtype=int)
    
    # Fill 1s at the shifted positions
    arr[shifted[:, 0], shifted[:, 1]] = 1
    
    print(arr)