Skip to main content
 首页 » 编程设计

python之比较n维numpy数组中的值

2024年10月01日6hnrainll

需要比较一个numpy数组中的每一个值,最大的返回1,其他的返回0。我在使用不同数量的 [] 时遇到问题。

输入示例:

[[[0.6673975 0.33333233]] 
. 
. 
. 
[[0.33260247 0.6673975]]] 

预期输出:

[[[1 0]] 
. 
. 
. 
[[0 1]]] 

请您参考如下方法:

最大过轴:

如果按照 Joe 在评论中的建议,您正在寻找沿轴的最大值,那么对于轴 axis,

np.moveaxis((np.moveaxis(ar, axis, 0) == ar.max(axis)).astype(int), 0, axis) 

或者,快一点,

(ar == np.broadcast_to(np.expand_dims(ar.max(axis), axis), ar.shape)).astype(int) 

应该涵盖 n 维情况。

例如:

ar = np.random.randint(0, 100, (2, 3, 4)) 
 
ar 
Out[157]:  
array([[[17, 28, 22, 31], 
        [99, 51, 65, 65], 
        [46, 24, 93,  4]], 
 
       [[ 5, 84, 85, 79], 
        [ 7, 80, 27, 25], 
        [46, 80, 90,  3]]]) 
 
(ar == np.broadcast_to(np.expand_dims(ar.max(-1), -1), ar.shape)).astype(int) 
Out[159]:  
array([[[0, 0, 0, 1], 
        [1, 0, 0, 0], 
        [0, 0, 1, 0]], 
 
       [[0, 0, 1, 0], 
        [0, 1, 0, 0], 
        [0, 0, 1, 0]]]) 
ar.max(-1) 
Out[160]:  
array([[31, 99, 93], 
       [85, 80, 90]]) 

全数组的最大值:

如果您尝试识别等于整个数组中最大值的元素,

(ar == ar.max()).astype(int) 

应该给你正在寻找的东西。