简体   繁体   中英

List of xy coordinates to matrix

I have a list of tuples containing x,y coordinate pairs. I wish to transform the list to a matrix, with xy coordinates representing indices of the matrix using numpy and without using a loop.

For any xy coordinate present in the list, have a 1 in the corresponding index position, and a 0 for any value not present in the list.

Original List:

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

Desired Output: Array of dimensions (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]
                ]

Similar to python - numpy create 2D mask from list of indices + then draw from masked array - Stack Overflow but not using scipy.

Use numpy.add.at and numpy.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.]])

This would work:

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)

Output:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM