0

I am trying to read a csv file and make an array of arrays of the rows of data. Here is my code:

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] = [float(x) for x in row.split()]
            x += 1
    print a 

Output:

[['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 turn these arrays from 1 string into an array of floats?

user1681664
  • 1,771
  • 8
  • 28
  • 53

2 Answers2

2

Can I use eval:

 >>> ls = [['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']]
 >>> [ eval(x[0]) for x in ls ]
 [(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)]
 >>>
James Sapam
  • 16,036
  • 12
  • 50
  • 73
1

Directly answering your question:

x = [['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']]
x = [float(q) for a in x for q in a[0].split(',')]

However, much better would be to split it when reading by specifying delimiter=','.

spamreader = csv.reader(csvfile, delimiter=',', quotechar='|')
a = [row for row in spamreader]
a = [x for sublist in a for x in sublist]
sashkello
  • 17,306
  • 24
  • 81
  • 109