感谢您的问题,感谢Roman提供答案。我花了一些时间才找到这个信息,希望以下内容对其他人有所帮助。
Python 2.7
参见:https://docs.scipy.org/doc/numpy/user/basics.io.genfromtxt.html
import numpy as np
from StringIO import StringIO
data = "1, abc , 2\n 3, xxx, 4"
print type(data)
"""
<type 'str'>
"""
print '\n', np.genfromtxt(StringIO(data), delimiter=",", dtype="|S3", autostrip=True)
"""
[['1' 'abc' '2']
['3' 'xxx' '4']]
"""
print '\n', type(data)
"""
<type 'str'>
"""
print '\n', np.genfromtxt(StringIO(data), delimiter=",", autostrip=True)
"""
[[ 1. nan 2.]
[ 3. nan 4.]]
"""
Python 3.5:
import numpy as np
from io import StringIO
import io
data = "1, abc , 2\n 3, xxx, 4"
"""
1, abc , 2
3, xxx, 4
"""
"""
<class 'str'>
"""
print('\n')
print(np.genfromtxt(io.BytesIO(data.encode()), delimiter=",", dtype="|S3", autostrip=True))
"""
[[b'1' b'abc' b'2']
[b'3' b'xxx' b'4']]
"""
print('\n')
print(np.genfromtxt(io.BytesIO(data.encode()), delimiter=",", autostrip=True))
"""
[[ 1. nan 2.]
[ 3. nan 4.]]
"""
提示:
dtype="|Sx",其中x = {1, 2, 3, ...} 中的任意数字:
dtypes. Difference between S1 and S2 in Python
"|S1和|S2字符串是数据类型描述符;第一个表示数组包含长度为1的字符串,第二个表示长度为2的字符串。..."
from io import StringIO
。 - Oleh PrypinStringIO
已经被删除,应该改为导入from io import BytesIO
。我在Python 3.5环境下进行了测试,使用了eclipse pyDev和win7 x64。如果我有错误,请告诉我。谢谢。 - Bill Huang