【Python】取Numpy多维数组中最大的几个值的索引

  • 先来看看二维数组
    a = np.array([[1, 7, 5],
                  [8, 2, 13]])
    
    假设我们要获取最大的两个值的位置索引
    • 我们先将二维数组展成一维数组,获取到排序后的索引下标,即
      index = np.argsort(a.ravel())[:-3:-1]
      
      得到 index 值为 [5 3]
      
    • 接下来将在一维得到的索引,映射到高维,得到在高维数组中的位置索引
      pos = np.unravel_index(index, a.shape)
      
      得到 pos 值为 (array([1, 1], dtype=int64), array([2, 0], dtype=int64))
      
    • 将 pos 按列合并
      np.column_stack(pos)
      
      结果:[[1 2]
      		[1 0]]
      
    • 索引 [1 2] 对应的就是最大值13[1 0] 对应的值就是第二大值 8
  • 试试三维的,三维(多维)和二维步骤一致
    a = np.array([
            [[1, 7, 5],
             [8, 2, 13]],
            [[25, 0, 3],
             [50, 14, 28]]
        ])
    
    index = np.argsort(a.ravel())[:-3:-1]
    pos = np.unravel_index(index, a.shape)
    print(a.ravel())
    print(index)
    print(pos)
    print(np.column_stack(pos))
    
    a.ravel(): [ 1  7  5  8  2 13 25  0  3 50 14 28]
    
    index: [ 9 11]
    
    pos: (array([1, 1], dtype=int64), array([1, 1], dtype=int64), array([0, 2], dtype=int64))
    
    np.column_stack(pos): [[1 1 0]
     						[1 1 2]]
    

猜你喜欢

转载自blog.csdn.net/weixin_42166222/article/details/119894269