将二进制(0 | 1)numpy转换为整数或二进制字符串?

2022-01-09 00:00:00 python numpy binary bitstring

问题描述

是否有将二进制 (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-product2-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])

相关文章