42

Is there a way to get max and argmax by one stroke ?

import numpy as np
a=[0,0,1,0]
maximum=max(a)
index=np.argmax(a)

Is there a fastest way to do it, with something like:

[maximum,index]=function(a)
1
  • 2
    There are times pytorch is more elegant than numpy: torch.tensor([0,0,1,0]).max(0) gives torch.return_types.max(values=tensor(1),indices=tensor(2))
    – daknowles
    Commented May 21, 2020 at 1:53

1 Answer 1

42

Maybe something like this is faster...

index = np.argmax(a)
maximum = a[index]
2
  • 3
    Good point on saving the calculation time, however, if the original argmax call were to sort a 2D array on the second axis, then the second statement would likely throw an error.
    – PaulDong
    Commented Dec 23, 2016 at 6:34
  • You could recover it by using unravel_index (docs.scipy.org/doc/numpy/reference/generated/…) Commented Jan 27, 2017 at 18:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.