numpy中的内置函数可以按位方式将整数解释为布尔值数组吗? [英] Built-in function in numpy to interpret an integer to an array of boolean values in a bitwise manner?

查看:73
本文介绍了numpy中的内置函数可以按位方式将整数解释为布尔值数组吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

例如:

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

然后我想返回:

[True, False, True]

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

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

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

谢谢

推荐答案

您可以使用numpy的unpackbits.

You can use numpy's unpackbits.

从文档中( 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)

要获取布尔数组:

In [49]: np.unpackbits(np.array([1],dtype="uint8")).astype("bool")
Out[49]: array([False, False, False, False, False, False, False,  True], dtype=bool)

这篇关于numpy中的内置函数可以按位方式将整数解释为布尔值数组吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆