E OC
E OC

Reputation: 21

How to convert a string list from csv file to float?

I am trying to read a csv file as a matrix like this:

import csv
with open("data.csv", "r") as file:
    table = [line for line in csv.reader(file)]
    for line in table:
        print(line)

But, I need to convert the content of the lists to floats. i tried to convert to float using

table = [int(x) for x in table]

however this comes up as an error

TypeError: int() argument must be a string or a number, not 'list'

How can fix this?

Upvotes: 2

Views: 1745

Answers (1)

Christos Lytras
Christos Lytras

Reputation: 37318

Here is a simple example how to convert each line data to float numeric type and do some calculations:

Assuming CSV data file data.csv is filled with some ints and floats:

12,13,14,15,16
0.1,0.2,0.3,0.4,0.5
import csv
with open("./data.csv", "rU") as file:
    table = [line for line in csv.reader(file)]
    for line in table:
        numbers = [ float(x) for x in line ]
        sum = 0
        for number in numbers:
            sum = sum + number
        print(numbers)
        print "The sum of numbers is: ", sum

OUPUTS:

[12.0, 13.0, 14.0, 15.0, 16.0]
The sum of numbers is:  70.0
[0.1, 0.2, 0.3, 0.4, 0.5]
The sum of numbers is:  1.5

Upvotes: 1

Related Questions