-1

I am trying to convert text from a csv file to a floating point number. But i keep getting the error: ValueError: could not convert string to float: year. I am getting the same error when trying to convert to int. The number that is imported is 2018.0

 import csv
 with open('test_csv.csv', 'rb') as data_file:
      data = csv.reader(data_file, delimiter=',')
      for i in data:
         year  = float(i[0])
  • 3
    Can you share the first few lines of the CSV? So that this is a [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve). – Alex Aug 08 '18 at 17:14
  • Possible duplicate of [How do I parse a string to a float or int in Python?](https://stackoverflow.com/questions/379906/how-do-i-parse-a-string-to-a-float-or-int-in-python) – Evan Edwards Aug 08 '18 at 17:15
  • @EvanEdwards May not be the duplicate as OP knows how to parse – mad_ Aug 08 '18 at 17:16
  • 2
    There is likely some hidden character or something, can you print `repr(i)` and make sure it is just `2018.0` – bison Aug 08 '18 at 17:17
  • Are you sure that the index you point to is ALWAYS in the format you expect it to be? Please provide the format of the CSV file – Riley Hughes Aug 08 '18 at 17:21

2 Answers2

1

Based on the error message you're getting, your issue is probably with the first line of your CSV. You haven't actually shared the contents of the file, but if I had to guess, it looks like this:

year,  some_value,    some_value,    ...
2018,  ...       ,    ...       ,    ...
2017,  ...       ,    ...       ,    ...

Your code is getting tripped up with the year that's on the first line of your CSV. The solution, then, is probably to skip that first line, or use a DictReader instead of a reader.

Green Cloak Guy
  • 23,793
  • 4
  • 33
  • 53
0

Try this:

 import csv
 with open('test_csv.csv', 'rb') as data_file:
      data = csv.reader(data_file, delimiter=',')
      for i in data:
         try:
             year  = float(i[0])
         except ValueError as e:
             print("Couldn't convert the following line {0}".format(i))

You probably have either a last empty line, (which creates a one empty cell array and cannot be converted) or a wrong row in your file.

OMY
  • 402
  • 1
  • 8
  • 18