-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])
5
  • 3
    Can you share the first few lines of the CSV? So that this is a Minimal, Complete, and Verifiable example. Commented Aug 8, 2018 at 17:14
  • Possible duplicate of How do I parse a string to a float or int in Python? Commented Aug 8, 2018 at 17:15
  • @EvanEdwards May not be the duplicate as OP knows how to parse Commented Aug 8, 2018 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 Commented Aug 8, 2018 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 Commented Aug 8, 2018 at 17:21

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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.