ValueError: could not convert string to float, values in CSV can't be converted to floats

匿名 (未验证) 提交于 2019-12-03 01:41:02

问题:

I am trying to do some mathematical operation on the values of a column fetched from a csv file. For that I wrote the code given below:

rows = csv.reader(open('sample_data_ml.csv', 'r')) newrows = [] selling_price = [] count = 0  Y_pred = np.asarray(Y_pred, dtype='float64')  for margin in Y_pred:     for row in rows:             if count == 0:                count = count+1             else:                 #print(row[7])                 sell = float(row[7]) + margin*float(row[7])                selling_price.append(sell)  print(selling_price) 

I am getting this error :

--------------------------------------------------------------------------- ValueError                                Traceback (most recent call last) <ipython-input-29-d6009e8dad12> in <module>()      16             #row[7] = float(row[7])      17  ---> 18             sell = float(row[7]) + margin*float(row[7])      19             selling_price.append(sell)      20   ValueError: could not convert string to float:  

Problem is likely with the values of row[7]. How to overcome?

Edit: The row[7] in csv looks like this (some sample values):

After adding try except block as suggested, I am getting all values of the column as the output of except block.

[array([312.81321038]), array([223.43800741]), array([1489.58671609]), array([49.34255997]), array([726.17352409]), array([2583.50196071]), array([116.37396219]), array([395.67147146]), array([27.92975093]), array([260.67767531]), array([1117.19003706]), array([1024.09086731]), array([884.44211268]), array([325.84709414]), array([186.19833951]), array([316.53717717]), array([43.75660979]), array([605.14460341]), array([5492.85101557]), array([65.16941883]), array([3798.44612602]), array([884.44211268]), array([1210.28920682]), array([726.17352409]), array([625.62642076]), array([698.24377317]), array([204.81817346]), array([1396.48754633]), array([325.84709414]), array([1815.43381023]....) 

It seems all the values in that column involve in the problem. How to proceed?

回答1:

Put it in a catch and try:

 try:    sell = float(row[7]) + margin*float(row[7])    selling_price.append(sell)  except ValueError, e:     # report the error in some way that is helpful -- maybe print        print(row[7])     row[7] = 0   # just to be safe  


回答2:

Possible solutions could be.

  • you could wrap your code try except block and handle error in except

At except block

  • you can extract only numbers and convert to float
  • just skip
  • make default value to 0 if there is not any string number which can be converted to float
  • make log of failed rows
     try:      except ValueError:             #handle here  


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!