Sunday, 15 June 2014

python - CSV Reader from one column whose element representing list/array not one value -



python - CSV Reader from one column whose element representing list/array not one value -

below content myfile.csv

1st 2nd 3rd 4th 5th 2061100 10638650 -8000 25 [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0] 2061800 10639100 -8100 26 [2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0] 2061150 10638750 -8250 25 [3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0] 2061650 10639150 -8200 25 [4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0] 2061350 10638800 -8250 3 [5.0, 5.0, 5.0] 2060950 10638700 -8000 1 [1.0] 2061700 10639100 -8100 11 [2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0] 2061050 10638800 -8250 6 [3.0, 3.0, 3.0, 3.0, 3.0, 3.0] 2061500 10639150 -8200 1 [4.0] 2061250 10638850 -8150 16 [5.0, 5.0, 5.0, 5.0]

my current code:

from numpy import genfromtxt mydata = genfromtxt('myfile.csv', delimiter=',') arr = np.array(mydata) col5 = arr[:,4]

however, want read 5th column list , read elements list farther calculation. shall do?

if whitespace between columns tabs:

import csv, ast, pprint result = list() open('in.txt') in_file: reader = csv.reader(in_file, delimiter = '\t') line in reader: line[:4] = map(int, line[:4]) line[4] = ast.literal_eval(line[4]) result.append(line) pprint.pprint(result) >>> [[2061100, 10638650, -8000, 25, [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]], [2061800, 10639100, -8100, 26, [2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0]], [2061150, 10638750, -8250, 25, [3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0]], [2061650, 10639150, -8200, 25, [4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0]], [2061350, 10638800, -8250, 3, [5.0, 5.0, 5.0]], [2060950, 10638700, -8000, 1, [1.0]], [2061700, 10639100, -8100, 11, [2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0]], [2061050, 10638800, -8250, 6, [3.0, 3.0, 3.0, 3.0, 3.0, 3.0]], [2061500, 10639150, -8200, 1, [4.0]], [2061250, 10638850, -8150, 16, [5.0, 5.0, 5.0, 5.0]]] >>>

a variation on theme:

with open('in.txt') in_file: reader = csv.reader(in_file, delimiter = '\t') result = [[ast.literal_eval(item) item in line] line in reader]

python csv

No comments:

Post a Comment