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

标签 python arrays numpy

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

我为一维数组创建了这样的函数(函数的原型(prototype)是ma​​x_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

我想将它应用于沿 axis=0 的 3d 数组。

我为以下维度 (A、B、C) 的 3d 阵列做的:

result_array = numpy.array([])
for i in range(B):    
     for j in range(C):
          result_array[i,j] = max_repeated_number(my_3d_array[:,i,j],1)

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

是否存在一种无需循环的方法?

谢谢。

PS:这里是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

最佳答案

你可以适应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)

例子:

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.]]]

关于Python:沿选定轴的 3D 数组中连续数字的最大长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19789854/

相关文章:

arrays - ^ 运算符在 Visual C++ 中的使用

javascript - 当我在分派(dispatch)后更新 vue 组件中的状态时,防止状态更新

python - 如何将n维数组(Python Numpy)导出到文本文件中?

c++ - 字符数组是唯一具有某种形式的空终止的类型吗?

python - 将列表的一维对象 numpy 数组转换为二维数值数组并返回

Python:如何先读取一个元素,然后读取两个元素?

python - 如何省略 "connect: network is unreachable"消息

python - Keras提示错误: (Error when checking input: expected conv2d_4_input to have 4 dimensions)

python - boolean 问题。和、或、和或、或不

python - Django在数据库中查询多个关键字