JupiterOrange
JupiterOrange

Reputation: 349

Convert string to float in Python

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?

Upvotes: 3

Views: 21747

Answers (2)

Burhan Khalid
Burhan Khalid

Reputation: 174718

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']

Upvotes: 4

Blender
Blender

Reputation: 298512

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])

Upvotes: 2

Related Questions