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

Ton*_*ony 2 python indexing nan series pandas

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
Run Code Online (Sandbox Code Playgroud)

当不存在的索引与现有索引一起添加到请求时,它返回NaN(这是我需要的)。

>>> a.loc[[0,1,2, 5]]
0    0.1
1    0.2
2    0.3
5    NaN
dtype: float64
Run Code Online (Sandbox Code Playgroud)

但是当我只请求不存在的索引时,我得到一个错误

>>> 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]'
Run Code Online (Sandbox Code Playgroud)

有没有一种方法可以使NaN再次到达那里,从而避免诉诸try/except解决方案?

cs9*_*s95 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
Run Code Online (Sandbox Code Playgroud)
out = a.reindex([5])
print(out)

5   NaN
dtype: float64
Run Code Online (Sandbox Code Playgroud)