使用适当的填充将整数转换为二进制数组 [英] Convert integer to binary array with suitable padding

查看:59
本文介绍了使用适当的填充将整数转换为二进制数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的整数范围为0..2**m - 1,我想将它们转换为长度为m的二进制numpy数组.例如,说m = 4.现在15 = 1111为二进制,因此输出应为(1,1,1,1). 2 = 10为二进制,因此输出应为(0,0,1,0).如果m3,则2应该转换为(0,1,0).

I have integers in the range 0..2**m - 1 and I would like to convert them to binary numpy arrays of length m. For example, say m = 4. Now 15 = 1111 in binary and so the output should be (1,1,1,1). 2 = 10 in binary and so the output should be (0,0,1,0). If m were 3 then 2 should be converted to (0,1,0).

我尝试了np.unpackbits(np.uint8(num)),但是没有给出正确长度的数组.例如

I tried np.unpackbits(np.uint8(num)) but that doesn't give an array of the right length. For example,

np.unpackbits(np.uint8(15))
Out[5]: array([0, 0, 0, 0, 1, 1, 1, 1], dtype=uint8)

我想要一种适用于代码中所有m的方法.

I would like a method that worked for whatever m I have in the code.

推荐答案

您应该能够对此向量化,例如

You should be able to vectorize this, something like

>>> d = np.array([1,2,3,4,5])
>>> m = 8
>>> (((d[:,None] & (1 << np.arange(m)))) > 0).astype(int)
array([[1, 0, 0, 0, 0, 0, 0, 0],
       [0, 1, 0, 0, 0, 0, 0, 0],
       [1, 1, 0, 0, 0, 0, 0, 0],
       [0, 0, 1, 0, 0, 0, 0, 0],
       [1, 0, 1, 0, 0, 0, 0, 0]])

仅获取适当的比特权重,然后按位进行取和:

which just gets the appropriate bit weights and then takes the bitwise and:

>>> (1 << np.arange(m))
array([  1,   2,   4,   8,  16,  32,  64, 128])
>>> d[:,None] & (1 << np.arange(m))
array([[1, 0, 0, 0, 0, 0, 0, 0],
       [0, 2, 0, 0, 0, 0, 0, 0],
       [1, 2, 0, 0, 0, 0, 0, 0],
       [0, 0, 4, 0, 0, 0, 0, 0],
       [1, 0, 4, 0, 0, 0, 0, 0]])

有很多方法可以将其转换为非零的(> 0)*1.astype(bool).astype(int)等.我基本上是随机选择一个.

There are lots of ways to convert this to 1s wherever it's non-zero (> 0)*1, .astype(bool).astype(int), etc. I chose one basically at random.

这篇关于使用适当的填充将整数转换为二进制数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆