2D numpy数组的加速迭代

时间:2018-01-31 13:20:11

标签: python arrays numpy

我有一个非常大的numpy 2D数组M,我需要获得所有可能的子矩阵,这些子矩阵都遵循限制,对于数组的每个元素并将它们放在字典中。

我尝试使用ndenumerate并使用双for循环,但它们都非常慢,有可能改进吗?

感谢。

版本1

poss = {}
for index, val in numpy.ndenumerate(M):
    poss[index] = [ z for z in filter(lambda t: 2*L <= sub_matrix_dim(index, t) <= H, zip(*numpy.where(M != val))) ]

第2版

poss = {}
for x in range(R):
    for y in range(C):
        poss[(x,y)] = [ z for z in filter(lambda t: 2*L <= sub_matrix_dim((x,y), t) <= H, zip(*numpy.where(M != M[x][y]))) ]

被调用的函数是:

def sub_matrix_dim(c1: tuple, c2: tuple): return numpy.empty((abs(c2[1] - c1[1]) + 1, abs(c2[0] - c1[0]) + 1), dtype=int).size

修改 例如,从这个2d数组:

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

L = 1H = 6 poss{}我将拥有:

{
 (0, 0): [(1, 1), (1, 2)],
 (0, 1): [(1, 1), (1, 2), (1, 3)],
 (0, 2): [(1, 1), (1, 2), (1, 3)],
 ...
 (1, 1): [(0, 0), (0, 1), (0, 2), (0, 3), (1, 0), (1, 4), (2, 0), (2, 1), (2, 2), (2, 3)],
 ...
 (2, 1): [(1, 1), (1, 2), (1, 3)], 
 (2, 2): [(1, 1), (1, 2), (1, 3)], 
 (2, 3): [(1, 1), (1, 2), (1, 3)], 
 (2, 4): [(1, 2), (1, 3)]
}

1 个答案:

答案 0 :(得分:0)

我可能会在这里走向完全错误的方向,但是不会做这项工作吗?

def sub_matrix_dim(c1: tuple, c2: tuple): return (abs(c2[1] - c1[1]) + 1)) * (abs(c2[0] - c1[0]) + 1)