2 python numpy matrix 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阵列的三种方法:
Convert to a boolean array and use the ~ operator to bitwise NOT the array:
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]]
Use numpy.logical_not and cast the resulting boolean array back to integers:
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]]
Just subtract all your integers from 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]]
The third way will probably be quickest for most non-boolean dtypes.