【发布时间】:2014-04-10 03:12:11
【问题描述】:
我有以下格式的 csv 文件
a b c d
1 12.0 3.5 4.3 5.9
2 13.0 5.7 2.8 5.2
3 14.0 6.4 9.7 2.3
4 15.0 6.8 4.7 3.4
我想将行导出到数组的 python 数组中。这是伪代码:
a = read csv
b[][] = a float 2d array that is 1x4
import rows into b
the output of b should be:
[[12.0,3.5,4.3,5.9],[13.0,5.7,2.8,5.2],[14.0,6.4,9.7,2.3],[15.0,6.8,4.7,3.4]]
我该怎么做?如果您需要任何其他说明,请告诉我。谢谢。
问题: 所有行的大小不同。有些行有 10 个元素,而其他行可能有 7 个或 8 个或 9 个。
这就是我所拥有的:
import csv
def main():
a = range(4)
x = 0
with open('test.csv', 'rb') as csvfile:
spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|')
for row in spamreader:
a[x] = row
x += 1
print a
输出:
[['13,4.2,2.4,5,6.4'], ['14,3.2,3.4,5.6,7.2'], ['15,8.5,3.7,8.5,0.75'], ['16,5.4,8.3,3.5,5.4']]
如何让数组从字符串变成浮点数?
【问题讨论】: