Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

numpy.loadtxt, ValueError: could not convert string to float

Tags:

numpy

This is sample from large csv file:

6.1;6.1;7.2;8.9;5.0;
8.9;10.0;8.9;6.1;5.0;

If I try to read it to numpy array with np.loadtxt('test.csv', delimiter=';') I get:

ValueError: could not convert string to float:

and don't understand why?

like image 285
theta Avatar asked May 24 '13 06:05

theta


People also ask

How do you fix ValueError could not convert string to float?

The Python "ValueError: could not convert string to float" occurs when we pass a string that cannot be converted to a float (e.g. an empty string or one containing characters) to the float() class. To solve the error, remove all unnecessary characters from the string.

How do you convert a string to a float in Python?

We can convert a string to float in Python using the float() function. This is a built-in function used to convert an object to a floating point number. Internally, the float() function calls specified object __float__() function.


2 Answers

You need to strip off the trailing ';' from the lines.

A possible workaround if you know you have 5 columns is:

np.loadtxt('test.csv', delimiter=';', usecols=range(5)) 

Or, use genfromtext instead which handles missing values

np.genfromtxt('test.csv', delimiter=';')[:,:-1] 
like image 194
wim Avatar answered Sep 18 '22 13:09

wim


So in my case the csv file had column names written in the first row. e.g.

Column1,Column2,Column3 5.4,2.3,2.4 6.7,3.6,9.3 

So as given in the docs, all I had to do was use the skiprows parameter

So the API call became,

np.loadtxt('test.csv', delimiter=',', skiprows=1)

like image 25
Rohit Rokde Avatar answered Sep 20 '22 13:09

Rohit Rokde