I have a numpy 2D matrix and each cell may containing an integer value. for example:
[[0, 1, 0, 2, 3],
[2, 0, 1, 1, 1]]
I want to make a list that containing each (x,y) of cell times it's value, for example I want below list for above matrix:
[(1,0) , (3,0) , (3,0) , (4,0) , (4,0) , (4,0) , (0,1) , (0,1) , (2,1) , (3,1) , (4,1)]
In other words, the value of [0,1]
is 1
so this x,y append in list "1" time.
I write this code. but it's really slow. How can I do this with an optimized method?
def page_to_std(data):
h, w = data.shape
res = []
for y in range(0, h):
for x in range(0, w):
amount = int(data[y][x])
for i in range(0, amount):
res.append((x,y))
return res
It seems as though you're getting both axes mixed there. Assuming that is so, you can generate the index tuples with np.ndindex
, and use np.repeat
to repeat the resulting array of tuples according to the flattened input array:
coo = np.fromiter(np.ndindex(a.shape), dtype='i,i')
np.repeat(coo, a.ravel()).tolist()
# [(0, 1), (0, 3), (0, 3), (0, 4), (0, 4), (0, 4), (1, 0), (1, 0), (1, 2), (1, 3), (1, 4)]
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.