Python:三维数组中沿选定轴的最大连续数长度

2024-04-26 01:12:08 发布

您现在位置:Python中文网/ 问答频道 /正文

如果在numpy中存在一个函数,该函数计算沿所选轴的3d数组中连续数的最大长度?在

我为1d数组创建了这样的函数(函数的原型是max_repeated_number(array_1d,number)):

>>> import numpy
>>> a = numpy.array([0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0])
>>> b = max_repeated_number(a, 1)
>>> b
4

我想把它应用到三维阵列中。在

我对以下尺寸(a、B、C)的3d数组执行此操作:

^{pr2}$

但由于循环的存在,计算时间很长。我知道需要避免python中的循环。在

如果它有一种不需要循环的方法吗?在

谢谢。在

注:这里是max_repeated_number(1d_array,number)的代码:

def max_repeated_number(array_1d,number):
    previous=-1
    nb_max=0
    nb=0
    for i in range(len(array_1d)):
        if array_1d[i]==number:
            if array_1d[i]!=previous:
                nb=1
            else:
                nb+=1
        else:
            nb=0

        if nb>nb_max:
            nb_max=nb

        previous=array_1d[i]
    return nb_max

Tags: 函数importnumpynumberif尺寸数组array
2条回答

您可以将the solution explained here改编为任何ndarray案例,方法如下:

def max_consec_elem_ndarray(a, axis=-1):
    def f(a):
        return max(sum(1 for i in g) for k,g in groupby(a))
    new_shape = list(a.shape)
    new_shape.pop(axis)
    a = a.swapaxes(axis, -1).reshape(-1, a.shape[axis])
    ans = np.zeros(np.prod(a.shape[:-1]))
    for i, v in enumerate(a):
        ans[i] = f(v)
    return ans.reshape(new_shape)

示例:

^{pr2}$

最后,我用C语言创建了一个函数(带循环),然后从Python调用它。它工作得很快!在

相关问题 更多 >