0

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)
martineau
  • 119,623
  • 25
  • 170
  • 301
Angela Mary
  • 49
  • 1
  • 8
  • Does this answer your question? [ValueError: could not convert string to float: id](https://stackoverflow.com/questions/8420143/valueerror-could-not-convert-string-to-float-id) – Mark Jul 04 '21 at 22:13
  • There's an empty line or line with empty fields in the CSV file. – Barmar Jul 04 '21 at 22:18
  • Where's the snippet of the csv file being read? – martineau Jul 04 '21 at 22:25
  • Try using `col1.append( float(line[0]) if line[0] else 0.0 )` instead of what you have. Do something similar for `col2`. – martineau Jul 04 '21 at 22:37

2 Answers2

1

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
    
-1

Maybe you forgot to add .split(',')? Right now, line[0] and line[1] simply take the first and second character of the line.