In the Python’s standard max function I can pass in a key parameter:
s = numpy.array(['one','two','three'])
max(s) # 'two' (lexicographically last)
max(s, key=len) # 'three' (longest string)
With a larger (multi-dimensional) array, we can not longer use max, but we can use numpy.amax… which unfortunately offers no key parameter.
t = numpy.array([['one','two','three'],
['four','five','six']],
dtype='object')
numpy.amax(t) # 'two` (max of the flat array)
numpy.amax(t, axis=1) # array([two, six], dtype=object) (max of first row, followed by max of second row)
What I want to be able to do is:
amax2(t, key=len) # 'three'
amax2(t, key=len, axis=1) # array([three, four], dtype=object)
Is there a built-in method to do this?
Note: In trying to write this question the first time I couldn’t get amax working in this toy example!
This is a non built-in way (it’s missing the
outandkeepdimparameters of features ofamaxwhen usingkey), it seems rather long:The idea for this function is extended from the second part of @PeterSobot’s answer to my previous question.