从熊猫系列的索引操作返回NaN

时间:2017-08-31 09:32:40

标签: python pandas indexing nan series

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(这就是我需要的)。

>>> 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]'

有没有办法再次获得NaN以避免诉诸try/except解决方案?

1 个答案:

答案 0 :(得分:5)

请尝试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
相关问题