Dnaiel Dnaiel - 6 months ago 79
Python Question

np.ndarray bitwise_or operator on ndarrays fails

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]
np.bitwise_or(myRow, myCol)

It fails:

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''

How can I do this in a similar manner but without errors?

If I try,

np.bitwise_or([0,0,0,0], [0,0,0,0])

it actually works.


By default, 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 [9]: myArray = np.zeros([4,4], dtype=int)

In [10]: myRow = myArray[1,:]

In [11]: myCol = myArray[:,1]

In [12]: np.bitwise_or(myRow, myCol)
Out[12]: array([0, 0, 0, 0])

or we could call astype(int):

In [14]: myArray = np.array([[1.0,0.0,1.0,0.0], [1.0,1.0,1.0,0.0]])

In [15]: np.bitwise_or(myArray[0].astype(int), myArray[1].astype(int))
Out[15]: 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 [21]: myArray = myArray.astype(bool)

In [22]: np.bitwise_or(myArray[0], myArray[1])
Out[22]: array([ True,  True,  True, False], dtype=bool)