繁体   English   中英

有没有办法不使用numpy广播的任意M x N矩阵?

[英]Is there a way to NOT an arbitrary M x N matrix using numpy broadcasting?

我有多个0和1的矩阵,我想找到NOT的版本。 例如:

M  
0 1 0  
1 0 1  
0 1 0

会成为:

!M  
1 0 1  
0 1 0  
1 0 1

现在我有了

for row in image:
    map(lambda x: 1 if x == 0 else 0, row)

哪个效果很好,但我有一种感觉,我已经看到这完成了简单的广播。 不幸的是,我没有看到任何东西已经敲响了钟声。 我假设类似的操作将用于对矩阵的值进行阈值处理(即, 1 if x > .5 else 0 )。

给定0和1的整数数组:

M = np.random.random_integers(0,1,(5,5))
print(M)
# [[1 0 0 1 1]
#  [0 0 1 1 0]
#  [0 1 1 0 1]
#  [1 1 1 0 1]
#  [0 1 1 0 0]]

以下是您NOT使用数组的三种方法:

  1. 转换为布尔数组并使用~运算符按位而NOT数组:

     print((~(M.astype(np.bool))).astype(M.dtype)) # [[0 1 1 0 0] # [1 1 0 0 1] # [1 0 0 1 0] # [0 0 0 1 0] # [1 0 0 1 1]] 
  2. 使用numpy.logical_not并将生成的布尔数组numpy.logical_not为整数:

     print(np.logical_not(M).astype(M.dtype)) # [[0 1 1 0 0] # [1 1 0 0 1] # [1 0 0 1 0] # [0 0 0 1 0] # [1 0 0 1 1]] 
  3. 只需从1中减去所有整数:

     print(1 - M) # [[0 1 1 0 0] # [1 1 0 0 1] # [1 0 0 1 0] # [0 0 0 1 0] # [1 0 0 1 1]] 

对于大多数非布尔dtypes,第三种方式可能是最快的。

一种解决方案是将数组转换为布尔数组

data = np.ones((4, 4))
bdata = np.array(data, dtype=bool)
print ~bdata

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM