2014-02-24 109 views
1

我想查找熊貓系列中最後一個非零元素的索引。我可以用一個循環做到這一點:在熊貓系列中查找最後一個非零元素的索引

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

有沒有做這件事的清潔&較短的方法嗎?

+0

我不知道熊貓系列的想法。這個系列的類型是什麼?你能舉個例子嗎?據我所知,你可以從最後開始旅行,並在遇到非零時返回。 – Sheng

回答

0

剛想出一些解決方案。

一對夫婦與發電機方面來說:

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 
4

我可能只是寫了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。

相關問題