[英]Filling a 2D Numpy array based on given coordinates
I want to fill a 2D numpy array created by this:我想填充由此创建的二维 numpy 数组:
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
即使坐标从2,1:2,5
切换到2,5:2,1
或从5,1:8,1
切换到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.如果我想在2,1: 2,5
, 2,1 2,2 2,3 2,4 2,5
将被填充。 Also same as 5,1: 5,8
也与5,1: 5,8
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:这导致arr
看起来像:
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]])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.