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

2 python numpy matrix numpy-broadcasting

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

M  
0 1 0  
1 0 1  
0 1 0
Run Code Online (Sandbox Code Playgroud)

会成为:

!M  
1 0 1  
0 1 0  
1 0 1
Run Code Online (Sandbox Code Playgroud)

现在我有了

for row in image:
    map(lambda x: 1 if x == 0 else 0, row)
Run Code Online (Sandbox Code Playgroud)

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

ali*_*i_m 7

给定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]]
Run Code Online (Sandbox Code Playgroud)

以下是NOT阵列的三种方法:

  1. 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]]
    
    Run Code Online (Sandbox Code Playgroud)
  2. 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]]
    
    Run Code Online (Sandbox Code Playgroud)
  3. 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]]
    
    Run Code Online (Sandbox Code Playgroud)

The third way will probably be quickest for most non-boolean dtypes.