0

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

Tom
  • 55
  • 1
  • 6
  • 1
    Are your values actually separated by commas? – MattDMo Apr 07 '22 at 15:39
  • May I suggest you copy and paste several lines of the text file into a code block so that we know what kind of data we are working with? – OTheDev Apr 07 '22 at 15:41
  • They weren't separated by commas. I have changed the delimiter and it is solved now :) – Tom Apr 07 '22 at 16:57

2 Answers2

1

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")
Ukulele
  • 612
  • 2
  • 10
1

numpy.loadtext returns an array so you could use fdata = data.astype(np.float)

How to convert an array of strings to an array of floats in numpy?

Wumbo
  • 90
  • 5