python - 根据给定坐标填充 2D Numpy 数组

标签 python arrays numpy

我想填充由此创建的 2D 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,18,1:5,1

如果我想在 2,1 : 2,5 上填充数据,2,1 2,2 2,3 2,4 2,5 将被填充.也与 5,1 : 5,8

相同

最佳答案

这是一种实现方式:

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

关于python - 根据给定坐标填充 2D Numpy 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58569157/

相关文章:

python - 如何为网络 python 包安装注册入口点?

python - flask 中的浏览器缓存问题

python - 用python检测时间序列异常

javascript - jQuery/JavaScript : use PHP return value as javaScript array

c++ - 结构和函数(通过引用传递)

java - 创建一个二维数组并将每个元素初始化为 i * j 的值,其中 i 和 j 是 2 个索引(例如,元素 [5][3] 为 5 * 3 = 15)

python - 使用 Tensorflow 的 top_k 和 scatter_nd

python - 使用 ND 数组选择维度

python - 如何检测列表中的上升和下降趋势

python - 在 numpy 中创建方阵的 3D 数组