-2

as a noob, I'm struggling with converting a column of numbers in a CSV to a float.

the test file looks like this: test.csv = [['a','1'],['b','2']].

My code:

def readLines():
    def conv(s):
        try:
            s=float(s)
        except ValueError:
            pass
        return s

    with open('C:/Users/Public/Documents/Scripts/test.csv', 'rU') as data:
        reader = csv.reader(data)
        for row in reader:
            for cell in row:
                y=conv(cell)
                print (y)

readLines()

The result is this:

a
1.0
b
2.0

But I really just want to have the array modified so that the number are floats, and everything else is kept intact.

Also, it would be nicer from my perspective to keep the code in order - ie open the file, then covert.

3
  • 2
    So... What precisely is the problem? Commented May 28, 2014 at 21:36
  • @jonrsharpe: I guess that y is not part of the row. Commented May 28, 2014 at 21:37
  • Something like this may help - your conception of how python treats variables is incorrect. Commented May 28, 2014 at 21:41

1 Answer 1

0

I am not sure, what would be the result you desire, but this is how I understand it: You want to read data from a CSV-file into a python data structure with the second cell in each line converted to a float:

with open('C:/Users/Public/Documents/Scripts/test.csv', 'rU') as data:
    reader = csv.reader(data)
    # using list comprehension
    result = [(row[0], float(row[1])) for row in reader]

print result

Out:

[('a', 1.0), ('b', 2.0)]
Sign up to request clarification or add additional context in comments.

1 Comment

thanks for working code, and the links to improve my understanding,

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.