简体   繁体   English

使用另一个数组在 Numpy ndarray 中选择某些索引

[英]selecting certain indices in Numpy ndarray using another array

I'm trying to mark the value and indices of max values in a 3D array, getting the max in the third axis.我试图在 3D 数组中标记最大值的值和索引,在第三个轴上获得最大值。 Now this would have been obvious in a lower dimension:现在这在较低的维度上会很明显:

argmaxes=np.argmax(array)
maximums=array[argmaxes]

but NumPy doesn't understand the second syntax properly for higher than 1D.但是 NumPy 不能正确理解高于 1D 的第二种语法。 Let's say my 3D array has shape (8,8,250).假设我的 3D 阵列具有形状 (8,8,250)。 argmaxes=np.argmax(array,axis=-1) would return a (8,8) array with numbers between 0 to 250. Now my expected output is an (8,8) array containing the maximum number in the 3rd dimension. argmaxes=np.argmax(array,axis=-1)将返回一个 (8,8) 数组,其数字在 0 到 250 之间。现在我的预期输出是一个 (8,8) 数组,其中包含第三维的最大数字。 I can achieve this with maxes=np.max(array,axis=-1) but that's repeating the same calculation twice (because I need both values and indices for later calculations) I can also just do a crude nested loop:我可以用maxes=np.max(array,axis=-1)来实现这一点,但这是重复两次相同的计算(因为我需要值和索引供以后计算)我也可以做一个粗略的嵌套循环:

for i in range(8):
   for j in range(8):
      maxes[i,j]=array[i,j,argmaxes[i,j]]

But is there a nicer way to do this?但是有没有更好的方法来做到这一点?

You can use advanced indexing.您可以使用高级索引。 This is a simpler case when shape is (8,8,3) :当形状为(8,8,3)时,这是一个更简单的情况:

arr = np.random.randint(99, size=(8,8,3))
x, y = np.indices(arr.shape[:-1])
arr[x, y, np.argmax(array,axis=-1)]

Sample run:示例运行:

>>> x
array([[0, 0, 0, 0, 0, 0, 0, 0],
       [1, 1, 1, 1, 1, 1, 1, 1],
       [2, 2, 2, 2, 2, 2, 2, 2],
       [3, 3, 3, 3, 3, 3, 3, 3],
       [4, 4, 4, 4, 4, 4, 4, 4],
       [5, 5, 5, 5, 5, 5, 5, 5],
       [6, 6, 6, 6, 6, 6, 6, 6],
       [7, 7, 7, 7, 7, 7, 7, 7]])
>>> y
array([[0, 1, 2, 3, 4, 5, 6, 7],
       [0, 1, 2, 3, 4, 5, 6, 7],
       [0, 1, 2, 3, 4, 5, 6, 7],
       [0, 1, 2, 3, 4, 5, 6, 7],
       [0, 1, 2, 3, 4, 5, 6, 7],
       [0, 1, 2, 3, 4, 5, 6, 7],
       [0, 1, 2, 3, 4, 5, 6, 7],
       [0, 1, 2, 3, 4, 5, 6, 7]])    
>>> np.argmax(arr,axis=-1)    
array([[2, 1, 1, 2, 0, 0, 0, 1],
       [2, 2, 2, 1, 0, 0, 1, 0],
       [1, 2, 0, 1, 1, 1, 2, 0],
       [1, 0, 0, 0, 2, 1, 1, 0],
       [2, 0, 1, 2, 2, 2, 1, 0],
       [2, 2, 0, 1, 1, 0, 2, 2],
       [1, 1, 0, 1, 1, 2, 1, 0],
       [2, 1, 1, 1, 0, 0, 2, 1]], dtype=int64)

This is a visual example of array to help to understand it better:这是一个数组的可视化示例,以帮助更好地理解它:

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM