triphook triphook - 3 months ago 15
Python Question

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?

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