Find last non-zero element's index in pandas series

后端 未结 2 1504
醉话见心
醉话见心 2021-01-24 16:24

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         


        
2条回答
  •  花落未央
    2021-01-24 16:58

    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.

提交回复
热议问题