2017-08-31 209 views
1
a = pd.Series([0.1,0.2,0.3,0.4]) 
>>> a.loc[[0,1,2]] 
0 0.1 
1 0.2 
2 0.3 
dtype: float64 

當一個不存在的索引加入到現有的沿要求索引操作都將返回NaN,它返回NaN(這是我所需要的)。從一個熊貓系列

>>> a.loc[[0,1,2, 5]] 
0 0.1 
1 0.2 
2 0.3 
5 NaN 
dtype: float64 

但是,當我請求完全不存在的指標,我得到一個錯誤

>>> a.loc[[5]] 
Traceback (most recent call last): 
    File "<pyshell#481>", line 1, in <module> 
    a.loc[[5]] 
KeyError: 'None of [[5]] are in the [index]' 

有沒有一種辦法,以避免訴諸try/except解決方案有再次得到了喃?

+0

https://stackoverflow.com/questions/37147735/remove-nan-value-from-a-set我認爲這應該幫助 – galeej

回答

4

嘗試用pd.Series.reindex代替。

out = a.reindex([0,1,2, 5]) 
print(out) 

0 0.1 
1 0.2 
2 0.3 
5 NaN 
dtype: float64 

out = a.reindex([5]) 
print(out) 

5 NaN 
dtype: float64