Reputation: 43
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 ...]]
Upvotes: 4
Views: 7751
Reputation: 69
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]]
Upvotes: 1
Reputation: 9806
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)
Upvotes: 6
Reputation: 2532
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]
Upvotes: 1
Reputation: 8702
this gives out as u required
[bin(x)[2:].zfill(8) for x in a]
out put
['00000001', '00000010', '00000011']
Upvotes: 2