En fait, np.loadtxt
ne peut pas gérer cette première rangée séparément très bien, donc vous devez faire quelque chose intelligent. Je vais vous donner deux façons, la première est plus courte, mais le second est plus straighforward
1), vous pouvez le faire « hack » en lisant la première ligne en tant que noms tête :
y_and_data = np.genfromtxt('131014-data-xy-conv-1.txt', names=True, delimiter=',')
x = np.array(y_and_data.dtype.names[1:], int)
y = y_and_data['YX_mm']
data = y_and_data.view(np.float).reshape(-1, len(y_and_data.dtype))[:,1:]
2) Mais je vous recommande de lire simplement la première ligne d'abord séparément, enregistrez-le, puis ouvrez le reste avec loadtxt
(ou genfromtxt
comme je l'ai utilisé et recommander):
with open('131014-data-xy-conv-1.txt', 'r') as f:
x = np.array(f.readline().split(',')[1:], int)
y_and_data = np.genfromtxt(f, delimiter=',')
y = y_and_data[:,0]
data = y_and_data[:,1:]
Comment ça marche, ouvrez le fichier et appelez-le f
:
with open('131014-data-xy-conv-1.txt', 'r') as f:
firstline = f.readline() # read off the first line
firstvalues = firstline.split(',') # split it on the comma
xvalues = firstvalues[1:] # and keep the all but the first elements
x = np.array(xvalues, int) # make it an array of integers (or float if you prefer)
Maintenant que la première ligne a été lu à partir f
à l'aide f.readline
, le reste peut être lu avec genfromtxt
:
y_and_data = np.genfromtxt(f, delimiter=',')
Maintenant, les autres réponses montrent comment diviser le reste:
y = y_and_data[:,0] # the first column is the y-values
data = y_and_data[:,1:] # the remaining columns are the data
Et voici la sortie:
In [58]: with open('131014-data-xy-conv-1.txt', 'r') as f:
....: x = np.array(f.readline().split(',')[1:], int)
....: y_and_data = np.genfromtxt(f, delimiter=',')
....: y = y_and_data[:,0]
....: data = y_and_data[:,1:]
....:
In [59]: x
Out[59]: array([ 0, 10, 20, 30, 40])
In [60]: y
Out[60]:
array([ 686.6 , 694.08, 701.56, 709.04, 716.52, 724. , 731.48,
738.96, 746.44, 753.92, 761.4 , 768.88, 776.36])
In [61]: data
Out[61]:
array([[ -5.02 , -0.417, 0. , 100.627, 0. ],
[ -5.02 , -4.529, -17.731, -5.309, -3.535],
[ 1.869, -4.529, -17.731, -5.309, -3.535],
[ 1.869, -4.689, -17.667, -5.704, -3.482],
[ 4.572, -4.689, -17.186, -5.704, -2.51 ],
[ 4.572, -4.486, -17.186, -5.138, -2.51 ],
[ 6.323, -4.486, -16.396, -5.138, -1.933],
[ 6.323, -4.977, -16.396, -5.319, -1.933],
[ 7.007, -4.251, -16.577, -5.319, -1.688],
[ 7.007, -4.251, -16.577, -5.618, -1.688],
[ 7.338, -3.514, -16.78 , -5.618, -1.207],
[ 7.338, -3.514, -16.78 , -4.657, -1.207],
[ 7.263, -3.877, -15.99 , -4.657, -0.822]])
Je ne pense pas que ce soit le format de l'OP. La deuxième colonne ne contient pas de données Y, elle contient le premier ylabel, puis les données. – DSM
Vous ne pouvez pas ignorer la première ligne, elle contient les données x. – askewchan
Merci. La réponse est mise à jour. – bogatron