查找 pandas 系列中最后一个非零元素的索引

问题描述 投票:0回答:2

我想找到 pandas 系列中最后一个非零元素的索引。我可以用循环来完成:

ilast = 0
for i in mySeries.index:
    if abs(mySeries[i]) > 0:
        ilast = i

有没有更干净、更短的方法?

python pandas
2个回答
9
投票

我可能会写

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.


1
投票

刚刚想出了一些解决方案。

使用发电机的几种方法:

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的

trim_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
© www.soinside.com 2019 - 2024. All rights reserved.