python - 使用 numpy.loadtxt 时无法将字符串转换为 float

标签 python python-3.x numpy machine-learning scikit-learn

代码:

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/

相关文章:

python - Matplotlib 自定义图例以显示正方形而不是矩形

python - 斯塔塔, python : Downloading files from a FTP site in Stata (or in Python)

python - 在 Python 中将日本时间格式 (H29.12.1) 转换为 YYYY-MM-DD 格式?

python-3.x - 用 Python 创建 JSONL

python - Discord.py SSLCertVerificationError

python - 遍历动态数量的 for 循环 (Python)

python - 如何合并 2 个 numpy 数组并连接它们的值?

python - 如何按连接数对查询进行排序

python - 类变量引用本身?

python - 从两个矩阵乘积的条目填充 4d 数组的有效方法