0

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.

3
  • Please show corresponding example output. Best if you did it on smaller strings. Commented Jun 14, 2021 at 10:04
  • also it is not clear how 120 became 2. Please show exact input and output on a dummy example. Commented Jun 14, 2021 at 10:05
  • 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. Commented Jun 14, 2021 at 10:09

2 Answers 2

1

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']])
Sign up to request clarification or add additional context in comments.

1 Comment

No need for a nested loop here though, to avoid slowing down your code
0

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]])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.