Built-in function in numpy to interpret an integer to an array of boolean values in a bitwise manner?

荒凉一梦 提交于 2019-12-24 04:56:43

问题


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 of the number please?

e.g:

x = 5 # i.e. 101 in binary
print FUNCTION(x)

and then I'd like returned:

[True, False, True]

or ideally, with padding to always return 8 boolean values (i.e. one full byte):

[False, False, False, False, False, True, False, True]

Thanks


回答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)



回答2:


Not a built in method, but something to get you going (and fun to write)

>>> def int_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]


来源:https://stackoverflow.com/questions/22773443/built-in-function-in-numpy-to-interpret-an-integer-to-an-array-of-boolean-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!