Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Collating row entries in 2D array

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading