矩阵的xy坐标列表

时间:2019-03-15 05:45:39

标签: python arrays numpy

我有一个包含x,y坐标对的元组列表。我希望将列表转换为矩阵,其中xy坐标使用numpy而不使用循环来表示矩阵的索引。

对于列表中存在的任何xy坐标,在对应的索引位置中使用1,对于列表中不存在的任何值使用0。

原始列表:

a = [(0,0),(0,2),(0,3),(0,4),
    (1,1),(1,2),(1,4),(2,2),
    (3,2),(3,4), (4,4)]
a

所需的输出:尺寸为(5,5)的数组

[
 [1, 1, 0, 1, 1],
 [1, 0, 0, 0, 0],
 [1, 1, 1, 1, 0],
 [0, 1, 0, 0, 0],
 [1, 0, 0, 0, 0]
                ]

类似于python - numpy create 2D mask from list of indices + then draw from masked array - Stack Overflow,但不使用scipy。

2 个答案:

答案 0 :(得分:3)

使用numpy.add.atnumpy.rot90

import numpy as np

res = np.zeros((5,5))
np.add.at(res, tuple(zip(*a)), 1)
np.rot90(res)
array([[1., 1., 0., 1., 1.],
       [1., 0., 0., 0., 0.],
       [1., 1., 1., 1., 0.],
       [0., 1., 0., 0., 0.],
       [1., 0., 0., 0., 0.]])

答案 1 :(得分:1)

这将起作用:

import numpy as np

a = [(0,0),(0,2),(0,3),(0,4),     # The list we start with
    (1,1),(1,2),(1,4),(2,2),
    (3,2),(3,4), (4,4)]

ar = np.array(a)                  # Convert list to numpy array
res = np.zeros((5,5), dtype=int)  # Create, the result array; initialize with 0
res[ar[:,0], ar[:,1]] = 1         # Use ar as a source of indices, to assign 1
print (res)

输出:

[[1 0 1 1 1]
 [0 1 1 0 1]
 [0 0 1 0 0]
 [0 0 1 0 1]
 [0 0 0 0 1]]
相关问题