Home > Net >  How to fix the error in order to convert string to float in python?
How to fix the error in order to convert string to float in python?

Time:10-20

I have the following in my code:

import numpy as np
b=np.loadtxt("abc.xyz")

My abc.xyz file is like following:

A 1.0400000 0.0620770 0.0479419
A 2.0060000 2.4675657 -0.0229796
A 3.0700000 0.0490902 1.5524933
B 4.0090000 2.4494762 1.4444613
A 2.0040000 1.2139214 3.1270965

I keep getting this error:

ValueError: could not convert string to float: 'A'

How to fix this issue? Thank you in advance.

CodePudding user response:

Use pandas and drop the first column

data = pandas.read_csv("abc.xyz",sep=" ")
data = data.drop(data.columns[0], axis=1)

CodePudding user response:

As per the documentation for numpy, you want to take the data without the extra column with the letters, (If not, that's a completely different case), to do so, you can use the parameter usecols as follows:

b=np.loadtxt("abc.xyz",usecols = (1,2,3))

Link for the documentation for more information:

https://numpy.org/doc/stable/reference/generated/numpy.loadtxt.html

CodePudding user response:

Try something like this:

b = np.loadtxt("abc.xyz", dtype=float)

Alternatively:

b = np.matrix(b, dtype=float)

Hope any of these works out for you.

CodePudding user response:

Your problem is the first column it contains letters and you want numbers only. So it looks like you'd want to skip the first column because it is irrelevant for your math and also not valid for conversion to numeric values: take a look at https://likegeeks.com/numpy-loadtxt-tutorial/#Ignoring_the_first_column

  • Related