[Numpy-discussion] Array min from argmin along an axis?

Ken Basye kbasye1 at jhu.edu
Tue Dec 13 17:11:54 EST 2011


Hi folks,
     I need an efficient way to get both the min and argmin of a 2-d 
array along one axis.  It seemed to me that the way to do this was to 
get the argmin and then use it to index into the array to get the min, 
but I can't figure out how to do it.  Here's my toy example:

 >>> x = np.arange(25).reshape((5,5))
 >>> x
array([[ 0,  1,  2,  3,  4],
        [ 5,  6,  7,  8,  9],
        [10, 11, 12, 13, 14],
        [15, 16, 17, 18, 19],
        [20, 21, 22, 23, 24]])
 >>> y = np.abs(x - x.T)
 >>> y
array([[ 0,  4,  8, 12, 16],
        [ 4,  0,  4,  8, 12],
        [ 8,  4,  0,  4,  8],
        [12,  8,  4,  0,  4],
        [16, 12,  8,  4,  0]])
 >>> np.argmin(y, axis=0)
array([0, 1, 2, 3, 4])
 >>> np.min(y, axis=0)
array([0, 0, 0, 0, 0])

Here it seems like there should be a simple way to get the same array 
that min() returns using the argmin result, which won't need to 'search' 
in the array.

Thanks very much,
     Ken





More information about the NumPy-Discussion mailing list