[英]Repeat 2D array index tuples according to value in index
I have a numpy 2D matrix and each cell may containing an integer value.我有一个 numpy 二维矩阵,每个单元格可能包含一个 integer 值。 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:我想制作一个包含每个 (x,y) 单元格乘以它的值的列表,例如,我想要上面矩阵的下面列表:
[(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.换句话说,
[0,1]
的值是1
,所以这个 x,y append 在列表“1”时间。
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:假设是这样,您可以使用
np.ndindex
生成索引元组,并使用np.repeat
根据展平的输入数组重复生成的元组数组:
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)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.