ValueError:无法将字符串转换为浮点,CSV中的值无法转换为浮点

时间:2019-03-12 06:41:35

标签: python string csv floating-point

我正在尝试对从csv文件获取的列的值进行一些数学运算。为此,我编写了以下代码:

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)

我收到此错误:

---------------------------------------------------------------------------
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: 

row [7]的值可能存在问题。如何克服?

编辑: csv中的row [7]看起来像这样(一些示例值): enter image description here

按照建议添加tryexcept块后,我将列的所有值作为except块的输出。

[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]....)

该列中的所有值似乎都与问题有关。如何进行?

1 个答案:

答案 0 :(得分:1)

将其放入陷阱并尝试:

 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