Search code examples
pythoncsvvalueerror

Could not convert string to float error while using csv files


I'm trying to load the two coluns of my csv files into an array in python. However I am getting:

ValueError: could not convert string to float: ''.

I have attached the snippets of the code implemented and the csv file I'm trying to store in an array.

import csv


col1 = []
col2 = []
path = r'C:\Users\angel\OneDrive\Documents\CSV_FILES_NV_LAB\1111 x 30.csv'
with open(path, "r") as f_in:
    reader = csv.reader(f_in)
    next(reader)  # skip headers

    for line in reader:
        col1.append(float(line[0]))
        col2.append(float(line[1]))

print(col1)
print(col2)

Solution

  • What values are in the CSV file? If the values cannot be converted to floats, you will get the ValueError. For example, if your CSV file looks like this:

    ColName,ColName2
    abc,def
    123,45.6
    g,20
    

    the error will be raised on the first iteration of your loop because abc cannot be converted to a float. If, however, all the values in the CSV file are numbers:

    ColName, ColName2
    1,2
    123,45.6
    100,20
    

    the error will not be raised.

    If you have some numeric and some non-numeric values in the CSV file, you can omit the lines containing non-numeric values by including a try...except block in your loop:

    for line in reader:
        try:
            float_1, float_2 = float(line[0]), float(line[1])
            
            # If either of the above conversions failed, the next two lines will not be reached
            col1.append(float_1)
            col2.append(float_2)
    
        except ValueError:
            continue  # Move on to next line