Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

ValueError: could not convert string to float solution

I have a text file containing data. The data, in this case, are simply the numbers ‘0.049371 0.049371 0.000000’.

I have the code

import numpy as np
import matplotlib.pyplot as plt
data = np.loadtxt("/path/to/file", delimiter=",")

plt.figure()

plt.plot(range(len(data)), data, color='blue')
plt.xlim(0, 100)
plt.ylim(0, 50)
plt.xlabel('t / t₀', fontstyle = 'italic')
plt.ylabel('Speed', fontstyle = 'italic')



plt.show()

But I get the error message ‘ValueError: could not convert string to float’. Is there a way to convert all of the values in a text file to floats?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thank you

>Solution :

In the line data = np.loadtxt("/path/to/file", delimiter=",") you have specified "," as the delimiter. This would give the correct result if your file contained 0.049371,0.049371,0.000000.

Since the numbers are actually separated by spaces, use:

data = np.loadtxt("/path/to/file", delimiter=" ")

or just:

data = np.loadtxt("/path/to/file")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading