Python:在不使用 groupby 的情况下在 3D numpy 数组中查找连续值?

Python: find consecutive values in 3D numpy array without using groupby?

假设您有以下 3D numpy 数组:

matrices=
numpy.array([[[1, 0, 0], #Level 0
              [1, 1, 1],
              [0, 1, 1]],

             [[0, 1, 0], #Level 1
              [1, 1, 0],
              [0, 0, 0]],

             [[0, 0, 1], #Level 2
              [0, 1, 1],
              [1, 0, 1]]])

并且您想计算每个单元格的连续值为 1 的次数。假设您要计算每个单元格的 2 个和 3 个连续值 1 出现的次数。结果应该是这样的:

two_cons=([[0,0,0],
           [1,1,0],
           [0,0,0]])
three_cons=([[0,0,0],
             [0,1,0],
             [0,0,0]])

表示两个单元格至少有 2 个连续值为 1,只有一个单元格有 3 个连续值。

我知道这可以通过使用 groupby 来完成,为每个单元格提取 "vertical" 系列值,并计算您获得 n 个连续值的次数:

import numpy
two_cons=numpy.zeros((3,3))
for i in range(0,matrices.shape[0]): #Iterate through each "level"
    for j in range(0,matrices.shape[1]):
        vertical=matrices[:,i,j] #Extract the series of 0-1 for each cell of the matrix
        #Determine the occurrence of 2 consecutive values
        cons=numpy.concatenate([numpy.cumsum(c) if c[0] == 1 else c for c in numpy.split(vertical, 1 + numpy.where(numpy.diff(vertical))[0])])
        two_cons[i][j]=numpy.count_nonzero(cons==2)

在这个例子中,你得到:

two_cons=
array([[ 0.,  0.,  0.],
       [ 1.,  1.,  0.],
       [ 0.,  0.,  0.]])

我的问题:如果我无法访问 vertical,我该怎么办? 在我的实际情况下,3D numpy 数组太对我来说跨多个级别提取垂直系列很大,所以我必须一次遍历每个级别,并记住之前 n 级别发生的事情。你有什么建议?

我还没有检查过代码,但是这样的事情应该可以工作...我的想法是沿三维扫描矩阵并有 2 个辅助矩阵,一个跟踪实际序列的长度一个,一个跟踪迄今为止遇到的最佳序列。

bests = np.zeros(matrices.shape[:-1])
counter = np.zeros(matrices.shape[:-1])

for depth in range(matrices.shape[0]):
    this_level = matrices[depth, :, :]
    counter = counter * this_level + this_level
    bests = (np.stack([bests, counter], axis=0)).max(axis=0)

two_con = bests > 1
three_con = bests > 2