[英]Find last non-zero element's index in pandas series
我想找到熊猫系列中最后一个非零元素的索引。 我可以通过循环来做到这一点:
ilast = 0
for i in mySeries.index:
if abs(mySeries[i]) > 0:
ilast = i
有没有更清洁,更短的方法呢?
我可能只写s[s != 0].index[-1]
,例如
>>> 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
最初我认为使用nonzero
会简化事情,但是我能想到的最好的办法是
>>> s.index[s.nonzero()[0][-1]]
12
对于本示例,这要快很多(快30倍以上),但我不喜欢它的外观。YMMV。
只是想出了一些解决方案。
使用Generator的几种方法:
max(i for i in s.index if s[i] != 0) # will work only if index is sorted
和
next(i for i in s.index[::-1] if s[i] != 0)
既可读又快捷。
通过numpy的trip_zeros
:
import numpy as np
np.trim_zeros(s, 'b').index[-1]
这比两个@DSM答案都要慢。
摘要:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.