MiguelA
MiguelA

Reputation: 85

Python, ValueError: could not convert string to float:

My script is picking up a string when it should not, I get

ValueError: could not convert string to float: for line list_col.append(float(row[c].strip('"'))) in the code below

 with open(fileTwoName) as f:

    reader = csv.reader(f, delimiter=",")
    fileTwoColumnNames = next(reader)
    output_column .extend(fileTwoColumnNames[2:-1])
    number_of_columns = len(fileTwoColumnNames)-2


    for c in range(2,number_of_columns+2):
        list_col = []
        f.seek(1)
        next(reader)
        for row in reader:
            list_col.append(float(row[c].strip('"'))) 

        list_col_name_wise = []
        for k in range(0, len(number_eng)):
            list_col_name_wise.append(sum(list_col[start_row[k] - 1:start_row[k] - 1 + 1- total_case [k]]))
        data.append(list_col_name_wise)

I tested it by adding

if list_col == str:
    list_col.append(float(row[c].strip('"'))) ` 

everything outputs ok but I need my data list to output as a float. Is there a way for me to account for both a str and float?

Upvotes: 1

Views: 15888

Answers (2)

TemporalWolf
TemporalWolf

Reputation: 7952

Your data is malformed and you're getting empty strings ''. You can either ignore them, or add some default value:

for row in reader:
    try:
        list_col.append(float(row[c].strip('"'))) 
    except ValueError:
        # Empty string
        if row[c].strip('" ') == '':
            list_col.append(0.0)
            # or
            pass  # ignore
        else:
            raise

You just have to decide how to deal with empty strings: append some default value or skip them.

Upvotes: 1

Copperfield
Copperfield

Reputation: 8520

by your comments looks like you are getting something to this effect

>>> float(" ")

Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    float(" ")
ValueError: could not convert string to float: 
>>> 

and obviously you can't a float from a string that don't contain any number to start with.

You have 2 options, ignore that value and continue with the next, or use a default value like 0 or some other convenient value when that happens

To do any of that is very simple with the try-except

to ignore it do

for row in reader:
    try:
        list_col.append(float(row[c].strip('"'))) 
    except ValueError:
        print("Error with row",c,":",row[c])
        pass  

or to use a default value instead do

for row in reader:
    try:
        list_col.append(float(row[c].strip('"'))) 
    except ValueError:
        print("Error with row",c,":",row[c])
        list_col.append( 0.0 )

(prints are optional)

Upvotes: 0

Related Questions