0

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.

4
  • can you try b=np.loadtxt("abc.xyz",usecols = (1,2,3)) ? Commented Oct 19, 2021 at 12:04
  • Yes. It's done. Thank you Commented Oct 19, 2021 at 12:08
  • Cheers, feel free to accept whichever answer helped you and is best. Also it would be great if you go through your questions history and do the same for previous questions, so it helps both you and others to find answers! Commented Oct 19, 2021 at 12:09
  • loadtxt as a default reads the whole line, and tries to convert each element to float. The error arises because the first value A does not represent a number. Commented Oct 19, 2021 at 16:18

4 Answers 4

1

Use pandas and drop the first column

data = pandas.read_csv("abc.xyz",sep=" ")
data = data.drop(data.columns[0], axis=1)
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

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.

1 Comment

float is the default dtype in loadtxt
0

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

1 Comment

Please do attempt to post the method here, link-only answers are not generally preferred in stackoverflow, as links might die at any point making the answer not future-proof. Read more here: meta.stackoverflow.com/tags/link-only-answers/info

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.