epic556
epic556

Reputation: 79

Turning flat array values into column vectors

I have an array of base 3 numbers expressed as strings:

['1', '2', '10']

I want to 0 pad each number such that the max spaces taken up by each is three.

['001', '002', '010']

And then convert it to a matrix which is the following:

[[0, 0, 0],
[0, 0, 1],
[1, 2, 0]]

That is, to convert each string entry into a column vector. I've tried rotation, transpose, and not sure what the best way to do this is.

Thanks

Upvotes: 3

Views: 74

Answers (4)

rnso
rnso

Reputation: 24613

Try following code. Explanation is added as comments:

lst = ['1', '2', '10']       # input list
outlist = []                 # empty output list
for i in lst:
    while len(i) <3:
        i = '0'+i           # add leading 0s
    outlist.append(list(i)) # string converted to list and added to output list

# convert to np.array, then to integers, transpose and convert back to list:
outlist = np.array(outlist).astype(np.int).T.tolist()    
print(outlist)

Output:

[[0, 0, 0], [0, 0, 1], [1, 2, 0]]

Upvotes: 0

Kasravnd
Kasravnd

Reputation: 107347

Use str.zfill to pad with zeros and then np.dstack to convert the the expected format:

In [106]: np.dstack([list(i.zfill(3)) for i in a])[0].astype(np.int)
Out[106]: 
array([[0, 0, 0],
       [0, 0, 1],
       [1, 2, 0]])

Upvotes: 3

Paul Panzer
Paul Panzer

Reputation: 53089

You can use the numpy.char module which provides vectorized versions of many string operations:

>>> import numpy as np
>>> 
>>> a = np.array((1,2,10),'U2')
>>> a
array(['1', '2', '10'],
      dtype='<U2')
>>> 
>>> b = np.char.zfill(a, 3)
>>> b
array(['001', '002', '010'],
      dtype='<U3')
>>> 
>>> c = b.view('U1').reshape(3, 3).T.astype(int)
>>> c
array([[0, 0, 0],
       [0, 0, 1],
       [1, 2, 0]])

Upvotes: 1

jpp
jpp

Reputation: 164783

Here's one way. I haven't split apart the intermediary step, but that's easily done.

lst = ['1', '2', '10']
result = list(zip(*(map(int, i.zfill(3)) for i in lst)))

If you want a numpy array:

import numpy as np
arr = np.array(result)

# array([[0, 0, 0],
#        [0, 0, 1],
#        [1, 2, 0]])

Upvotes: 3

Related Questions