4

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

5 Answers 5

6

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)
Sign up to request clarification or add additional context in comments.

Comments

2

Try this.

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

3 Comments

This is the fastest solution so far
This gives ValueError: cannot reshape array of size 1 into shape (1,16) on Python 3 and numpy 1.21.5.
@MichaelHerrmann you may be interested in np.unpackbits(a).reshape(*a.shape,8). The 8 is for uint8. Replace with the number of bits in your dtype.
2

this gives out as u required

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

out put

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

2 Comments

This works perfectly.Thanks.. It is taking similar time to using vectorize.
pls make it tick .. and ote up:)
1

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]

2 Comments

Second one throws "TypeError: argument 2 to map() must support iteration"
I think your array is not 2d. In your question you use two brackets [[]].
1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.