如何将字符串列表从csv文件转换为float?

时间:2016-11-15 21:03:42

标签: python-2.7 list csv matrix

我正在尝试将csv文件读取为这样的矩阵:

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

但是,我需要将列表的内容转换为浮点数。我试图使用

转换为浮动
table = [int(x) for x in table]

但是这出现了错误

  

TypeError:int()参数必须是字符串或数字,而不是'list'

如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

以下是如何将每个行数据转换为float数字类型并进行一些计算的简单示例:

假设CSV数据文件data.csv填充了一些intsfloats

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