【问题标题】:Indexing numpy array with bounds checking使用边界检查索引 numpy 数组
【发布时间】:2018-04-17 17:29:55
【问题描述】:

假设我有一些随机的 numpy 数组:

>>> x = np.random.randn(10, 4, 4)

因此可以将其视为 10 个 4x4 数组。现在,我也有一些关于这些数组的坐标:

>>> coords.shape
(10, 4, 4, 2)

这个数组的特定元素可能如下所示:

>>> coords[i][j][k]
array([ 2,  2])

现在,我想创建一个数组,y,大小为 (10, 4, 4),如果 coords[i][j][k] 在边界内,则 y[i][j][k] = x[coords[i][j][k]],否则 0

我尝试过如下操作:

>>> y = np.where(np.logical_and(
                 np.all(coords >= 0, axis = 3), 
                 np.all(coords <= 3, axis = 3)), 
                 x[tuple(coords)], 0)

但我无法完全正确地获取广播规则,而且我遇到了错误。

例如,假设我们有,

>>> x = np.array([
                 [[1., 2.],
                  [4., 5.]],
                 [[6., 7.],
                  [8., 9.]]])

与,

>>> coords = np.array([
                       [[[0,-1], [0, 0]],
                        [[1, 1], [1, 0]]],
                       [[[1, 1], [1, 0]],
                        [[7, 2], [0, 0]]]
                      ])

那么,我想以某种方式得到

y = np.array([
             [[0., 1.],
              [5., 4.]],
             [[9., 8.],
              [0., 6.]]]) 

如何在 Python 中实现这一点?

【问题讨论】:

  • np.where(mask,x,0) 不能在 maskall 掩码的地方工作?也就是说,您可以在那里列出x 而不是x[tuple(coords)]
  • 所以这只是给你x,除了那些坐标超出范围的位置。不是 x 相对于新坐标的洗牌。
  • 你的意思不是 [j][k] 有:if coords[i][j][j] is in bounds, a 吗?另外,我们在谈论什么洗牌?
  • 已编辑以反映您的上述评论。而coords 可以被认为是元素的“洗牌”,但有些坐标可能会出现两次,或者根本不会出现,所以它可能不是真正的洗牌。
  • 那么,coords[i,j,k,0] 正在索引到第二轴,coords[i,j,k,1] 索引到 x 的第三轴?

标签: python arrays numpy indexing array-broadcasting


【解决方案1】:

似乎需要进行一些 adavnced-indexing 工作,并且应该适用于通用 n-dim 案例 -

m,n = x.shape[0], x.shape[-1]
mask = (coords < n).all((-1)) & (coords >=0).all((-1))
v_coords = np.where(mask[:,:,:,None],coords,0)
out = x[np.arange(m)[:,None,None], v_coords[...,0], v_coords[...,1]]
out[~mask] = 0

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-01
    • 2015-10-02
    • 2013-09-23
    • 2019-10-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多