Skip to main content
 首页 » 编程设计

python之替换给定索引处的所有 1之numpy

2024年10月17日7虾米哥

我有一个大小为 10×10 的二进制矩阵。我想将矩阵中给定索引处的所有 1 更改为 -1

我能得到这样的东西

import numpy as np 
mat = np.random.randint(2, size=(10, 10)) 
index = [6,7,8,9] 
 
mat[(mat[index,:] == 1).nonzero()] = -1 
print(mat) 

当我打印这个时,我得到这样的东西

[[-1  0 -1  1  0 -1 -1  1 -1  0] 
 [ 1  0  1 -1 -1  1 -1 -1 -1  1] 
 [ 0 -1  1  0 -1 -1 -1  1 -1  0] 
 [-1 -1 -1 -1 -1  1 -1  1 -1  1] 
 [ 1  1  1  1  0  0  0  0  0  1] 
 [ 1  1  1  1  0  0  0  0  1  0] 
 [ 1  0  1  0  0  1  1  0  1  0] 
 [ 0  0  0  1  1  0  1  1  1  0] 
 [ 0  1  0  0  1  1  1  0  1  0] 
 [ 1  1  1  1  1  0  1  0  1  0]] 

但这似乎是错误的,因为索引在矩阵的末尾,我想要的是

[[ 1  0  1  1  0  1  1  1  1  0] 
 [ 1  0  1  1  1  1  1  1  1  1] 
 [ 0  1  1  0  1  1  1  1  1  0] 
 [ 1  1  1  1  1  1  1  1  1  1] 
 [ 1  1  1  1  0  0  0  0  0  1] 
 [ 1  1  1  1  0  0  0  0  1  0] 
 [-1  0 -1  0  0 -1 -1  0 -1  0] 
 [ 0  0  0 -1 -1  0 -1 -1 -1  0] 
 [ 0 -1  0  0 -1 -1 -1  0 -1  0] 
 [-1 -1 -1 -1 -1  0 -1  0 -1  0]] 

我知道 nonzero() 不是必需的,因为我已经将内容与 1 进行了比较,但这是我得到的最好结果。

我做错了什么?有没有办法得到正确的答案?

请您参考如下方法:

使用numpy.where根据mat选择条件元素:

import numpy as np 
mat = np.random.randint(2, size=(10, 10)) 
index = [6,7,8,9] 
 
mat[index,:] = np.where(mat[index,:],-1,mat[index,:]) 
print(mat) 

这将根据原始值的真实性覆盖 mat 的给定行。如果这些行中的原始值为 1,它们将被 -1 覆盖,否则它们将保持不变。

尽管请注意,如果您有一个只有 0 和 1 的二进制矩阵,您可以只翻转给定行中每个元素的符号,因为 0 对于此转换是不变的:

mat[index,:] = -mat[index,:]