一种方法是使用dot-product
范围2-powered
数组 -
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
或者,我们可以使用按位左移运算符来创建范围数组,从而获得所需的输出,如下所示 -
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
-
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])