I want to initialize a numpy array of size (n,m) that can only contain zeros or ones.
Furthermore, I want to later to np.bitwise_or with the array.
For example, If I try:
import numpy as np
myArray = np.zeros([4,4])
myRow = myArray[1,]
myCol = myArray[,1]
TypeError: ufunc 'bitwise_or' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
np.zeros will use a float dtype, and you can't perform the bitwise operations on floats.
np.bitwise_or([0,0,0,0], [0,0,0,0]) acts on integers, which is why it works.
If you pass an integer dtype instead when you construct
myArray, it'll work too:
In : myArray = np.zeros([4,4], dtype=int) In : myRow = myArray[1,:] In : myCol = myArray[:,1] In : np.bitwise_or(myRow, myCol) Out: array([0, 0, 0, 0])
or we could call
In : myArray = np.array([[1.0,0.0,1.0,0.0], [1.0,1.0,1.0,0.0]]) In : np.bitwise_or(myArray.astype(int), myArray.astype(int)) Out: array([1, 1, 1, 0])
That said, if you know the array is always going to contain only 0 or 1, you should consider a
bool array instead:
In : myArray = myArray.astype(bool) In : np.bitwise_or(myArray, myArray) Out: array([ True, True, True, False], dtype=bool)