I\'d like to find the index of last non-zero element in pandas series. I can do it with a loop:
ilast = 0
for i in mySeries.index:
if abs(mySeries[i]) > 0
I might just write s[s != 0].index[-1]
, e.g.
>>> s = pd.Series([0,1,2,3,0,4,0],index=range(7,14))
>>> s
7 0
8 1
9 2
10 3
11 0
12 4
13 0
dtype: int64
>>> s[s != 0].index[-1]
12
Originally I thought using nonzero
would make things simpler, but the best I could come up with was
>>> s.index[s.nonzero()[0][-1]]
12
which is a lot faster (30+ times faster) for this example but I don't like the look of it.. YMMV.