对于越界索引,我是否可以使用回退到默认值的NumPy N-D数组进行索引?下面是一些虚构的np.get_with_default(a, indexes, default)
的示例代码
import numpy as np
print(np.get_with_default(
np.array([[1,2,3],[4,5,6]]), # N-D array
[(np.array([0, 0, 1, 1, 2, 2]), np.array([1, 2, 2, 3, 3, 5]))], # N-tuple of indexes along each axis
13, # Default for out-of-bounds fallback
))
应打印
[2 3 6 13 13 13]
我正在寻找一些内置函数来实现这一点。如果不存在,那么至少有一些简短而有效的实现来实现它。
发布于 2021-10-31 18:42:43
我提出这个问题是因为我在寻找完全相同的东西。我想出了下面的函数,它可以做你所要求的二维。它很可能被推广到N维。
def get_with_defaults(a, xx, yy, nodata):
# get values from a, clipping the index values to valid ranges
res = a[np.clip(yy, 0, a.shape[0] - 1), np.clip(xx, 0, a.shape[1] - 1)]
# compute a mask for both x and y, where all invalid index values are set to true
myy = np.ma.masked_outside(yy, 0, a.shape[0] - 1).mask
mxx = np.ma.masked_outside(xx, 0, a.shape[1] - 1).mask
# replace all values in res with NODATA, where either the x or y index are invalid
np.choose(myy + mxx, [res, nodata], out=res)
return res
xx
和yy
是索引数组,a
由(y,x)
索引。
这提供了:
>>> a=np.zeros((3,2),dtype=int)
>>> get_with_defaults(a, (-1, 1000, 0, 1, 2), (0, -1, 0, 1, 2), -1)
array([-1, -1, 0, 0, -1])
作为另一种选择,下面的实现实现了同样的功能,而且更简洁:
def get_with_default(a, xx, yy, nodata):
# get values from a, clipping the index values to valid ranges
res = a[np.clip(yy, 0, a.shape[0] - 1), np.clip(xx, 0, a.shape[1] - 1)]
# replace all values in res with NODATA (gets broadcasted to the result array), where
# either the x or y index are invalid
res[(yy < 0) | (yy >= a.shape[0]) | (xx < 0) | (xx >= a.shape[1])] = nodata
return res
https://stackoverflow.com/questions/64114357
复制相似问题