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

Python 通过索引和掩码进行更新?,python,numpy,indexing,updates,mask,Python,Numpy,Indexing,Updates,Mask,我有一个大的二维数组,我通过索引访问它。我只想更新索引数组中不为零的值 arrayx = np.random.random((10,10)) 假设我有索引(这只是一个示例,实际的索引是通过单独的过程生成的): 考虑到这些索引,这应该是可行的,但事实并非如此 arrayx[idxs] array([[0.7 , 0.1 ], [0.79, 0.51], [0. , 0.8 ], [0.82, 0.32], [0.82, 0.89]],

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

arrayx = np.random.random((10,10))
假设我有索引(这只是一个示例,实际的索引是通过单独的过程生成的):

考虑到这些索引,这应该是可行的,但事实并非如此

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
arrayx[idxs]
数组([[0.7,0.1],
[0.79, 0.51],
[0.  , 0.8 ],
[0.82, 0.32],
[0.82,0.89]],dtype=float16)
//编辑器中的注释:“”相当于“!=”
//但我同意'>'0更正确
//mask=mapx[idxs]0//原始
mask=arrayx[idxs]>0//更好
数组([[True,True],
[对,对],
[假,真],
[对,对],
[对,对]]
arrayx[idxs][mask]+=1
但是,这不会更新阵列。如何解决这个问题?

一个简单的方法,将掩码作为选择和分配的第一个输入-

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\u new
代替
idxs
进行更新。

这样地图的2D和索引就有了一个奇怪的形状,你能用适当的数据更新你的问题吗?我的意思是你对map有一些可以理解的东西,但对idxs没有。同样,你应该避免使用
map
作为变量名,因为它会覆盖python的内置map函数。你的目标是更新
mapx
本身吗?我简化了更新不是简单的+=1,而是一个复杂的公式@斯滕:这个复杂的公式能被当作涉及到mapx[idxs]的东西吗?如果是这样,那么就用第二个参数替换这个复杂的公式。。mapx[idxs]+=x*(A-mapx[idxs])@sten So,只需将第二个参数替换为
np。其中
替换为:
mapx[idxs]+x*(A-mapx[idxs])
。我看到从未使用过。像这样的where()。。。检查文档:)
r,c = np.nonzero(mask)
idxs_new = (idxs[0][:,0][r], idxs[1][0][c])
mapx[idxs_new] += 1