numpy: how to get a max from an argmax result

后端 未结 3 1944
梦如初夏
梦如初夏 2020-12-07 03:12

I have a numpy array of arbitrary shape, e.g.:

a = array([[[ 1,  2],
            [ 3,  4],
            [ 8,  6]],

          [[ 7,  8],
           [ 9,  8],
         


        
3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-07 03:44

    You can use advanced indexing -

    In [17]: a
    Out[17]: 
    array([[[ 1,  2],
            [ 3,  4],
            [ 8,  6]],
    
           [[ 7,  8],
            [ 9,  8],
            [ 3, 12]]])
    
    In [18]: idx = a.argmax(axis=-1)
    
    In [19]: m,n = a.shape[:2]
    
    In [20]: a[np.arange(m)[:,None],np.arange(n),idx]
    Out[20]: 
    array([[ 2,  4,  8],
           [ 8,  9, 12]])
    

    For a generic ndarray case of any number of dimensions, as stated in the comments by @hpaulj, we could use np.ix_, like so -

    shp = np.array(a.shape)
    dim_idx = list(np.ix_(*[np.arange(i) for i in shp[:-1]]))
    dim_idx.append(idx)
    out = a[dim_idx]
    

提交回复
热议问题