Skip to content Skip to sidebar Skip to footer

Python. Valueerror Could Not Convert String To Float:

I'm trying to produce the average of numbers in a specified column in a text file. I am receiving an error that python could not convert string to float, although I don't see where

Solution 1:

You are passing in one string to sum_lod():

data = line.split(delim)
col_data = data[col]
total = sum_data(col_data) + total

data is a list of strings, data[col] is then one element.

sum_data() on the other hand expects an iterable:

defsum_data(lod):
    # ...for number in lod: 

Iterating over a number then gives you the individual characters:

>>>for element in'5.8':...print element... 
5
.
8

Trying to turn each element of such a string can easily lead to you trying to convert characters that are not numbers to a float:

>>>float('.')
Traceback (most recent calllast):
  File "<stdin>", line 1, in<module>
ValueError: could notconvert string tofloat: .

Either pass in a list of strings:

total += sum_data([col_data])
count += 1

or simply use float() on the one element you have:

total += float(col_data)
count += 1

Post a Comment for "Python. Valueerror Could Not Convert String To Float:"