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?

2
  • 1
    Why do you have delimiter=' ' when your data is delimited by commas? Commented Mar 7, 2014 at 6:20
  • possible duplicate of csv row import into python array Commented Mar 7, 2014 at 6:20

2 Answers 2

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)]
 >>>
Sign up to request clarification or add additional context in comments.

5 Comments

eval is slower than map or list comprehension
any reason why its slow ?
you can timeit on your own, or see stackoverflow.com/questions/1832940/…
i din't see any reason for slow in that post ? can you explain ?
search with ctrl+F and you'll see It leads to relatively slow on-the-fly compilation of small pieces of code ;)
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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.