Grazie OP per la tua domanda e Roman per la tua risposta. Ho dovuto cercare un po 'per trovare questo; Spero che quanto segue aiuti gli altri.
Python 2,7
See: https://docs.scipy.org/doc/numpy-dev/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"
#print(data)
"""
1, abc , 2
3, xxx, 4
"""
#print(type(data))
"""
<class 'str'>
"""
#np.genfromtxt(StringIO(data), delimiter=",", autostrip=True)
# TypeError: Can't convert 'bytes' object to str implicitly
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.]]
"""
parte:
DTYPE = "| Sx", dove x = qualsiasi {1, 2, 3, ...}:
dtypes. Difference between S1 and S2 in Python
"L'| S1 e | S2 stringhe sono dati di tipo descrittori; Il primo mezzo della matrice contiene stringhe di lunghezza 1, il secondo di lunghezza 2. ..."
Vale la pena menzionare questi non sono gli stessi, in modo da poter finire con 'TypeError's (argomento stringa previsto, ottenuto 'byte') se si effettua questa modifica in isolamento. È necessario distinguere attentamente btyes e str (unicode) in python 3. –
Per i newb come me: da io import StringIO significa che lo si chiama come StringIO(), non io.StringIO(). – Noumenon
Come effettivamente essere compatibile con Python 2 e 3: solo 'da io import StringIO' –