SkogensKonung
SkogensKonung

Reputation: 663

How to choose the row from a numpy's array for which a specific column's value is the largest?

Given an array of a particular shape (m, n), I'd like to choose the whole row (or find its index) for which a specific's column value is the largest.

Consider the array below. I'd like to find the row where a value of the second column is the largest. The biggest value of the second columns is 0.795, so I should return [0.21212121, 0.795].

array([[-3.        ,  0.5       ],
       [-2.93939394,  0.5       ],
       [-2.87878788,  0.5       ],
       [ 0.21212121,  0.795     ],
       [ 0.27272727,  0.785     ],
       [ 0.33333333,  0.785     ],
       [ 0.39393939,  0.77      ],
       [ 2.93939394,  0.5       ],
       [ 3.        ,  0.5       ]])

I have achieved the desired result in the following way:

best_result = np.max(acc_m[:, 1])
row_with_best_res = acc_m[acc_m[:, 1] == best_result]

where acc_m is the name of the array.

The presented solution works, but I can't believe that there's no fancier, pythonic way to do this.

Upvotes: 1

Views: 70

Answers (2)

Horace
Horace

Reputation: 1054

You can use the argmax function:

row = acc_m[np.argmax(acc_m[:, 1])]
print(row)
[0.21212121 0.795     ]

Upvotes: 0

bluesummers
bluesummers

Reputation: 12607

Using np.argmax()

In your case

row_with_best_res = acc_m[acc_m[:, 1].argmax()]

Upvotes: 4

Related Questions