简体   繁体   中英

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:

[['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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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