Convert binary (0|1) numpy to integer or binary-string?(将二进制(0 | 1)numpy转换为整数或二进制字符串?)
问题描述
是否有将二进制 (0|1) numpy 数组转换为整数或二进制字符串的快捷方式?F.e.
Is there a shortcut to Convert binary (0|1) numpy array to integer or binary-string ? F.e.
b = np.array([0,0,0,0,0,1,0,1])
=> b is 5
np.packbits(b)
有效,但仅适用于 8 位值..如果 numpy 是 9 个或更多元素,它会生成 2 个或更多 8 位值.另一种选择是返回一个字符串 0|1 ...
works but only for 8 bit values ..if the numpy is 9 or more elements it generates 2 or more 8bit values. Another option would be to return a string of 0|1 ...
我目前做的是:
ba = bitarray()
ba.pack(b.astype(np.bool).tostring())
#convert from bitarray 0|1 to integer
result = int( ba.to01(), 2 )
太丑了!!!
推荐答案
一种方法是使用 dot-product 与 2-powered 范围数组 -
One way would be using dot-product with 2-powered range array -
b.dot(2**np.arange(b.size)[::-1])
示例运行 -
In [95]: b = np.array([1,0,1,0,0,0,0,0,1,0,1])
In [96]: b.dot(2**np.arange(b.size)[::-1])
Out[96]: 1285
或者,我们可以使用按位左移运算符来创建范围数组,从而获得所需的输出,就像这样 -
Alternatively, we could use bitwise left-shift operator to create the range array and thus get the desired output, like so -
b.dot(1 << np.arange(b.size)[::-1])
如果对时间感兴趣 -
In [148]: b = np.random.randint(0,2,(50))
In [149]: %timeit b.dot(2**np.arange(b.size)[::-1])
100000 loops, best of 3: 13.1 µs per loop
In [150]: %timeit b.dot(1 << np.arange(b.size)[::-1])
100000 loops, best of 3: 7.92 µs per loop
<小时>
逆向处理
要检索二进制数组,请使用 np.binary_repr 以及 np.fromstring -
To retrieve back the binary array, use np.binary_repr alongwith np.fromstring -
In [96]: b = np.array([1,0,1,0,0,0,0,0,1,0,1])
In [97]: num = b.dot(2**np.arange(b.size)[::-1]) # integer
In [98]: np.fromstring(np.binary_repr(num), dtype='S1').astype(int)
Out[98]: array([1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1])
这篇关于将二进制(0 | 1)numpy转换为整数或二进制字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将二进制(0 | 1)numpy转换为整数或二进制字符串?
基础教程推荐
- matplotlib 设置 yaxis 标签大小 2022-01-01
- 在 Python 中将货币解析为数字 2022-01-01
- Python 中是否有任何支持将长字符串转储为块文字或折叠块的 yaml 库? 2022-01-01
- Kivy 使用 opencv.调整图像大小 2022-01-01
- Python,确定字符串是否应转换为 Int 或 Float 2022-01-01
- 对多索引数据帧的列进行排序 2022-01-01
- 比较两个文本文件以找出差异并将它们输出到新的文本文件 2022-01-01
- kivy 应用程序中的一个简单网页作为小部件 2022-01-01
- 在 Django Admin 中使用内联 OneToOneField 2022-01-01
- 究竟什么是“容器"?在蟒蛇?(以及所有的 python 容器类型是什么?) 2022-01-01
