通过索引和掩码进行更新?

4

我有一个大的二维数组,通过索引访问。我想仅更新非零索引数组的值。

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

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

你的地图和索引的形状很奇怪,能否请你更新一下问题并提供正确的数据?我的意思是,你对于地图有一些可以理解的东西,但是对于索引却不是。 - ted
另外,你应该避免使用 map 作为变量名,因为它会覆盖 Python 的内置 map 函数。 - ted
你的目标是更新 mapx 本身吗? - Mad Physicist
1个回答

1

一个简单的例子,使用np.where函数,将掩码作为第一个输入来选择和赋值 -

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

自定义更新值

第二个参数(这里是mapx[idxs]+1)可以编辑为任何您可能正在执行的复杂更新,以用于与mask中的True相对应的掩码位置。因此,假设您正在对掩码位置进行更新:

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

然后,将第二个参数替换为 mapx[idxs] + x * (A - mapx[idxs])
另一种方法是从“mask”中提取整数索引,然后创建一个基于掩码的选择性新“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
@sten 那个复杂的公式是否可以转化为涉及 mapx[idxs] 的内容?如果是,那么只需用 np.where 的第二个参数替换那个复杂的公式即可。 - Divakar
没错.. mapx[idxs] += x * (A - mapx[idxs]) - sten
@sten,所以只需将np.where的第二个参数替换为:mapx[idxs] + x * (A - mapx[idxs]) - Divakar
哦,我明白了,从未像这样使用过.where()...查看了文档 :) - sten

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接