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]
])
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)
points.min(axis=0) and points.max(axis=0) get the min/max for both x and y.
Subtracting the min from all coordinates gives you 0-based indexing for the new array.
The shape is calculated as max - min + 1 for each axis.
You can then directly assign 1 to the desired positions using NumPy’s advanced indexing.