Python 3.x 在python中按列追加二进制值
我希望字符串的二进制值以列方式存储在数组中Python 3.x 在python中按列追加二进制值,python-3.x,numpy,multidimensional-array,character-encoding,Python 3.x,Numpy,Multidimensional Array,Character Encoding,我希望字符串的二进制值以列方式存储在数组中 st = "hello world" st = st.encode('utf-8') # binary value for letter 'h' bin(st[0]) -> '0b1101000' # binary value for letter 'e' bin(st[1]) -> '0b1100101' 等等 我想将这些二进制字符串存储在数组中,如下所示: 0 1 0 0 0 1 1 0 0 0 1 1 1 1 b
st = "hello world"
st = st.encode('utf-8')
# binary value for letter 'h'
bin(st[0]) -> '0b1101000'
# binary value for letter 'e'
bin(st[1]) -> '0b1100101'
等等
我想将这些二进制字符串存储在数组中,如下所示:
0 1
0 0
0 1
1 0
0 0
1 1
1 1
b b
0 0
谢谢,
Neeraj您可以使用
np.fromstring
和np.unpackbits
:
>>> a = np.unpackbits(np.fromstring(st, np.uint8)).reshape((8, -1), order='F')[::-1]
>>> a
array([[0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 1, 1, 1, 0, 0],
[0, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1],
[1, 0, 1, 1, 1, 0, 0, 1, 0, 1, 0],
[0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=uint8)
这不包含b
字符。如果您必须拥有:
>>> np.r_['0,2,1', a.astype('U1')[:7], np.full(a.shape[1], 'b'), np.full(a.shape[1], '0')]
array([['0', '1', '0', '0', '1', '0', '1', '1', '0', '0', '0'],
['0', '0', '0', '0', '1', '0', '1', '1', '1', '0', '0'],
['0', '1', '1', '1', '1', '0', '1', '1', '0', '1', '1'],
['1', '0', '1', '1', '1', '0', '0', '1', '0', '1', '0'],
['0', '0', '0', '0', '0', '0', '1', '0', '1', '0', '0'],
['1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1'],
['1', '1', '1', '1', '1', '0', '1', '1', '1', '1', '1'],
['b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b'],
['0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0']],
dtype='<U1')
np.r_['0,2,1',a.astype('U1')[:7],np.full(a.shape[1],'b'),np.full(a.shape[1],'0')]
数组([[0',1',0',0',1',0',1',1',0',0',0'],
['0', '0', '0', '0', '1', '0', '1', '1', '1', '0', '0'],
['0', '1', '1', '1', '1', '0', '1', '1', '0', '1', '1'],
['1', '0', '1', '1', '1', '0', '0', '1', '0', '1', '0'],
['0', '0', '0', '0', '0', '0', '1', '0', '1', '0', '0'],
['1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1'],
['1', '1', '1', '1', '1', '0', '1', '1', '1', '1', '1'],
['b','b','b','b','b','b','b','b','b','b'],
['0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0']],
dtype='1