Python: find position of element in array
Python: find position of element in array
Have you thought about using Python lists .index(value)
method? It return the index in the list of where the first instance of the value
passed in is found.
Without actually seeing your data it is difficult to say how to find location of max and min in your particular case, but in general, you can search for the locations as follows. This is just a simple example below:
In [9]: a=np.array([5,1,2,3,10,4])
In [10]: np.where(a == a.min())
Out[10]: (array([1]),)
In [11]: np.where(a == a.max())
Out[11]: (array([4]),)
Alternatively, you can also do as follows:
In [19]: a=np.array([5,1,2,3,10,4])
In [20]: a.argmin()
Out[20]: 1
In [21]: a.argmax()
Out[21]: 4
Python: find position of element in array
As Aaron states, you can use .index(value)
, but because that will throw an exception if value
is not present, you should handle that case, even if youre sure it will never happen. A couple options are by checking its presence first, such as:
if value in my_list:
value_index = my_list.index(value)
or by catching the exception as in:
try:
value_index = my_list.index(value)
except:
value_index = -1
You can never go wrong with proper error handling.