1

So I am trying to make sure that all the values that I have in the csv file are converted into float. The values in each cell inside the csv file are just numbers like for example "0.089" "23". For some reason when I try to run the code it is giving the following error, " ValueError: could not convert string to float: '.' " I can not really understand why the program is not reading the numbers from the csv file properly.

def loadCsv(filename):
    with open('BreastCancerTumor.csv','r') as f:
        lines = f.readlines()[1:]
    dataset = list(lines)
    for i in range(len(dataset)):
        dataset[i] = [float(x) for x in dataset[i]]
    return dataset
4
  • 1
    The error message is pretty clear. One of the lines you're converting contains just a decimal point. It doesn't know how to convert . to a float. Commented Nov 11, 2021 at 0:14
  • By the way, did you mean to write dataset[I]? What is I here? Commented Nov 11, 2021 at 0:16
  • lines is already a list, there's no need to write list(lines) Commented Nov 11, 2021 at 0:17
  • I just misspell that, it is [i]. I will try to replace the value that contains just the decimal point for 0. So by doing that I can run the program with no errors. Should that work? Commented Nov 11, 2021 at 0:20

1 Answer 1

1

You never split the line into comma-separated fields. So you're looping over the characters in the line, not the fields, and trying to parse each character as a float. You get an error when you get to the . character.

Use the csv library to read the file, it will split each line into lists of fields.

import csv

def loadCsv(filename):
    with open('BreastCancerTumor.csv','r') as f:
        f.readline() # skip header
        csvf = csv.reader(f):

        dataset = [[float(x) for x in row] for row in csvf]
        return dataset
Sign up to request clarification or add additional context in comments.

1 Comment

Panda's read_csv is also an option.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.