I have a 2d numpy array (type int64) consisting of 1s and 0s.
I want to club up the 1s and 0s of each row in order to be able to convert them to decimal.
arr =
[[0 1 0]
[ 0 0 0]
[ 1 1 1]
[ 0 1 1]]
Desired output (each element is dtype str, to make sure leading zeros are not omitted)
[ 010 , 000 , 111 , 011 ]
How can I manipulate the 2d array to get this output? Is it possible in numpy or re packages, by using their functions? Can a for loop be avoided to do this array transformation?
>Solution :
The question is quite unclear, assuming integers in and out, you could use:
a = np.array([[0, 1, 0],
[0, 0, 0],
[1, 1, 1],
[0, 1, 1]])
out = (a[:,::-1]*(10**np.arange(a.shape[1]))).sum(1)
But you won’t have leading zeros…
output:
array([ 10, 0, 111, 11])
Assuming you really want to convert from binary, you should probably use np.packbits:
out = np.packbits(a, axis=1, bitorder='little')
output:
array([[2],
[0],
[7],
[6]], dtype=uint8)
or as flat version:
out = np.packbits(a, axis=1, bitorder='little').ravel()
# array([2, 0, 7, 6], dtype=uint8)