我有一些代码试图在另一个指定的索引处找到数组的内容,这可能指定超出前一个数组范围的索引.
input = np.arange(0, 5)
indices = np.array([0, 1, 2, 99])
我想要做的是:
打印输入[索引]
得到
[0 1 2]
但这会产生异常(如预期的那样):
IndexError: index 99 out of bounds 0<=index<5
所以我想我可以使用蒙面数组来隐藏越界索引:
indices = np.ma.masked_greater_equal(indices, 5)
但仍然:
>print input[indices]
IndexError: index 99 out of bounds 0<=index<5
即使:
>np.max(indices)
2
所以我必须首先填充蒙面数组,这很烦人,因为我不知道我可以使用什么填充值来不为超出范围的那些选择任何索引:
print input[np.ma.filled(indices, 0)]
[0 1 2 0]
所以我的问题是:如何有效地使用numpy从数组安全地选择索引而不超出输入数组的边界?