ValueError: could not convert string to float: 'Pregnancies'
ValueError: could not convert string to float: 'Pregnancies'
def loadCsv(filename):
lines = csv.reader(open('diabetes.csv'))
dataset = list(lines)
for i in range(len(dataset)):
dataset[i] = [float(x) for x in dataset[i]
return dataset
你好,我正在尝试实现朴素贝叶斯,但它给了我这个错误,即使我已经手动将每列的类型更改为浮动。
它仍然给我错误。
以上是要转换的函数。
ValueError
是因为代码试图将 CSV header 行中的项目(字符串)转换(转换)为浮点数。您可以跳过 CSV 文件的第一行,例如:
for i in range(1, len(dataset)): # specifying 1 here will skip the first row
dataset[i] = [float(x) for x in dataset[i]
注意:这会将 dataset
中的第一项保留为 headers (str
)。
就个人而言,我会使用 pandas, which has a read_csv()
method, which will load the data directly into a dataframe。
例如:
import pandas as pd
dataset = pd.read_csv('diabetes.csv')
不过,这会给您一个 dataframe
,而不是列表列表。如果你真的想要一个列表列表,你可以使用 dataset.values.tolist()
.
def loadCsv(filename):
lines = csv.reader(open('diabetes.csv'))
dataset = list(lines)
for i in range(len(dataset)):
dataset[i] = [float(x) for x in dataset[i]
return dataset
你好,我正在尝试实现朴素贝叶斯,但它给了我这个错误,即使我已经手动将每列的类型更改为浮动。 它仍然给我错误。 以上是要转换的函数。
ValueError
是因为代码试图将 CSV header 行中的项目(字符串)转换(转换)为浮点数。您可以跳过 CSV 文件的第一行,例如:
for i in range(1, len(dataset)): # specifying 1 here will skip the first row
dataset[i] = [float(x) for x in dataset[i]
注意:这会将 dataset
中的第一项保留为 headers (str
)。
就个人而言,我会使用 pandas, which has a read_csv()
method, which will load the data directly into a dataframe。
例如:
import pandas as pd
dataset = pd.read_csv('diabetes.csv')
不过,这会给您一个 dataframe
,而不是列表列表。如果你真的想要一个列表列表,你可以使用 dataset.values.tolist()
.