1

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?

2
  • 4
    I suspect your data is malformed: add a print row[c].strip('"') before the offending line and the last result before it errors. Commented Dec 20, 2016 at 22:10
  • 2
    Read the error: can't convert string to float. row[c].strip('""') is a string, which should contain only a float and maybe whitespace, otherwise float(...) will fail, with the error you're seeing, Commented Dec 20, 2016 at 22:10

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

5 Comments

I see nothing but white space in my Ipython console, however it does output some data as a float. What can I do to fix this problem, I am very new to python
@MiguelA can you add the output from that to your question?
Unfortunately my output goes to a .csv file which is very large. The printed data in the console after adding the error check is just blank white space that goes on for a while until the run it stops.
@MiguelA can you post what you get between the single quotes of bad string? I updated it to make it more useful
@MiguelA I updated my solution after I realized that's what you were getting.
0

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)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.