python+numpy Method of Maximizing a Two Dimensional Array by Row

  • 2021-07-13 05:33:20
  • OfStack

Problem description:

Given 1 2-dimensional array, find the maximum value per 1 row

Returns 1 column vector

Such as:

Given array '1, 2, 3; 4, 5, 3'

Return to [3; 5]


import numpy as np

x = np.array([[1,2,3],[4,5,3]])
#  First, find the subscript of the maximum value of each row 
index_max = np.argmax(x, axis=1)#  Among them, axis=1 Indicates calculation by row 
print(index_max.shape)

max = x[range(x.shape[0]), index_max]
print(max)
#  Notice that the row vector is returned here 
#  This can be 1 A general method, 
#  Among them range () can be 1 A column vector representing 0 To n
# index_max Also 1 Column vectors representing specific coordinates 
#  In this way, the two coordinates are combined to become 2 Dimensional index 

max_ = x[range(x.shape[0]), index_max].reshape(-1,1)
print(max_)
#  This becomes a column vector 

It is worth noting that:

1) np. argmax gets a column vector, not a row vector, which is also reflected in other functions

2) Sum and other operations can be done on a row or column basis by specifying axis

3) Use reshape () to return the specific dimension, the dimension we need. The parameter of the function can have 1-1, but it can only have 1, indicating that this number is unknown


Related articles: