在numpy 3d数组中查找最常见的值(排除-1),其中另一个数组中对应的值为1



我有两个数组,array_a和array_b,形状都是(2,3,4(。

我想做的是在array_b中轴=2处获得最常见的值,其中array_a中对应的值为1。

这是我的密码。有什么方法可以更快地做到这一点吗?谢谢

array_a = np.array([[[-1,-1,-1,1], [-1,-1,-1,1], [-1,1,1,1]], [[-1,-1,1,1], [-1,1,1,1], [-1,1,1,1]]])
array_b = np.array([[[1,2,2,4], [0,0,1,3], [1,1,1,8]], [[0,1,0,3], [3,3,8,8], [3,3,0,1]]])
array_b[array_a!=1] = -1 
# Only want to use the values in array_b where the corrsponding value in array_a is 1 
result = []
for row in np.ndindex(array_b.shape[:2]):
count = Counter(array_b[row])
del count[-1]
result = np.append(result , count.most_common(1)[0][0])

如果我没有误解轴=2的条件;如果OP使用更大维度的数组,那么删除for循环并使用NumPy本机选择将提高性能。

select = array_b[array_a == 1] # pick all the values in array_b, 
# where the corresponding element in 
# array_a equals 1
val, cnt = np.unique(select, return_counts=True) # get the frequencies of 
# values
print( val[np.argmax(cnt)] )  # print the most frequent element.

相关内容

最新更新