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:
我想将它转换为2d numpy数组,如下所示:
[['F' 'A' 'D' 'V' 'A' 'G']
['X' 'X' 'D' 'X' 'F' 'A']
['G' 'D' 'X' 'X' '.' '.']]
How can I do that?
我怎样才能做到这一点?
2 个解决方案
#1
1
list('astring')
splits up the characters:
list('astring')拆分字符:
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)
#2
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')
#1
1
list('astring')
splits up the characters:
list('astring')拆分字符:
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)
#2
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')