Search code examples
pythongraphfloating-point

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?

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")