numpy: how to get a max from an argmax result

后端 未结 3 1942
梦如初夏
梦如初夏 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条回答
  •  感动是毒
    2020-12-07 03:52

    For arbitrary-shape arrays, the following should work :)

    a = np.arange(5 * 4 * 3).reshape((5,4,3))
    
    # for last axis
    argmax = a.argmax(axis=-1)
    a[tuple(np.indices(a.shape[:-1])) + (argmax,)]
    
    # for other axis (eg. axis=1)
    argmax = a.argmax(axis=1)
    idx = list(np.indices(a.shape[:1]+a.shape[2:]))
    idx[1:1] = [argmax]
    a[tuple(idx)]
    

    or

    a = np.arange(5 * 4 * 3).reshape((5,4,3))
    
    argmax = a.argmax(axis=0)
    np.choose(argmax, np.moveaxis(a, 0, 0))
    
    argmax = a.argmax(axis=1)
    np.choose(argmax, np.moveaxis(a, 1, 0))
    
    argmax = a.argmax(axis=2)
    np.choose(argmax, np.moveaxis(a, 2, 0))
    
    argmax = a.argmax(axis=-1)
    np.choose(argmax, np.moveaxis(a, -1, 0))
    

提交回复
热议问题