Daniel Lemire's blog

, 5 min read

Computing argmax fast in Python

12 thoughts on “Computing argmax fast in Python”

  1. Anonymous says:

    You can try this:

    def positionMax(sequence, excludedIndexesSet=None):
    if not badindexes:
    return max( izip(sequence, xrange(len(sequence)) ) )[1]
    else:
    badindexes = set(badindexes)
    return max( (e,i) for i,e in enumerate(sequence) if i not in badindexes )[1]

  2. SwiftCoder says:

    You should also try a functional idiom – typically better and faster:

    array = [1.0, 2.0, 3.0, 1.0]

    m = reduce(max, array)

  3. Protector one says:

    I’m sorry SwiftCoder, but I believe that is a max. It is equivalent to:

    m = max(array)

    My (arg)max:

    lambda array: max([array[i],i] for i in range(len(array)))[1]

    Cheers!

  4. kralin says:

    array.index(max(array))

    is it too simple?

  5. Sam says:

    import numpy

    array = numpy.array ( [1,2,4,3,5,1 ] )

    numpy.argmax( array )

    # should return 4

  6. Mapio says:

    In case of duplicate values you solution returns the last position, while the array.index(max(array)) solution returns the first which, beside the simplicity of the solution, seems to be the more natural answer.

  7. Anonymous says:

    How about

    max(xrange(len(array)), key=array.__getitem__)

    1. great, much faster!

  8. Pingback: argmax in Python | Tastalian's Blog
  9. Kasia says:

    numpy.ndarray object has no attributes index and maxarg. What should I do?

  10. jean says:

    argmax=max([(i[0], array[i[0]]) \
    for i in enumerate(array)], key=lambda t:t[1])[0]