2016-09-19 4 views
3

と仮定、私はn要素とnumpyベクトルを持っているので、私は形状がmは、例えばlog2(maxnumber)ある(n,m)となり得、バイナリ表記として、このベクターの番号を符号化したい:numpyのバイナリ表記迅速世代

私が持っている最大数が 67ある
x = numpy.array([32,5,67]) 

ため、結果の形状になるように、私は、このベクトルを符号化するためにnumpy.ceil(numpy.log2(67)) == 7ビットを必要(3,7)

array([[1, 0, 0, 0, 0, 1, 1], 
     [0, 0, 0, 0, 1, 0, 1], 
     [0, 1, 0, 0, 0, 0, 0]]) 

私はすぐにバイナリ表記を
関数numpy.binary_reprからnumpy配列に移動することができないため、問題が発生します。今、私は結果を反復処理する必要がある、と別々に各ビットを置く:

brepr = numpy.binary_repr(x[i],width=7) 
j = 0 
for bin in brepr: 
    X[i][j] = bin 
    j += 1 

それが効率的にするためにどのように、非常にtimecostと愚かな方法ですか?

+0

http://stackoverflow.com/questions/22227595/convert-integer-to-binary-arrayを参照してください:あなたが手に持っている場合については

- 適切なパディングあり –

答えて

3

ここで私たちnp.unpackbitsと放送を使って片道:

>>> max_size = np.ceil(np.log2(x.max())).astype(int) 
>>> np.unpackbits(x[:,None].astype(np.uint8), axis=1)[:,-max_size:] 
array([[0, 1, 0, 0, 0, 0, 0], 
     [0, 0, 0, 0, 1, 0, 1], 
     [1, 0, 0, 0, 0, 1, 1]], dtype=uint8) 
1

あなたがnumpyのバイト文字列を使用することができます。

res = numpy.array(len(x),dtype='S7') 
for i in range(len(x)): 
    res[i] = numpy.binary_repr(x[i]) 

以上のコンパクト

res = numpy.array([numpy.binary_repr(val) for val in x])