I know there is a method for python list to return the first index of something
l = list(1,2,3)
l.index(2)
>>> 1
Is there something like that for numpy arrays?
|
Yes, here is the answer given a Numpy array, array, and a value, item, to search for.
The result is a tuple with first all the row indices, then all the column indices. For example if array is two dimensions and it contained your item at two locations then
would be equal to your item and so would
|
|||||||||||||||||||||
|
If you need the index of the first occurrence of only one value, you can use
If you need the first index of each of many values, you could obviously do the same as above repeatedly, but there is a trick that may be faster. The following finds the indices of the first element of each subsequence:
Notice that it finds the beginning of both subsequence of 3s and both subsequences of 8s: [1, 1, 1, 2, 2, 3, 8, 3, 8, 8] So it's slightly different than finding the first occurrence of each value. In your program, you may be able to work with a sorted version of
|
|||||||||||||||||
|
you can also convert a Numpy array to list in the air and get its index . for example
Will print 1. |
||||
|
If you're going to use this as an index into something else, you can use boolean indices if the arrays are broadcastable; you don't need explicit indices. The absolute simplest way to do this is to simply index based on a truth value.
Any boolean operation works:
The nonzero method takes booleans, too:
The two zeros are for the tuple of indices (assuming first_array is 1D) and then the first item in the array of indices. |
|||
|
to index on any criteria, you can so something like the following:
[edit] and here's a quick function to do what list.index() does, except doesn't raise an exception if it's not found. beware -- this is probably very slow on large arrays. you can probably monkeypatch this on to arrays if you'd rather use it as a method.
|
||||
|
There are lots of operations in numpy that could perhaps be put together to accomplish this. This will return indices of elements equal to item:
You could then take the first elements of the lists to get a single element. |
|||||||||
|
An alternative to selecting the first element from np.where() is to use a generator expression together with enumerate, such as:
For a two dimensional array one would do:
The advantage of this approach is that it stops checking the elements of the array after the first match is found, whereas np.where checks all elements for a match. A generator expression would be faster if there's match early in the array. |
||||
|