numpy: what is the logic of the argmin() and argmax() functions?

后端 未结 5 493
遇见更好的自我
遇见更好的自我 2020-12-23 21:01

I can not understand the output of argmax and argmin when use with the axis parameter. For example:

>>> a = np.array([[1,2         


        
5条回答
  •  无人及你
    2020-12-23 21:52

    By adding the axis argument, NumPy looks at the rows and columns individually. When it's not given, the array a is flattened into a single 1D array.

    axis=0 means that the operation is performed down the columns of a 2D array a in turn.

    For example np.argmin(a, axis=0) returns the index of the minimum value in each of the four columns. The minimum value in each column is shown in bold below:

    >>> a
    array([[ 1,  2,  4,  7],  # 0
           [ 9, 88,  6, 45],  # 1
           [ 9, 76,  3,  4]]) # 2
    
    >>> np.argmin(a, axis=0)
    array([0, 0, 2, 2])
    

    On the other hand, axis=1 means that the operation is performed across the rows of a.

    That means np.argmin(a, axis=1) returns [0, 2, 2] because a has three rows. The index of the minimum value in the first row is 0, the index of the minimum value of the second and third rows is 2:

    >>> a
    #        0   1   2   3
    array([[ 1,  2,  4,  7],
           [ 9, 88,  6, 45],
           [ 9, 76,  3,  4]])
    
    >>> np.argmin(a, axis=1)
    array([0, 2, 2])
    

提交回复
热议问题