xa = np.hstack([[0], x, [0]])
xa1 = (xa != 0) + 0
xadf = np.diff(xa1)
starts = np.where(xadf == 1)[0]
stops_p1 = np.where(xadf == -1)[0]
lens = stops_p1 - starts
put_m1 = stops_p1[[stops_p1 < x.size]]
vec = xa1[1:-1]
vec[put_m1] = -lens[0:put_m1.size]
out = vec.cumsum()
Numpy sum running length of non-zero values