Question

I have a following numpy array

a = np.array([[1,2,3,4 ,11, 12,13,14,21,22,23,24,31,32,33,34 ]], dtype=uint8)

when I print a i am getting the following output

[[ 1  2  3  4 11 12 13 14 21 22 23 24 31 32 33 34]]

How can i get the output in binary representation?

for example

[[ 00000001  00000010  00000011  00000100 ...]]
Was it helpful?

Solution 2

Try this.

np.array(map(bin, a.flatten())).reshape(a.shape)

OTHER TIPS

You can use numpy.binary_repr

It takes a number as input and returns its binary representation as a string. You can vectorize this function so that it can take an array as input:

np.vectorize(np.binary_repr)(a, width=8)

this gives out as u required

[bin(x)[2:].zfill(8) for x in a]

out put

['00000001', '00000010', '00000011']

How about this?

a = np.array([[1,2,3,4 ,11, 12,13,14,21,22,23,24,31,32,33,34 ]], dtype=uint8)
print [bin(n) for n in a[0]]

Using numpy's unpackbits, this can work too.

A=np.unpackbits(a, axis=0).T
print [''.join(map(str,a)) for a in A]

For uint8 you can use the builtin numpy function unpackbits. (As mentioned by @ysakamoto) First reshape array so it is 1 column wide. After that use unpackbits as stated below.

a = numpy.array([[1,2,3,4 ,11, 12,13,14,21,22,23,24,31,32,33,34 ]], dtype="uint8")
print(numpy.unpackbits(a.reshape(-1,1), axis=1))

output:

[[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, 0, 1, 0, 0],
[0, 0, 0, 0, 1, 0, 1, 1],
[0, 0, 0, 0, 1, 1, 0, 0],
[0, 0, 0, 0, 1, 1, 0, 1],
[0, 0, 0, 0, 1, 1, 1, 0],
[0, 0, 0, 1, 0, 1, 0, 1],
[0, 0, 0, 1, 0, 1, 1, 0],
[0, 0, 0, 1, 0, 1, 1, 1],
[0, 0, 0, 1, 1, 0, 0, 0],
[0, 0, 0, 1, 1, 1, 1, 1],
[0, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0, 0, 1],
[0, 0, 1, 0, 0, 0, 1, 0]]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top