【问题标题】:Python: Maximum length of consecutive numbers in 3D array along a chosen axisPython:沿选定轴的 3D 数组中连续数字的最大长度
【发布时间】:2013-11-16 09:04:23
【问题描述】:

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

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

我想将它应用于沿轴 = 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

【问题讨论】:

标签: python arrays numpy


【解决方案1】:

您可以将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.]]]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-21
    • 2019-04-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多