Home > other >  Find max of each column and its index with numpy ( when max is duplicate in the same col)
Find max of each column and its index with numpy ( when max is duplicate in the same col)

Time:10-25

I have the following 2D numpy array:

>>> A = ([[  100,   -5,   3, 200],
           [  20, -100,   4,   8],
           [  12,  -10,  10,   4],
           [-100,   80,   4,  14]])

>>> A = np.array(A)

I want to find the absolute max value of each column and its index.

For the absolute max I use:

>>> max_col = abs(A).max(axis=0)
>>> print(max_col)
[100 100  10 200]

But when it comes to finding all indices, I can't get the [3][0] -> -100 index in my list.

I used:

>>> maxValueIndex = abs(A).argmax(axis=0)
[0 1 2 0]

I want my maxValueIndex to be:

[0 3 1 2 0]

Maybe I should use the np.where() function but I don't know how.

Any help is appreciated.

CodePudding user response:

Yes, use numpy.where:

# max_col = abs(A).max(axis=0)
np.where(abs(A) == max_col)

output: (array([0, 0, 1, 2, 3]), array([0, 3, 1, 2, 0]))

If you only want the column indices:

np.where(abs(A) == max_col)[1]

output: array([0, 3, 1, 2, 0])

  • Related