【问题标题】:Find last non-zero element's index in pandas series在熊猫系列中查找最后一个非零元素的索引
【发布时间】:2014-02-26 06:43:28
【问题描述】:

我想查找 pandas 系列中最后一个非零元素的索引。我可以通过循环来做到这一点:

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

有没有更简洁更简洁的方法?

【问题讨论】:

  • 我对熊猫系列一无所知。该系列的类型是什么?你能举个例子吗?在我看来,你可以从头到尾旅行,遇到非零时返回。

标签: python pandas


【解决方案1】:

我可能只写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。

【讨论】:

  • s.nonzero() 不再有效。可以改用s.to_numpy().nonzero()
【解决方案2】:

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

生成器的几种方式:

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

【讨论】:

    猜你喜欢
    • 2013-08-22
    • 2020-02-19
    • 2017-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多