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

标签 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 不要抛出异常并返回垃圾,然后我可以用我的默认值替换它吗?

最佳答案

np.takeclip模式,有点这样做

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/

相关文章:

python - 使用折叠相关参数对 GridSearchCV 进行自定义评分

android - android galaxy的真实设备数据库文件为空点异常

vector - 如何反向填充向量?

java - 如何在 Java 中对角检查 2D 字符数组中的字符串 (Eclipse)

Java - 使用字符串合并排序

python - python中的非局部最大值抑制

python - 使用 where 避免 RuntimeWarning

performance - numpy数组子维度上的python操作

Python - "comparison"将一个数组映射到另一个数组的简单方法

java - 获取 ArrayIndexOutOfBoundsException,数组大小是动态确定的