我有一些代码尝试在另一个数组指定的索引处查找数组的内容,该索引可能指定超出前一个数组范围的索引。
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
因此,我必须首先填充屏蔽数组,这很烦人,因为我不知道可以使用什么填充值来不为超出范围的索引选择任何索引:
打印输入[np.ma.filled(indices, 0)]
[0 1 2 0]
所以我的问题是:如何有效地使用 numpy 从数组中安全地选择索引而不超出输入数组的范围?
如果不使用掩码数组,您可以删除大于或等于 5 的索引,如下所示:
print input[indices[indices<5]]
编辑:请注意,如果您还想丢弃负索引,您可以编写:
print input[indices[(0 <= indices) & (indices < 5)]]
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)