2016-02-09 105 views
1

在熊貓,我現在有系列的一個實例循環,有可能是我知道下一個非楠指數瞬間,當我遇到一個NaN的。我不想跳過那些NaN,因爲我想對它們進行插值。如何獲得熊貓系列中下一個非NaN數字的索引?

例如,現在我有一個元素

5, 6, 5, NaN, NaN, NaN, 7, 8, 9, NaN, NaN, NaN, 10, 10 

他們的指標是從0到13,當我迭代系列,當時就只是愛要知道什麼是下一個楠指數系列a ,什麼是下一個非NaN。所以從一開始,我能立即知道第一個NaN的索引是4嗎?然後,當我跳到[4]時,我需要知道下一個非NaN號的索引,在這種情況下爲6。

非常感謝。

回答

3

你可以使用isnull方法在那些索引你有NaN值,然後對當前步驟,你可以用比較下你的索引查找:

In [48]: s.index[s.isnull()] 
Out[48]: Int64Index([3, 4, 5, 9, 10, 11], dtype='int64') 

你也可以使用first_valid_index找到第一個非NaN值如:

In [49]: s[4:] 
Out[49]: 
4 NaN 
5 NaN 
6  7 
7  8 
8  9 
9 NaN 
10 NaN 
11 NaN 
12 10 
13 10 
dtype: float64 

In [50]: s[4:].first_valid_index() 
Out[50]: 6 

編輯

如果你想爲一個整數索引,你可以使用熊貓指數get_loc

b = s[4:] 

In [156]: b 
Out[156]: 
4 NaN 
5 NaN 
6  7 
7  8 
8  9 
9 NaN 
10 NaN 
11 NaN 
12 10 
13 10 
dtype: float64 

In [157]: b.first_valid_index() 
Out[157]: 6 

In [158]: b.index.get_loc(b.first_valid_index()) 
Out[158]: 2 

EDIT2

你可以使用get_indexer讓您擁有NaNs,並在那裏你有有效值所有指數:

import string 
s = pd.Series([5, 6, 5, np.nan, np.nan, np.nan, 7, 8, 9, np.nan, np.nan, np.nan, 10, 10], index = list(string.ascii_letters[:len(s.index)])) 

In [216]: s 
Out[216]: 
a  5 
b  6 
c  5 
d NaN 
e NaN 
f NaN 
g  7 
h  8 
i  9 
j NaN 
k NaN 
l NaN 
m 10 
n 10 
dtype: float64 

valid_indx = s.index.get_indexer(s.index[~s.isnull()]) 
nan_indx = s.index.get_indexer(s.index[s.isnull()]) 

In [220]: valid_indx 
Out[220]: array([ 0, 1, 2, 6, 7, 8, 12, 13]) 

In [221]: nan_indx 
Out[221]: array([ 3, 4, 5, 9, 10, 11])  

或者最簡單的方法將與np.where

In [222]: np.where(s.isnull()) 
Out[222]: (array([ 3, 4, 5, 9, 10, 11], dtype=int32),) 

In [223]: np.where(~s.isnull()) 
Out[223]: (array([ 0, 1, 2, 6, 7, 8, 12, 13], dtype=int32),) 
+0

謝謝!我可以得到整數索引而不是自己定義的索引嗎? – xxx222

+0

@ xxx222我認爲你可以這樣做'reset_index(drop = True)'使你的索引從0開始。或者你還需要那些索引來做別的事嗎? –

+0

是的,我想在這之後返回一個插值的系列(所以我想保留這些索引)。 – xxx222