Reputation: 169
The text data is like the following:
a1 1 2 3 4 5 6 7 8 9 10
b2 2 3 4 5 6 7 8 9 10 11
c3 3 4 5 6 7 8 9 10 11 12
d4 4 5 6 7 8 9 10 11 12 13
e5 5 6 7 8 9 10 11 12 13 14
f6 6 7 8 9 10 11 12 13 14 15
g7 7 8 9 10 11 12 13 14 15 16
h8 8 9 10 11 12 13 14 15 16 17
i9 9 10 11 12 13 14 15 16 17 18
j10 10 11 12 13 14 15 16 17 18 19
How can I read this text file into np.array without the first column (the first column is the name of each row)? Many thanks.
PS. I tried np.loadtxt("filename") and got " could not convert string to float: b'a' " error
Upvotes: 1
Views: 10898
Reputation: 536
np.loadtxt
should work as long as you know the number of columns.
>>> a = np.loadtxt("file_name", usecols=range(1,11), dtype=np.float32)
>>> a
array([[ 1., 2., 3., 4., 5., 6., 7., 8., 9., 10.],
[ 2., 3., 4., 5., 6., 7., 8., 9., 10., 11.],
[ 3., 4., 5., 6., 7., 8., 9., 10., 11., 12.],
[ 4., 5., 6., 7., 8., 9., 10., 11., 12., 13.],
[ 5., 6., 7., 8., 9., 10., 11., 12., 13., 14.],
[ 6., 7., 8., 9., 10., 11., 12., 13., 14., 15.],
[ 7., 8., 9., 10., 11., 12., 13., 14., 15., 16.],
[ 8., 9., 10., 11., 12., 13., 14., 15., 16., 17.],
[ 9., 10., 11., 12., 13., 14., 15., 16., 17., 18.],
[ 10., 11., 12., 13., 14., 15., 16., 17., 18., 19.]])
Upvotes: 5
Reputation: 1032
import numpy as np
b = []
with open('data.txt') as infile:
lines = infile.readlines()
for line in lines:
for n in line.split()[1:]:
b.append(int(n))
c = np.array(b)
Upvotes: 0