numpy中的内置函数以按位方式将整数解释为布尔值数组?

时间:2021-12-28 14:08:46

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?

我想知道在Python / Numpy中是否有一个简单的内置函数用于将整数数据类型转换为数组/布尔列表,对应于对该数字的按位解释?

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):

或理想情况下,使用padding始终返回8个布尔值(即一个完整字节):

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

Thanks

谢谢

2 个解决方案

#1


5  

You can use numpy's unpackbits.

你可以使用numpy的unpackbits。

From the docs (http://docs.scipy.org/doc/numpy/reference/generated/numpy.unpackbits.html)

来自文档(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:

要获得bool数组:

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


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]

#1


5  

You can use numpy's unpackbits.

你可以使用numpy的unpackbits。

From the docs (http://docs.scipy.org/doc/numpy/reference/generated/numpy.unpackbits.html)

来自文档(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:

要获得bool数组:

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


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]