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