简体   繁体   English

无法将字符串转换为浮点 {PYTHON}

[英]could not convert string to float {PYTHON}

I convet a csv file to list我将一个 csv 文件列出来

with open('sample_data/california_housing_train.csv', 'r') as f:
  next(f)
  housing = list(csv.reader(f, delimiter=';'))



housing[:5]
[['-114.310000,34.190000,15.000000,5612.000000,1283.000000,1015.000000,472.000000,1.493600,66900.000000'],
 ['-114.470000,34.400000,19.000000,7650.000000,1901.000000,1129.000000,463.000000,1.820000,80100.000000'],
 ['-114.560000,33.690000,17.000000,720.000000,174.000000,333.000000,117.000000,1.650900,85700.000000'],
 ['-114.570000,33.640000,14.000000,1501.000000,337.000000,515.000000,226.000000,3.191700,73400.000000'],
 ['-114.570000,33.570000,20.000000,1454.000000,326.000000,624.000000,262.000000,1.925000,65500.000000']]

When try to convert this list float give me error msg i try a lot of motheds to convet string list to int but doesn't work当尝试将此列表浮动转换给我错误消息时,我尝试了很多方法将字符串列表转换为 int 但不起作用

wines = np.array(housing[1:], dtype=np.float)

Error msg错误信息


ValueError                                Traceback (most recent call last)
<ipython-input-40-5d89c6082408> in <module>()
----> 1 wines = np.array(housing[1:], dtype=np.float)

ValueError: could not convert string to float: '-114.560000,33.690000,17.000000,720.000000,174.000000,333.000000,117.000000,1.650900,85700.000000'

I try a lot of motheds to convert list to float but doesn't wokr with me.我尝试了很多方法将列表转换为浮点数,但不适合我。

Try this method:试试这个方法:

a = '-114.560000,33.690000,17.000000,720.000000,174.000000,333.000000,117.000000,1.650900,85700.000000'
a = a.split(',')
for i in range(len(a)):
   a[i] = float(a[i])

It seems you are using default california_housing_train.csv with Google Colab.看来您正在使用默认的california_housing_train.csv和 Google Colab。 Do not give delimiter ;不要给定界符;

with open('sample_data/california_housing_train.csv', 'r') as f:
  next(f)
  housing = list(csv.reader(f))

wines = np.array(housing[1:], dtype=np.float)

then this works fine那么这工作正常

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM