Turn NumPy Array of characters into a string

拟墨画扇 提交于 2020-12-05 11:16:26

问题


I have a numpy array of characters and when I write it to file it writes as:

['K' 'R' 'K' 'P' 'T' 'T' 'K' 'T' 'K' 'R' 'G' 'L']

I want it to write with just the letters and without the brackets or quotations i.e. as:

KRKPTTKTKRGL 

I have looked at numpy documentation and from what I have gathered the solution is a chararray however it looks like this is not as functional as a normal array.

Any help would be great. Thanks!


回答1:


You can use tostring() method of numpy as:

>>> st = np.array(['K' 'R' 'K' 'P' 'T' 'T' 'K' 'T' 'K' 'R' 'G' 'L'])
>>> st.tostring()
'KRKPTTKTKRGL'

Since you have a numpy array, this method will be faster than join().

For Python3x tostring() can be used as:

>>> st = np.array(['K','R','K','P','T','T','K','T','K','R','G','L'])
>>> st.astype('|S1').tostring().decode('utf-8')
'KRKPTTKTKRGL' 



回答2:


If you just have a numpy array then why not convert it to a string directly for writing to your file? You can do this using str.join which accepts an iterable (list, numpy array, etc).

import numpy as np

arr = np.array(['K', 'R', 'K', 'P', 'T', 'T', 'K', 'T', 'K', 'R', 'G', 'L'])

s = ''.join(arr)
# KRKPTTKTKRGL



回答3:


In a numpy way, you can do:

Using F-String (Only available for Python 3.4+)

s = arr.view(f'U{arr.size}')[0]

Using the default string:

s = arr.view('U' + str(arr.size))[0]

In both, we convert the array into a usable unicode (check the kind attribute at page bottom) format of the size of the array.

Which is the dtype of the string if you try to convert it to numpy.array

In[15]: import numpy as np
In[16]: arr = np.array(['KRKPTTKTKRGL'])
In[17]: arr.dtype
Out[17]: dtype('<U12')

Note: it works with non-English letters.




回答4:


"".join(['K' 'R' 'K' 'P' 'T' 'T' 'K' 'T' 'K' 'R' 'G' 'L'])



回答5:


If you use the tofile() method to save the array to file, the default separator is the empty string "".

So if your array is this,

st = np.array(['K', 'R', 'K', 'P', 'T', 'T', 'K', 'T', 'K', 'R', 'G', 'L'])

then if you're using Python 2,

>>> st.tofile('myfile.txt')

creates a file with the following content:

KRKPTTKTKRGL

If you're using Python 3, you may need to explicitly cast the array to the S string type first:

>>> st.astype('|S1').tofile('myfile.txt')


来源:https://stackoverflow.com/questions/27572219/turn-numpy-array-of-characters-into-a-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!