代码:
import csv
import numpy
raw_data = open('C:\\Users\\train.csv', 'rt')
data = numpy.loadtxt(raw_data, delimiter=",")
print(data.shape)
下面是使用的示例数据
Time Freq
8:00 91.1
8:03 91.1
8:06 91.1
8:09 91.1
8:12 91.1
8:15 91.1
8:18 91.1
8:21 91.1
8:24 91.1
8:27 91.1
8:30 91.1
Error:
ValueError: could not convert string to float: b'Time'
最佳答案
In [350]: txt ='''Time Freq
...: 8:00 91.1
...: 8:03 91.1
...: 8:06 91.1
...: 8:09 91.1
...: 8:12 91.1
...: 8:15 91.1
...: 8:18 91.1
...: 8:21 91.1
...: 8:24 91.1
...: 8:27 91.1
...: 8:30 91.1
...: '''
作为结构化数组加载,使用第一行作为字段名称。
In [351]: data = np.genfromtxt(txt.splitlines(),names=True,dtype=None,encoding=N
...: one)
In [352]: data
Out[352]:
array([('8:00', 91.1), ('8:03', 91.1), ('8:06', 91.1), ('8:09', 91.1),
('8:12', 91.1), ('8:15', 91.1), ('8:18', 91.1), ('8:21', 91.1),
('8:24', 91.1), ('8:27', 91.1), ('8:30', 91.1)],
dtype=[('Time', '<U4'), ('Freq', '<f8')])
In [353]: data['Freq']
Out[353]: array([91.1, 91.1, 91.1, 91.1, 91.1, 91.1, 91.1, 91.1, 91.1, 91.1, 91.1])
请注意,第二列已作为数字加载,但第一列作为字符串加载。
关于python - 使用 numpy.loadtxt 时无法将字符串转换为 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50051040/