Python:沿选定轴的3D数组中连续数字的最大长度

Python:沿选定轴的3D数组中连续数字的最大长度,python,arrays,numpy,Python,Arrays,Numpy,如果numpy中存在一个函数,该函数沿选定轴计算3d数组中连续数字的最大长度 我为1d数组创建了这样的函数(该函数的原型是max\u repeated\u number(array\u 1d,number)): 我想把它应用于轴=0的三维阵列 我对以下维度(a、B、C)的3d数组执行以下操作: 但由于循环的存在,计算时间很长。我知道人们需要避免python中的循环 如果存在一种没有循环的方法 谢谢 PS:这是最大重复数(1d数组,数字)的代码: 您可以使用以下方法适应任何ndarray情况: d

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

我为1d数组创建了这样的函数(该函数的原型是max\u repeated\u number(array\u 1d,number)):

我想把它应用于轴=0的三维阵列

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

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

如果存在一种没有循环的方法

谢谢

PS:这是最大重复数(1d数组,数字)的代码:

您可以使用以下方法适应任何
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)
例如:

a = np.array([[[[1,2,3,4],
                [1,3,5,4],
                [4,5,6,4]],
               [[1,2,4,4],
                [4,5,3,4],
                [4,4,6,4]]],

              [[[1,2,3,4],
                [1,3,5,4],
                [0,5,6,4]],
               [[1,2,4,4],
                [4,0,3,4],
                [4,4,0,4]]]])

print(max_consec_elem_ndarray(a, axis=2))
#[[[ 2.  1.  1.  3.]
#  [ 2.  1.  1.  3.]]
# 
# [[ 2.  1.  1.  3.]
#  [ 2.  1.  1.  3.]]]

你为什么不给我们看一下max_repeated_number的代码,我们也许可以向你展示如何扩展它(对于1d案例):还有@MrE,我刚刚添加了max_repeated_number的代码。@askewchan,谢谢!但是我需要3d阵列…我明白,但是你可以通过使用这些解决方案中的一种来提高你的速度。
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
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)
a = np.array([[[[1,2,3,4],
                [1,3,5,4],
                [4,5,6,4]],
               [[1,2,4,4],
                [4,5,3,4],
                [4,4,6,4]]],

              [[[1,2,3,4],
                [1,3,5,4],
                [0,5,6,4]],
               [[1,2,4,4],
                [4,0,3,4],
                [4,4,0,4]]]])

print(max_consec_elem_ndarray(a, axis=2))
#[[[ 2.  1.  1.  3.]
#  [ 2.  1.  1.  3.]]
# 
# [[ 2.  1.  1.  3.]
#  [ 2.  1.  1.  3.]]]