Skip to content Skip to sidebar Skip to footer

Why Is Python Showing 'valueerror: Could Not Convert String To Float'?

I have a CSV containing numbers which I am trying to convert to floats. filename = 'filename.csv' enclosed_folder = 'path/to/Folder' full_path = os.path.join(enclosed_folder,filena

Solution 1:

The error is due to your line parsing. You are separating on spaces, not commas, which is what should happen according to your screenshot. The key is looking at the error returned. It is trying to convert the entire line from a string into a float.

Change:

matrix = [x.split(" ") for x in temp]

To:

matrix = [x.split(",") for x in temp]

Solution 2:

you can use strip() to remove whitespaces from the string.

matrix[i][j] = float(matrix[i][j].strip())

If the commas are troubling you, you might want to .split(',') with commas and not spaces:

matrix = [x.strip().split(",") for x in temp]

Solution 3:

Remove the newline char with rstrip() like this:

matrix[i][j] = float(matrix[i][j].rstrip())

Post a Comment for "Why Is Python Showing 'valueerror: Could Not Convert String To Float'?"