简体   繁体   English

numpy:创建一个二维numpy数组,其中的每一行都填充有常规数组中的字符串

[英]numpy: create a 2d numpy array where each row is filled with strings from a regular array

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: 我想将其转换为二维numpy数组,如下所示:

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

How can I do that? 我怎样才能做到这一点?

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)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM