Wid*_*jet 6 python indexing numpy
我有一些代码试图在另一个指定的索引处找到数组的内容,这可能指定超出前一个数组范围的索引.
input = np.arange(0, 5)
indices = np.array([0, 1, 2, 99])
Run Code Online (Sandbox Code Playgroud)
我想要做的是:打印输入[indices]并得到[0 1 2]
但这会产生异常(如预期的那样):
IndexError: index 99 out of bounds 0<=index<5
Run Code Online (Sandbox Code Playgroud)
所以我想我可以使用蒙面数组来隐藏越界索引:
indices = np.ma.masked_greater_equal(indices, 5)
Run Code Online (Sandbox Code Playgroud)
但仍然:
>print input[indices]
IndexError: index 99 out of bounds 0<=index<5
Run Code Online (Sandbox Code Playgroud)
即使:
>np.max(indices)
2
Run Code Online (Sandbox Code Playgroud)
所以我必须首先填充蒙面数组,这很烦人,因为我不知道我可以使用什么填充值来不为超出范围的那些选择任何索引:
打印输入[np.ma.filled(indices,0)]
[0 1 2 0]
Run Code Online (Sandbox Code Playgroud)
所以我的问题是:如何有效地使用numpy从数组安全地选择索引而不超出输入数组的边界?
不使用蒙版数组,您可以删除大于或等于5的索引,如下所示:
print input[indices[indices<5]]
Run Code Online (Sandbox Code Playgroud)
编辑:请注意,如果您还想丢弃负指数,您可以写:
print input[indices[(0 <= indices) & (indices < 5)]]
Run Code Online (Sandbox Code Playgroud)