Python: maximum length of consecutive numbers in a three-dimensional array along a selected axis

If there is a function in numpy that calculates the maximum length of consecutive numbers in a 3d array along the selected axis?

I created such a function for array 1d (prototype of max_repeated_number (array_1d, number) function ):

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

And I want to apply it for a 3d array along axis = 0.

I make the following values ​​(A, B, C) for a three-dimensional array:

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)

But the computation time is very long due to cycles. I know that you need to avoid loops in python.

If there is a way to do this without loops?

Thanks.

PS: Here is the code 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
+4
source share
2 answers

, 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.]]]
+2

Finnaly, C ( ), Python. !

0

All Articles