我正在尝试将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'
如何解决这个问题?
答案 0 :(得分:1)
以下是如何将每个行数据转换为float
数字类型并进行一些计算的简单示例:
假设CSV数据文件data.csv
填充了一些ints
和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