Convert integer to binary array with suitable padding

后端 未结 4 1606
不思量自难忘°
不思量自难忘° 2020-12-05 20:29

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.

4条回答
  •  [愿得一人]
    2020-12-05 20:42

    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]])
    

    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.

提交回复
热议问题