【问题标题】:Update by an index and a mask?通过索引和掩码更新?
【发布时间】:2020-03-29 23:31:42
【问题描述】:

我有一个大的二维数组,我可以通过索引访问它。我只想更新索引数组中不为零的值。

arrayx = np.random.random((10,10))

假设我有索引(这只是示例,实际索引是由单独的进程生成的):

idxs = np.array([[4],
        [5],
        [6],
        [7],
        [8]]), np.array([[5, 9]])

鉴于这些索引,这应该可以工作,但它没有。

arrayx[idxs]

array([[0.7 , 0.1 ],
       [0.79, 0.51],
       [0.  , 0.8 ],
       [0.82, 0.32],
       [0.82, 0.89]], dtype=float16)

// note from editor: '<>' is equivalent to '!='
// but I agree that '>' 0 is more correct
// mask = mapx[idxs] <> 0 // original
mask = arrayx[idxs] > 0 // better

array([[ True,  True],
       [ True,  True],
       [False,  True],
       [ True,  True],
       [ True,  True]])

arrayx[idxs][mask] += 1

但是,这不会更新数组。我该如何解决这个问题?

【问题讨论】:

  • 所以你的地图的 2D 和索引有一个奇怪的形状你能用适当的数据更新你的问题吗?我的意思是你有一些可以理解的地图,但不是 idxs
  • 另外,你应该避免使用map作为变量名,因为它会覆盖python的内置映射函数
  • 您的目标是更新mapx 本身吗?

标签: python numpy indexing updates mask


【解决方案1】:

一个简单的 np.where 带有掩码作为第一个输入来选择和分配 -

mapx[idxs] = np.where(mask,mapx[idxs]+1,mapx[idxs])

自定义更新值

第二个参数(此处为mapx[idxs]+1)可以编辑为您可能对Truemask 中的True 对应的屏蔽位置进行的任何复杂更新。因此,假设您正在对蒙面的地方进行更新:

mapx[idxs] += x * (A - mapx[idxs])

然后,将第二个 arg 替换为 mapx[idxs] + x * (A - mapx[idxs])


另一种方法是从mask 中的True 中提取整数索引,然后根据掩码选择性地创建新的idxs,就像这样 -

r,c = np.nonzero(mask)
idxs_new = (idxs[0][:,0][r], idxs[1][0][c])
mapx[idxs_new] += 1

最后一步可以类似地编辑以进行自定义更新。只需使用idxs_new 代替idxs 即可更新。

【讨论】:

  • 我简化了更新不是简单的+=1,而是一个复杂的公式!
  • @sten 可以把这个复杂的公式当作涉及mapx[idxs] 的东西吗?如果是这样,那么只需用第二个参数替换那个复杂的公式到np.where?
  • 是的.. mapx[idxs] += x * (A - mapx[idxs])
  • @sten 所以,只需将第二个参数替换为 np.where 即可:mapx[idxs] + x * (A - mapx[idxs])
  • oo 我看到从来没有像这样使用过 .where() ......检查了文档 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-11-04
  • 1970-01-01
  • 2015-02-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-23
相关资源
最近更新 更多