如果它存在于 numpy 中,该函数计算沿所选轴的 3d 数组中连续数字的最大长度?
我为一维数组创建了这样的函数(函数的原型是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
我想将它应用于沿轴 = 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