0

I'm reading in a csv file, and all rows contain string elements. One might be:

"orange", "2", "65", "banana" 

I want to change this, within my dataset, to become:

row = ["orange", 2.0, 65.0, "banana"]

Here is my code:

data = f.read().split("\n")
for row in data:
    for x in row:
        if x.isdigit():
            x = float(x)
    print row

But it still prints the original rows like:

 "orange", "2", "65", "banana"

I also want to achieve this without using list comprehensions (for now).

Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126
boldbrandywine
  • 322
  • 1
  • 14

2 Answers2

1

I believe it is because you cannot edit the row array in place like that. The x variable doesn't actually refer to the element in the array but a copy of it, so all changes you make evaporate after you're done iterating through the array.

I'm not sure if this is the idiomatic 'python way' of doing this but you could do:

data = f.read().split("\n")
for row in data:
    parsed_row = []
    for x in row:
        if x.isdigit():
            x = float(x)
        parsed_row.append(x)
    print parsed_row 

Alternatively a more 'pythonic' way, as provided by JGreenwell in the comments, may be to allow an exception to be thrown if an element cannot be parsed to float.

data = f.read().split("\n")
for row in data:
    parsed_row = []
    for x in row:
        try: 
            parsed_row.append(float(x)) 
        except ValueError: 
            parsed_row.append(x)
    print parsed_row 

It really would come down to personal preference I imagine. Python exceptions shouldn't be slow so I wouldn't be concerned about that.

dave
  • 1,127
  • 2
  • 10
  • 26
  • This is the problem the OP is having, a more Pythonic way may be the "its better to ask forgiviness than permission" idiom. Meaning use a try/except block: `try: parsed_row.append(float(x)) except ValueError: parsed_row.append(x)` - this method is [shown here](http://stackoverflow.com/a/20929983/4667934) but the other answers show the variety of ways to do this depending on ones requirements – LinkBerest Sep 15 '16 at 02:43
0

Perhaps is your delimiter. Try something like

with open('yourfile.csv', 'rb') as csvfile:
    reader = csv.reader(csvfile, delimiter=',', quotechar='|')
    for row in reader:
        for x in row:
            if x.isdigit():
                 print(float(x))
eafloresf
  • 164
  • 1
  • 7