首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >NumPy中默认值为N-D索引

NumPy中默认值为N-D索引
EN

Stack Overflow用户
提问于 2020-09-29 14:54:44
回答 2查看 99关注 0票数 2

对于越界索引,我是否可以使用回退到默认值的NumPy N-D数组进行索引?下面是一些虚构的np.get_with_default(a, indexes, default)的示例代码

代码语言:javascript
运行
复制
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
))

应打印

代码语言:javascript
运行
复制
[2 3 6 13 13 13]

我正在寻找一些内置函数来实现这一点。如果不存在,那么至少有一些简短而有效的实现来实现它。

EN

Stack Overflow用户

发布于 2021-10-31 18:42:43

我提出这个问题是因为我在寻找完全相同的东西。我想出了下面的函数,它可以做你所要求的二维。它很可能被推广到N维。

代码语言:javascript
运行
复制
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

xxyy是索引数组,a(y,x)索引。

这提供了:

代码语言:javascript
运行
复制
>>> 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])

作为另一种选择,下面的实现实现了同样的功能,而且更简洁:

代码语言:javascript
运行
复制
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
票数 1
EN
查看全部 2 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64114357

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档