Reputation: 2273
I have some data, expressed as a Numpy array, that has a sequence that looks faintly like this:
np.array([1, 0, 2, 5, 10, 6, 2, 0, 4, 1, 0, 1, 2, 3, 4, 2, 0, 0, 0, 0, 0, 0, 0])
I would like to know what position the last non-zero value of this array - so in this case, the "2" that occurs at position 15.
What's the fastest and easiest way to do this? I'm possibly generating a large number of these, so my initial plan, which was to iterate over the array, remove the last element if it = 0, then take the length of the resulting array, which seems potentially too slow to be useful.
Upvotes: 0
Views: 310
Reputation: 176820
With a
as your array, you could use np.where
to specify the condition you are looking for:
>>> np.where(a != 0)[0][-1]
15
This function returns the indexes of array for which a given condition holds (in this case the indexes of all elements which are not 0). (Actually np.where(a != 0)
returns a one-tuple containing the array so we access it with [0]
.)
The [-1]
is the familiar Python notation for accessing the last element of an iterable object.
Upvotes: 4
Reputation: 2804
You can use the nonzero
function -
>>> arr1.nonzero()[0][-1]
15
Upvotes: 5