How to convert a vector of integers into a matrix of binary representation with NumPy?

Viewed 444

Suppose I have the following array:

import numpy as np
I = np.array([0, 1, 2, 3, 15, 16, 32, 64, 128])

I would like to convert each item in the array into its binary representation.

Desired output:

[[0 0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0 1]
 [0 0 0 0 0 0 1 0]
 [0 0 0 0 0 0 1 1]
 [0 0 0 0 1 1 1 1]
 [0 0 0 1 0 0 0 0]
 [0 0 1 0 0 0 0 0]
 [0 1 0 0 0 0 0 0]
 [1 0 0 0 0 0 0 0]]

Whats the most straight forward way to do this? Thanks!

3 Answers

There are many ways you can accomplish this.

One way to do it:

# Your array
I = np.array([0, 1, 2, 3, 15, 16, 32, 64, 128])

B = ((I.reshape(-1,1) & (2**np.arange(8))) != 0).astype(int)
print(B[:,::-1])

You can also do this:

I = np.array([0, 1, 2, 3, 15, 16, 32, 64, 128], dtype=np.uint8)
print(np.unpackbits(I[:, np.newaxis], axis=1))

I personalty would recommend the first method! Cheers!

np.array([[int(d) for d in '{0:08b}'.format(el)] for el in I])

This should give you the desired output, {0:08b} gives you the binary representation of your number consisting of 8 digits as a string, in a second list comprehension the binary number is split into digits and then result is converted to a numpy array.

You can use bin() function to convert an integer to a binary string.

One of the possible solution can be:

[list(bin(num)[2:].zfill(8)) for num in I ]

Here I am using list comprehension for iterating over the array and then for each number in the array, I am applying bin function to convert it to the binary string. Then I am using zfill(8) to add zeros at the beginning of the string to make it of length 8, as required by your output format. Then it is typecasted into a list.

Related