Reputation: 11
While running the code to open a csv file using pandas and converting them to a list of floating point values there this error always occur i have tried several things but it isn't working
import csv
import random
import math
import pandas as pd
def loadCsv():
import pandas as pd
lines = pd.read_csv(r"C:\Users\apoor\OneDrive\Documents\apoorv.csv")
dataset = list(lines)
for i in range(len(dataset)):
dataset[i] = [float(x) for x in dataset[i]]
return dataset
dataset=loadCsv()
print(dataset)
everytime this error occurs
File "C:/Users/apoor/.spyder-py3/untitled2.py", line 11, in <listcomp>
dataset[i] = [float(x) for x in dataset[i]]
ValueError: could not convert string to float: '.'
Upvotes: 1
Views: 433
Reputation: 4750
dataset[i] = [float(x) for x in dataset[i]]
Here you are converting every element of dataset
into float where some of it's element cannot be converted to float. For example, one element may contains a space or some other invalid character that cannot be converted to float.
To fix this, you use try catch to handle this exception or you can just make sure that no element of dataset contains any character that cannot be converted to string.
Let's replace this line:
dataset[i] = [float(x) for x in dataset[i]]
To following lines:
for i, x in dataset:
try:
dataset[i] = float(x)
except ValueError:
print 'Invalid string to convert into float'
Now instead of value Error you will see which value at which index was occurring that error. As you are handling the exception now.
Upvotes: 1