Search code examples
pythonpython-3.xvalueerrornaivebayes

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

I'm trying to implement Naive-Bayes but its giving me this error even though I've manually changed the type of each column to float. it's still giving me error.

Above is the function to convert.


Solution

  • The ValueError is because the code is trying to cast (convert) the items in the CSV header row, which are strings, to floats. You could just skip the first row of the CSV file, for example:

    for i in range(1, len(dataset)): # specifying 1 here will skip the first row
        dataset[i] = [float(x) for x in dataset[i]
    

    Note: that would leave the first item in dataset as the headers (str).

    Personally, I'd use pandas, which has a read_csv() method, which will load the data directly into a dataframe.

    For example:

    import pandas as pd
    dataset = pd.read_csv('diabetes.csv')
    

    This will give you a dataframe though, not a list of lists. If you really want a list of lists, you could use dataset.values.tolist().