基于给定坐标填充二维Numpy数组

2024-04-20 08:03:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我要填充由以下内容创建的二维numpy数组:

import numpy as np

arr = np.full((10,10),0)

坐标示例:

enter image description here

即使坐标从2,1:2,5切换到2,5:2,1或从5,1:8,1切换到8,1:5,1,如何用数据填充这些选定的元素

如果我想填充2,1 : 2,5上的数据,2,1 2,2 2,3 2,4 2,5将被填充。与5,1 : 5,8相同


Tags: 数据importnumpy元素示例asnp数组
1条回答
网友
1楼 · 发布于 2024-04-20 08:03:45

有一种方法:

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

结果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]])

相关问题 更多 >