Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does float() fail to convert my string to a float?

Tags:

python

My program is giving me an error when it tries to convert a string from a list of strings to a floating point number. The list is read from a line in a CSV text file and then separated into a list. How do I make this work and why is it going wrong? Here are the relevant bits of code:

def Main():
    srcf = open(bkp, 'r')
    for line in srcf:
        liLn = line.split(',')

...Then the following function is called...

def Pred_PSME(liLn):
    dbh = float(liLn[6])

Here is the line from the file:

1345327,20486,"ABCO","Abies concolor","Y","Y","31.496","0.0779","19.3567",,"0.5602","0",1,"0.9268","11.8968","2.6832","6.6646","2399.256",54.47,24.15,248.47,42.19,9.16,8.16,9.23,272.27,264.11,369.30,345.15,71.80,0.00,0.00,4393.57,4106.22,3239.25,3142.07,854.30,0.00,0.00,,12.70,10.16,15.24,0.02,0.04,0.38,0.38,0.00,0.00,1.95,1.83,1.44,1.40

I get this error message:

Traceback (most recent call last):  
  File "/home/cfws/python/error_calcs/FC_NF_PredInt_Gen8.py", line 263, in <module>  
    Main()  
  File "/home/cfws/python/error_calcs/FC_NF_PredInt_Gen8.py", line 36, in Main  
    li_tBQI = BQI_Calc(liLn)  
  File "/home/cfws/python/error_calcs/FC_NF_PredInt_Gen8.py", line 63, in BQI_Calc  
    di_eqns = {"PSME": Pred_PSME(liLn), "ABAM":Pred_ABAM(liLn), \  
  File "/home/cfws/python/error_calcs/FC_NF_PredInt_Gen8.py", line 172, in Pred_PSME  
    dbh = float(liLn[6])  
ValueError: could not convert string to float: "31.496"

I'm using Python 2.7 on an Ubuntu Linux computer.

like image 918
cfwschmidt Avatar asked Mar 10 '11 03:03

cfwschmidt


People also ask

Why can I not convert string to float?

This error usually occurs when you attempt to convert a string to a float in pandas, yet the string contains one or more of the following: Spaces. Commas. Special characters.

How do you convert a string to a float?

We can convert a string to float in Python using the float() function. This is a built-in function used to convert an object to a floating point number. Internally, the float() function calls specified object __float__() function.

How do you convert a string variable to a float in Python?

In Python, we can use float() to convert String to float. and we can use int() to convert String to an integer.


1 Answers

You need to strip the double quotes off the string. This will then you give a legitimate floating point string that float() can convert.

like image 181
winwaed Avatar answered Oct 17 '22 16:10

winwaed