CSV行导入蟒蛇阵 [英] csv row import into python array

查看:149
本文介绍了CSV行导入蟒蛇阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下格式的CSV文件

I have csv file in the following format

   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

我要行导出到阵列的蟒蛇数组。这里是伪code:

I want to export rows into a python array of arrays. Here is the pseudocode:

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

我会怎么做呢?请让我知道如果你需要任何其他说明。谢谢你。

how would I do this? Please let me know if you need any other clarification. Thank you.

问题:
所有行的大小不同。某些行有10个元素和其他人可能有7或8或9。

Problems: all rows are NOT of same size. some rows have 10 elements and others may have 7 or 8 or 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']]

我如何使阵列转从字符串转换成花车?

How do I make the arrays turn from string into floats?

推荐答案

使用模块 csv.DictReader 跳过空行,并得到字典列表:

Using module csv.DictReader to skip empty lines and get a list of dictionaries:

In [131]: import csv
     ...: with open('a.csv') as f:
     ...:     lst=list(csv.DictReader(f))

In [132]: lst
Out[132]: 
[{'a': '12.0', 'b': '3.5', 'c': '4.3', 'd': '5.9'},
 {'a': '13.0', 'b': '5.7', 'c': '2.8', 'd': '5.2'},
 {'a': '14.0', 'b': '6.4', 'c': '9.7', 'd': '2.3'},
 {'a': '15.0', 'b': '6.8', 'c': '4.7', 'd': '3.4'}]

In [134]: [{k:float(d[k]) for k in d} for d in lst] #convert values to floats
Out[134]: 
[{'a': 12.0, 'b': 3.5, 'c': 4.3, 'd': 5.9},
 {'a': 13.0, 'b': 5.7, 'c': 2.8, 'd': 5.2},
 {'a': 14.0, 'b': 6.4, 'c': 9.7, 'd': 2.3},
 {'a': 15.0, 'b': 6.8, 'c': 4.7, 'd': 3.4}]

编辑:

要获取列表列表:

to get a list of list:

In [143]: with open('a.csv') as f:
     ...:     cr=csv.reader(f)
     ...:     skip=next(cr)  #skip the first row of keys "a,b,c,d"
     ...:     print [map(float, l) for l in cr]
     ...: 
[[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]]

这篇关于CSV行导入蟒蛇阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆