【问题标题】:Return NaN from indexing operation on a pandas series从熊猫系列的索引操作中返回 NaN
【发布时间】:2018-02-09 05:01:44
【问题描述】:
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 解决方案?

【问题讨论】:

标签: python pandas indexing nan series


【解决方案1】:

改用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

【讨论】:

    猜你喜欢
    • 2013-12-12
    • 1970-01-01
    • 2020-02-19
    • 2018-03-27
    • 1970-01-01
    • 2018-11-23
    • 1970-01-01
    • 2016-02-06
    • 1970-01-01
    相关资源
    最近更新 更多