Abc
Abc

Reputation: 19

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

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.

Upvotes: 0

Views: 95

Answers (4)

William Berntsson
William Berntsson

Reputation: 11

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.

Upvotes: 1

Zaid Al Shattle
Zaid Al Shattle

Reputation: 1534

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

Upvotes: 1

The Emperor
The Emperor

Reputation: 56

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

Upvotes: 0

Jan Willem
Jan Willem

Reputation: 1094

Use pandas and drop the first column

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

Upvotes: 1

Related Questions