3

I have a csv file and I am trying to plot some of the contents and need to convert the strings to floats. My problem is the following:

When I run the code below,

with open('meteors.csv', 'rU') as csvfile:
    reader=csv.reader(csvfile)
    for row in reader:    
        print row[6]

I get this output:

58.58333

When I instead try

print type(row[6])

I get this output:

<type 'str'>

But when I try

 print float(row[6])

I get this error:

ValueError: could not convert string to float: coordinate_1

Anyone know what's going on?

7
  • Is there some form of terminator on the end of the string such as \n, \t etc...? Commented Apr 23, 2013 at 4:43
  • not sure. Is there a way to check? Commented Apr 23, 2013 at 4:44
  • I reckon there probably is but I'm not sure of it sorry. Maybe @jamylak can help, he seems to have a clue about most python stuff Commented Apr 23, 2013 at 4:48
  • 1
    @TheMerovingian You mean like repr(s) Commented Apr 23, 2013 at 4:53
  • 1
    @user1571767: There you go, try print(repr(row[6])) and it should print out the raw string showing all terminating characters Commented Apr 23, 2013 at 4:56

2 Answers 2

4

Most likely you are seeing the first row, which has the column headers on your CSV file, and coordinate_1 is a header.

You can either skip the first row:

with open('meteors.csv', 'rU') as csvfile:
    reader=csv.reader(csvfile)
    reader.next() # skips the first (header) row
    for row in reader:    
        print row[6]

Or, use DictReader, like this:

with open('meteors.csv', 'rU') as csvfile:
    reader=csv.DictReader(csvfile)
    for row in reader:    
        print row['coordinate_1']
Sign up to request clarification or add additional context in comments.

1 Comment

@BurhanKhalid you should also use next() function instead for the reason I specified on the other answer. Otherwise yes this is the cleaner way
2

Your CSV file probably has a header that lists the name of each column. You can't convert those names into floats, so that's where your error is coming from.

You have to consume the header first:

with open('meteors.csv', 'rU') as csvfile:
    reader = csv.reader(csvfile)
    header = next(reader)

    for row in reader:
        print float(row[6])

2 Comments

yes because they change .next to the special method .__next__, since the function next was supposed to be used when it was created
@jamylak: Ah, I never knew that. Thanks.

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.