0

I have a regular list filled with strings of equal length:

['FADVAG', 'XXDXFA', 'GDXX..']

I want to transform it into a 2d numpy array, like the following:

[['F' 'A' 'D' 'V' 'A' 'G']
['X' 'X' 'D' 'X' 'F' 'A']
['G' 'D' 'X' 'X' '.' '.']]

How can I do that?

2 Answers 2

1

list('astring') splits up the characters:

In [187]: alist=['FADVAG', 'XXDXFA', 'GDXX..']
In [188]: arr = np.array([list(a) for a in alist])
In [189]: arr
Out[189]: 
array([['F', 'A', 'D', 'V', 'A', 'G'],
       ['X', 'X', 'D', 'X', 'F', 'A'],
       ['G', 'D', 'X', 'X', '.', '.']],
      dtype='<U1')

If you want to avoid a list comprehension, join them into one string and go from there

np.array(list(''.join(alist))).reshape(3,-1)
Sign up to request clarification or add additional context in comments.

1 Comment

(3,-1) - 3 rows, -1 means what ever works. Short hand for calculate the remaining dimension.
0

try below code:

import numpy as np
l = ['FADVAG', 'XXDXFA', 'GDXX..']
l = np.array(l)
l.reshape(len(l),-1)

output:

array([['FADVAG'],
       ['XXDXFA'],
       ['GDXX..']],
      dtype='<U6')

2 Comments

can't you able to reproduce your output as given by removing dtype
@Argus I think it is not possible to remove a dtype from numpy array as every ndarray must have a dtype

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.