Skip to main content
 首页 » 编程设计

python之基于numpy 1D数组的2D numpy数组中的智能分配

2024年11月24日13yxwkf

我有一个 numpy 二维数组,我想根据以下逻辑将它变成 -1\1 值:

一个。找到每一行的 argmax()

基于该一维数组 (a) 分配包含值 1 的值

基于这个一维数组的否定赋值-1

例子:

arr2D = np.random.randint(10,size=(3,3)) 
idx = np.argmax(arr2D, axis=1) 
 
arr2D = [[5 4 1] 
         [0 9 4] 
         [4 2 6]] 
idx = [0 1 2] 
 
arr2D[idx] = 1 
arr2D[~idx] = -1 

我得到的是这样的:

arr2D = [[-1 -1 -1] 
         [-1 -1 -1] 
         [-1 -1 -1]] 

当我想要的时候:

arr2D = [[1 -1 -1] 
         [-1 1 -1] 
         [-1 -1 1]] 

感谢一些帮助, 谢谢

请您参考如下方法:

方法 #1

用那些 argmax 创建一个掩码 -

mask = idx[:,None] == np.arange(arr2D.shape[1]) 

然后,使用这些索引,然后使用它来创建那些 1s 和 -1s 数组 -

out = 2*mask-1 

或者,我们可以使用 np.where -

out = np.where(mask,1,-1) 

方法 #2

创建 mask 的另一种方法是 -

mask = np.zeros(arr2D.shape, dtype=bool) 
mask[np.arange(len(idx)),idx] = 1 

然后,使用方法 #1 中列出的方法之一out。

方法 #3

还有一种方法是这样的-

out = np.full(arr2D.shape, -1) 
out[np.arange(len(idx)),idx] = 1 

或者,我们可以使用 np.put_along_axis 进行赋值 -

np.put_along_axis(out,idx[:,None],1,axis=1)