Built-in Function In Numpy To Interpret An Integer To An Array Of Boolean Values In A Bitwise Manner?
I'm wondering if there is a simple, built-in function in Python / Numpy for converting an integer datatype to an array/list of booleans, corresponding to a bitwise interpretation o
Solution 1:
You can use numpy's unpackbits
.
From the docs (http://docs.scipy.org/doc/numpy/reference/generated/numpy.unpackbits.html)
>>> a = np.array([[2], [7], [23]], dtype=np.uint8)
>>> a
array([[ 2],
[ 7],
[23]], dtype=uint8)
>>> b = np.unpackbits(a, axis=1)
>>> b
array([[0, 0, 0, 0, 0, 0, 1, 0],
[0, 0, 0, 0, 0, 1, 1, 1],
[0, 0, 0, 1, 0, 1, 1, 1]], dtype=uint8)
To get to a bool array:
In [49]: np.unpackbits(np.array([1],dtype="uint8")).astype("bool")
Out[49]: array([False, False, False, False, False, False, False, True], dtype=bool)
Solution 2:
Not a built in method, but something to get you going (and fun to write)
>>> defint_to_binary_bool(num):
return [bool(int(i)) for i in"{0:08b}".format(num)]
>>> int_to_binary_bool(5)
[False, False, False, False, False, True, False, True]
Post a Comment for "Built-in Function In Numpy To Interpret An Integer To An Array Of Boolean Values In A Bitwise Manner?"