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

后端 未结 2 1506
醉话见心
醉话见心 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:55

    Just came up with a few solutions.

    A couple of ways it with generator:

    max(i for i in s.index if s[i] != 0) # will work only if index is sorted
    

    and

    next(i for i in s.index[::-1] if s[i] != 0)
    

    which is quite readable and also relatively quick.

    Through numpy's trip_zeros:

    import numpy as np
    np.trim_zeros(s, 'b').index[-1]
    

    which is slower than both of the @DSM answers.


    Summary:

    timeit np.trim_zeros(s, 'b').index[-1]
    10000 loops, best of 3: 89.9 us per loop
    
    timeit s[s != 0].index[-1]
    10000 loops, best of 3: 68.5 us per loop
    
    timeit next(i for i in s.index[::-1] if s[i] != 0)
    10000 loops, best of 3: 19.4 us per loop
    
    timeit max(i for i in s.index if s[i] != 0)
    10000 loops, best of 3: 16.8 us per loop
    
    timeit s.index[s.nonzero()[0][-1]]
    100000 loops, best of 3: 1.94 us per loop
    

提交回复
热议问题