[Numpy-discussion] maximum value and corresponding index

Hans Meine meine@informatik.uni-hamburg...
Thu Aug 6 03:21:58 CDT 2009

On Wednesday 05 August 2009 22:06:03 David Goldsmith wrote:
> But you can "cheat" and put them on one line (if that's all you're after):
> >>> x = np.array([1, 2, 3])
> >>> maxi = x.argmax(); maxv = x[maxi]

Is there any reason not to put this as a convenience function into numpy?
It is needed so frequently, and it's a shame that the shortest solution 
traverses the array twice (the above is usually longer due to variable names, 
and/or >1 dimensions).

def give_me_a_good_name(array):
	pos = array.argmax()
	val = array[unravel_index(pos)]
	return pos, val

The name should not be too long, maybe "findmax"?  I don't see good 
predecessors to learn from ATM.

OTOH, a minmax() would be more pressing, since there is no shortcut yet 


More information about the NumPy-Discussion mailing list