0

I have a numpy.array of data called f, I know the max value in it is f_max=max(f) but I would like to know the index in the array corresponding to the maximum value.

I tried:

count = 0
while (f[count]!=fmax)
    conto ++

but I receive an error:

SyntaxError: invalid syntax

Could anyone help me?

3
  • On the syntax error: you need a : at the end of the while statement, and use count += 1, but the answer below is the right way to do it. Commented May 24, 2014 at 17:32
  • @Caos note that I have edited your question and included the numpy tag based on the information below that you are using a numpy array. If this information is incorrect then please say so. Commented May 24, 2014 at 17:38
  • Yes! I confirm that I was using a numpy array Commented May 24, 2014 at 19:02

2 Answers 2

4

If you're already using numpy, you can do this with argmax().

import numpy as np
a = np.array([1, 5, 2, 6, 3])

index = a.argmax()
Sign up to request clarification or add additional context in comments.

Comments

1

The easiest way would be to find the max and then, look for its index.

>>> a = [1, 5, 2, 3, 4]
>>> val = max(a)
>>> a.index(val)
1

You could also use enumerate to get a list of indices and the values corresponding to them and choose the max among them.

>>> list(enumerate(a))
[(0, 1), (1, 5), (2, 2), (3, 3), (4, 4)]
>>> index, _ = max(enumerate(a), key = lambda x: x[1])
>>> index
1

5 Comments

Doing this I receive: 'numpy.ndarray' object has no attribute 'index'
@Caos: You should have mentioned you have a Numpy Array.
@Caos: You should use np.argmax in that case.
Sorry I am new to python ad I thought I was using a list
This solution only works to show the first instance of a max, is there a more robust solution?

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.