索引在numpy数组之外的默认值,即使是非平凡的索引

时间:2016-04-28 18:58:51

标签: numpy indexoutofboundsexception

是否可以在不抛出IndexError的情况下从nd数组中查找条目?

我希望有类似的东西:

>>> a = np.arange(10) * 2
>>> a[[-4, 2, 8, 12]]
IndexError
>>> wrap(a, default=-1)[[-4, 2, 8, 12]]
[-1, 4, 16, -1]

>>> wrap(a, default=-1)[200]
-1

或者可能更像get_with_default(a, [-4, 2, 8, 12], default=-1)

是否有一些内置方法可以做到这一点?我可以请求numpy不要抛出异常并返回垃圾,然后我可以用我的默认值替换它吗?

3 个答案:

答案 0 :(得分:2)

{p> np.take clip模式,此类

In [155]: a
Out[155]: array([ 0,  2,  4,  6,  8, 10, 12, 14, 16, 18])

In [156]: a.take([-4,2,8,12],mode='raise')
...
IndexError: index 12 is out of bounds for size 10

In [157]: a.take([-4,2,8,12],mode='wrap')
Out[157]: array([12,  4, 16,  4])

In [158]: a.take([-4,2,8,12],mode='clip')
Out[158]: array([ 0,  4, 16, 18])

除非您对返回值没有太多控制权 - 这里索引12返回18,最后一个值。并将-4视为另一个方向的界限,返回0。

添加默认值的一种方法是首先填充a

In [174]: a = np.arange(10) * 2
In [175]: ind=np.array([-4,2,8,12])

In [176]: np.pad(a, [1,1], 'constant', constant_values=-1).take(ind+1, mode='clip')
Out[176]: array([-1,  4, 16, -1])

不完全漂亮,但是一个开始。

答案 1 :(得分:0)

您可以使用np.maximum()np.minimum()将索引的范围限制为要编入索引的值数组的大小。

示例:

我有像

这样的热图
h = np.array([[ 2,  3,  1],
              [ 3, -1,  5]])

我有一个RGB值的调色板,我想用它来为热图着色。调色板仅为值0..4:

命名颜色
p = np.array([[0, 0, 0],  # black
              [0, 0, 1],  # blue
              [1, 0, 1],  # purple
              [1, 1, 0],  # yellow
              [1, 1, 1]]) # white

现在我想使用调色板为我的热图着色:

p[h]

目前,由于热图中的值-15,这会导致错误:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: index 5 is out of bounds for axis 0 with size 5

但我可以限制热图的范围:

p[np.maximum(np.minimum(h, 4), 0)]

这有效并且给我结果:

array([[[1, 0, 1],
        [1, 1, 0],
        [0, 0, 1]],

       [[1, 1, 0],
        [0, 0, 0],
        [1, 1, 1]]])

如果您确实需要为超出范围的索引设置特殊值,则可以像这样实现建议的get_with_default()

def get_with_default(values, indexes, default=-1):
    return np.concatenate([[default], values, [default]])[
        np.maximum(np.minimum(indexes, len(values)), -1) + 1]

a = np.arange(10) * 2
get_with_default(a, [-4, 2, 8, 12], default=-1)

将返回:

array([-1,  4, 16, -1])

希望。

答案 2 :(得分:0)

这是我在任何堆栈交换站点上的第一篇文章,所以请原谅我所有样式错误(希望只有样式错误)。我对相同的功能感兴趣,但是从numpy中找不到比hpaulj提到的np.take更好的东西。仍然np.take不能完全满足需要。 Alfe的答案有效,但是需要一些详细说明才能处理n维输入。以下是归纳为n维情况的另一种解决方法。基本思想与Alfe所使用的思想类似:创建一个新索引,将超出范围的索引遮盖(在我的情况下)或伪装(在Alfe的情况下),并使用它为输入数组建立索引而不会引发错误。

null

这是Eric的示例问题的输出:

Cannot read property 'getBoundingClientRect' of null