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

Warren Weckesser warren.weckesser at enthought.com
Tue Dec 13 17:23:12 EST 2011


On Tue, Dec 13, 2011 at 4:11 PM, Ken Basye <kbasye1 at jhu.edu> wrote:

> 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.
>
>
You can use the result of argmin to index into y, if you combine it with,
say, arange(ncols) in the second dimension:

In [53]: y = random.randint(0,10,size=(5,7))

In [54]: y
Out[54]:
array([[3, 3, 5, 1, 5, 3, 7],
       [1, 0, 6, 8, 0, 1, 1],
       [7, 9, 9, 3, 3, 1, 6],
       [5, 3, 5, 4, 9, 7, 4],
       [1, 7, 1, 6, 6, 1, 8]])

In [55]: am = np.argmin(y, axis=0)

In [56]: am
Out[56]: array([1, 1, 4, 0, 1, 1, 1])

In [57]: colmins = y[am, arange(7)]

In [58]: colmins
Out[58]: array([1, 0, 1, 1, 0, 1, 1])


Warren
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/numpy-discussion/attachments/20111213/efa232ab/attachment.html>


More information about the NumPy-Discussion mailing list