If it exists in numpy a function which calculates a maximum length of consecutive numbers in 3d array along a chosen axis?
I created such function for 1d array (the function's prototype is 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
And I want to applicate it for 3d array along axis=0.
I do for a 3d array of following dimentions (A,B,C):
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 time of calculation is very long because of the loops. I know that one need to avoid the loops in python.
If it exists a way to do it without loops?
Thanks.
PS: Here is the code of 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