【问题标题】:modify numpy array to return `nan` out of bounds?修改numpy数组以返回“nan”越界?
【发布时间】:2019-10-22 22:21:20
【问题描述】:

无论如何创建一个numpy数组,当索引超出范围时返回np.nan?例如

x = np.array([1,2,3])
x[1] # 2
x[-2] # np.nan
x[5] # np.nan

我找到的最接近的东西是np.pad

我知道我可以编写一个包装类,但我想知道是否有任何有效的 numpy 方法可以做到这一点。

【问题讨论】:

  • x[-2] 有效吗? Numpy 支持负索引。是否要覆盖此功能?
  • 这似乎是 scipy 人必须添加到 numpy 中的东西。我不认为 numpy 有这个选项。您可以使用 try 和 except,如果找不到索引,则返回 np.nan 或类似的东西。这是我现在唯一能想到的。
  • 你为什么不直接try except
  • @J.Doe:不能。负索引在 numpy 中有效
  • 啊我现在明白了,你想禁用负索引。在这种情况下,我认为您需要一个包装器,就像this answer__getitem__ 一样,您还可以手动或使用try/except 检查索引是否超出范围。我不认为你可以猴子补丁 np.ndarray

标签: python numpy


【解决方案1】:
In [360]: x = np.array([1,2,3])                                                                        
In [361]: x[1]                                                                                         
Out[361]: 2

np.take 允许您使用模式控制进行索引。如果索引超出范围,默认是引发错误(有关其他选项,请参阅文档):

In [363]: np.take(x,1)                                                                                 
Out[363]: 2
In [364]: np.take(x,-2)                                                                                
Out[364]: 2
In [365]: np.take(x,5)                                                                                 
----
IndexError: index 5 is out of bounds for size 3

您可以编写一个小函数,将其包装在 try/except 中,在 IndexError 的情况下返回 np.nan

请记住,np.nan 是浮点数,而您的示例数组是整数 dtype。

【讨论】:

    【解决方案2】:

    你有很多选择:

    • 只需在代码中插入 try/except 即可。
    • 创建一个继承自 np.array 的类并重新定义索引运算符以实现该行为
    • 编写一个执行 try/except 的简单函数

    我喜欢第一堂课。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-12
      • 1970-01-01
      • 2021-04-06
      • 2013-11-17
      • 1970-01-01
      • 2013-12-21
      • 2012-10-28
      • 1970-01-01
      相关资源
      最近更新 更多