0
votes

I have a numpy array of shape (120,1). The second dimension is a string of numbers for example:

mat = array([['010000000000000'],
             ['000000000000000']])

So this matrix (mat) is of shape (2,1). I want to change it to shape (2,15) where 15 is length of each string in the array. So the original matrix will become (120,len(string)).

Desired output:

desired = array([[0,1,0,0,0,0,0,0,0,0,0,0,0,0,0],
                    [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]])

How can I achieve this? Insights will be appreciated.

2
Please show corresponding example output. Best if you did it on smaller strings.Gulzar
also it is not clear how 120 became 2. Please show exact input and output on a dummy example.Gulzar
No 120 doesn't become 2. I just as example made an array with just 2 rows. Original matrix has 120 rows. And it is the second dimension that actually changes. I've put the desired output to be more clear.John

2 Answers

1
votes

Cast a string as a list and it will give you a list of characters, then you can use list comprehension like this:

>>> mat = np.array([['010000000000000'],['000000000000000']])
>>> mat = np.array([[list(m2) for m2 in m1][0] for m1 in mat])

>>> mat.shape
(2, 15)

>>> mat
array([['0', '1', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0',
    '0', '0'],
   ['0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0',
    '0', '0']])
0
votes

Simply by using a list comprehension:

>>> mat = np.array([['010000000000000'],
                    ['000000000000000']])

>>> np.array([list(a[0]) for a in mat], dtype=int)

Out[1]: array([[0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
               [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]])