Reputation: 450
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.
Upvotes: 4
Views: 5170
Reputation: 3722
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]]
Upvotes: 3
Reputation: 29732
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.]])
Upvotes: 5