Given an integer array of 0s and 1s:
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]]
Here are three ways you could NOT
the array:
Convert to a boolean array and use the
~
operator to bitwiseNOT
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.