Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/346.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 从对系列的索引操作返回NaN_Python_Pandas_Indexing_Nan_Series - Fatal编程技术网

Python 从对系列的索引操作返回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

当一个不存在的索引与现有索引一起添加到请求中时,它返回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/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