Python 从对系列的索引操作返回NaN
当一个不存在的索引与现有索引一起添加到请求中时,它返回NaN(这是我所需要的) 但是当我只请求不存在的索引时,我得到了一个错误Python 从对系列的索引操作返回NaN,python,pandas,indexing,nan,series,Python,Pandas,Indexing,Nan,Series,当一个不存在的索引与现有索引一起添加到请求中时,它返回NaN(这是我所需要的) 但是当我只请求不存在的索引时,我得到了一个错误 >>> a.loc[[0,1,2, 5]] 0 0.1 1 0.2 2 0.3 5 NaN dtype: float64 >a.loc[[5]] 回溯(最近一次呼叫最后一次): 文件“”,第1行,在 a、 loc[[5]] KeyError:“[[5]]中没有一个在[索引]中” 是否有办法再次获得NaN,以避免诉诸try/e
>>> a.loc[[0,1,2, 5]]
0 0.1
1 0.2
2 0.3
5 NaN
dtype: float64
>a.loc[[5]]
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
a、 loc[[5]]
KeyError:“[[5]]中没有一个在[索引]中”
是否有办法再次获得NaN,以避免诉诸
try/except
解决方案 试着用pd.Series.reindex代替
>>> 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]'
我认为这应该有帮助
>>> 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]'
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