通过索引和掩码更新?
Update by an index and a mask?
我有一个大的二维数组,我通过索引访问它。我只想更新不为零的索引数组的值。
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
但是,这不会更新数组。我该如何解决?
一个简单的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
中的 True
中提取整数索引,然后创建新的 idxs
,它是基于掩码的选择性,就像这样 -
r,c = np.nonzero(mask)
idxs_new = (idxs[0][:,0][r], idxs[1][0][c])
mapx[idxs_new] += 1
对于自定义更新,最后一步可以进行类似的编辑。只需使用 idxs_new
代替 idxs
即可更新。
我有一个大的二维数组,我通过索引访问它。我只想更新不为零的索引数组的值。
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
但是,这不会更新数组。我该如何解决?
一个简单的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
中的 True
中提取整数索引,然后创建新的 idxs
,它是基于掩码的选择性,就像这样 -
r,c = np.nonzero(mask)
idxs_new = (idxs[0][:,0][r], idxs[1][0][c])
mapx[idxs_new] += 1
对于自定义更新,最后一步可以进行类似的编辑。只需使用 idxs_new
代替 idxs
即可更新。