2014-08-27 124 views
9

我有一個數據幀df具有以下:大熊貓數據幀選擇楠索引

In [10]: df.index.unique() 
Out[10]: array([u'DC', nan, u'BS', u'AB', u'OA'], dtype=object) 

我可以容易地選擇出df.ix [ 「DC」],df.ix [ 「BS」]等但我在選擇nan索引時遇到問題。

df.ix[nan], df.ix["nan"], df.ix[np.nan] all won't work. 

如何選擇nan作爲索引的行?

+1

一般來說,在一個索引中使用nan是非常不鼓勵的 - 如果你有超過1納米,你的索引不是唯一的,因此很多操作的效率和複雜度都很低 – Jeff 2014-08-27 20:31:11

回答

12

一種方法是使用df.index.isnull()識別的NaN的位置:

In [218]: df = pd.DataFrame({'Date': [0, 1, 2, 0, 1, 2], 'Name': ['A', 'B', 'C', 'A', 'B', 'C'], 'val': [0, 1, 2, 3, 4, 5]}, index=['DC', np.nan, 'BS', 'AB', 'OA', np.nan]); df 
Out[218]: 
    Date Name val 
DC  0 A 0 
NaN  1 B 1 
BS  2 C 2 
AB  0 A 3 
OA  1 B 4 
NaN  2 C 5 

In [219]: df.index.isnull() 
Out[219]: array([False, True, False, False, False, True], dtype=bool) 

然後,你可以使用df.loc選擇那些行:

In [220]: df.loc[df.index.isnull()] 
Out[220]: 
    Date Name val 
NaN  1 B 1 
NaN  2 C 5 

注:我原來的答覆用pd.isnull(df.index)代替Zero's suggestion,df.index.isnull()。最好使用df.index.isnull(),因爲對於不能容納NaN的索引類型(如Int64IndexRangeIndex,isnull方法returns an array of all False values immediately),而不是盲目檢查索引中每個項目的NaN值。

+0

另外,'df.loc [df.index .isnull()]' - 'isnull'方法被添加。 – Zero 2017-10-05 17:25:26

+0

@零:感謝您的改進! – unutbu 2017-10-05 18:13:07

+0

如果我們不得不放棄'nan'索引行,那麼'df.loc [df.index.notnull()]'幫助!! – 2017-10-24 09:40:19