Home > OS >  Collating row entries in 2D array
Collating row entries in 2D array

Time:06-29

I have a 2d numpy array consisting of 1s and 0s. I want to club up the 1s and 0s of each row.

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 regex packages, by using their functions? Can a for loop be avoided to do this array transformation?

CodePudding user response:

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(np.pad(a, ((0,0), (8-a.shape[1],0))), axis=1, bitorder='big')

output:

array([[2],
       [0],
       [7],
       [3]], dtype=uint8)

or as flat version:

out = (np.packbits(np.pad(a, ((0,0), (8-a.shape[1],0))), axis=1, bitorder='big')
         .ravel()
       )
# array([2, 0, 7, 3], dtype=uint8)

CodePudding user response:

Using strings:

import numpy as np

arr = np.array([[0,  1,  0], [ 0,  0,  0], [ 1,  1,  1], [ 0,  1,  1]])

binaries = []
for idx, row in enumerate(arr):
    strings = [str(integer) for integer in row]
    a_string = "".join(strings)
    binaries.append(a_string)

>>> binaries
>>> ['010', '000', '111', '011']
  • Related