問題描述
是否有將二進制 (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
或者,我們可以使用按位左移運算符來創(chuàng)建范圍數組,從而獲得所需的輸出,就像這樣 -
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轉換為整數或二進制字符串?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!