-1

I am getting information from a csv, I need to take a field which in theory is a float, but can come empty, I'm this function which takes the row [i] where the float is, and should return the float,

def fun(x):
    if not(x):
        x=0
        x=float(x)
    else:
        x = float(x)
    return x

but when i try it throws me this error tells me "float () argument must be a string or a number"

jww
  • 97,681
  • 90
  • 411
  • 885
Hook
  • 391
  • 5
  • 16

2 Answers2

1

Ok, how about

def fn(x):
    try:
        return float(x)
    except (ValueError, TypeError):
        return 0.0
Hugh Bothwell
  • 55,315
  • 8
  • 84
  • 99
  • still tells me "float() argument must be a string or a number" – Hook Jan 17 '15 at 01:46
  • @Tabbz, are you passing a list, a tuple, etc,,? You need to `print row[11] `and see exactly what you are passing – Padraic Cunningham Jan 17 '15 at 01:48
  • @Tabbz,`except (ValueError,TypeError):` will catch the TypeError but you should really see what row[11] is when you get the error. What does` print row[11]` show right before the error? – Padraic Cunningham Jan 17 '15 at 01:52
  • im printing like this print 'row[11] '+str(row[11]) print 'row[12] '+str(row[12]) print 'row[13] '+str(row[13]), just you can know what im printing, but if i print only row[11] prints like " " – Hook Jan 17 '15 at 01:53
  • what exactly are you trying to cast to float? – Padraic Cunningham Jan 17 '15 at 01:55
  • row[11] are weight, in the csv several fields of this are empty, but others have numbers, the problem is those fields that are empty – Hook Jan 17 '15 at 01:58
  • 1
    ok so just catch the TypeError also, that will catch the empty strings `except (ValueError,TypeError):` – Padraic Cunningham Jan 17 '15 at 01:58
-1
def fun(x):
    try:
        x = float(x)
    except ValueError:
        x = 0
    return x

print fun("1")
print fun(' ')

Output:

1.0
0
f.rodrigues
  • 3,499
  • 6
  • 26
  • 62