triphook
triphook

Reputation: 3097

Address of last value in 1d NumPy array

I have a 1d array with zeros scattered throughout. Would like to create a second array which contains the position of the last zero, like so:

>>> a = np.array([1, 0, 3, 2, 0, 3, 5, 8, 0, 7, 12])
>>> foo(a)
[0, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3]

Is there a built-in NumPy function or broadcasting trick to do this without using a for loop or other iterator?

Upvotes: 3

Views: 73

Answers (1)

NPE
NPE

Reputation: 500357

>>> (a == 0).cumsum()
array([0, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3])

Upvotes: 8

Related Questions