Skip to content Skip to sidebar Skip to footer

Csv Row Import Into Python Array

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

Solution 1:

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

In [131]: import csv
     ...: withopen('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}]

EDIT:

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

Post a Comment for "Csv Row Import Into Python Array"