Reputation: 139
I want to fill a 2D numpy array created by this:
import numpy as np
arr = np.full((10,10),0)
Example coordinates:
How can I fill those selected elements with data even if the coordinates is switched from 2,1:2,5
to 2,5:2,1
or from 5,1:8,1
to 8,1:5,1
If I want to fill data on 2,1 : 2,5
,2,1 2,2 2,3 2,4 2,5
will be filled. Also same as 5,1 : 5,8
Upvotes: 3
Views: 1403
Reputation: 8122
Here's one way of doing it:
import numpy as np
coords = ['2,1:2,5', '8,6:4,6', '5,1:8,1']
arr = np.full((10, 10), 0)
for coord in coords:
start, stop = map(lambda x: x.split(','), coord.split(':'))
(x0, y0), (x1, y1) = sorted([start, stop])
arr[int(y0):int(y1)+1, int(x0):int(x1)+1] = 1
Which results in arr
looking like:
array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 1, 1, 1, 1, 0],
[0, 0, 1, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 1, 1, 1, 1, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]])
Upvotes: 1