Home > Mobile >  could not convert string to float {PYTHON}
could not convert string to float {PYTHON}

Time:11-19

I have converted a .csv file to list

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 I try to convert the string value in the list to float, it gives me an error msg. I have tried a lot of methods to convert the datatype but it doesn't work

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'

CodePudding user response:

It seems you are using default california_housing_train.csv with 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

CodePudding user response:

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])
  • Related