是否可以在不抛出 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 不要抛出异常并返回垃圾,然后我可以用我的默认值替换它吗?
最佳答案
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])
不是很漂亮,而是一个开始。
关于numpy - 在 numpy 数组之外索引时的默认值,即使是非平凡的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36923309/