Home > Net >  ValueError while importing data from a file using Python
ValueError while importing data from a file using Python

Time:03-06

I keep getting ValueError: could not convert string to float:' '.

The code I used is:

import matplotlib.pyplot as plt
import numpy as np
    
X, Y = np.loadtxt('/Users/sul/Desktop/2,54,51PM.txt', delimiter=',', unpack=True)
    
plt.plot(X, Y)
plt.title('Line Graph using NUMPY')
plt.xlabel('X')
plt.ylabel('Y')
plt.show()

The file contains two columns and over 1000 rows, like this:

1413.541000000  0.001121856
1413.548812500  0.001122533
1413.556625000  0.001121994
1413.564437500  0.001120641
1413.572250000  0.001120932

What can I do to fix this?

CodePudding user response:

Well, apparently it looks that the values are not comma-separated, rather separated by a single space, which causes the error as the values are being interpreted as strings. Change delimiter = ',' to delimiter = ' ', and it should work. See the result below:

Fig

CodePudding user response:

Take a look at this line from your code:

X, Y = np.loadtxt('/Users/sul/Desktop/2,54,51PM.txt', delimiter=',', unpack=True)

If your data file looks like the sample you posted, then there is no comma being used as a delimiter.

It seems like it's looking at these two float values separated by a space and interpreting that as a String.

You need to match the delimiter.

  • Related