Saving floats to a file
Solution 1
In your first attempt you are trying to save a numpy.float64
variable, and documentation says that numpy.savetxt
expects an array_like object.
In your second attempt you missed the brackets to specify a matrix g_=array([g])
, however if you save the txt inside the loop you will be overwriting your output file each time.
I guess this is what you want:
import numpy as np
g = list()
k = range(8,15)
for i in k:
q = range(i)
g.append(np.mean(q))
np.savetxt('myfile.txt', np.array(g), fmt='%.2f')
Output of myfile.txt
:
3.50
4.00
4.50
5.00
5.50
6.00
6.50
Solution 2
myFile = open("mean_values.csv","w")
myFile.write("ID" + "," + "Mean Value" +"\n") //column headers
k=range(8,15)
for i in k:
q=range(i)
g=str(mean(q))
myFile.write(str(i) + "," + g +"\n")
myFile.close()
should give you 2 columns when opened in excel. One with the ID one with the mean value
MartyMcFly
Updated on June 04, 2022Comments
-
MartyMcFly almost 2 years
I have calculated the mean values of several lists. Now I would like to save the data to a txt or csv file. Here's my approach:
k=range(8,15) for i in k: q=range(i) g=mean(q) print g savetxt('mean_values.txt', g)
But this gives me
IndexError: tuple index out of range
. I think it's becausesavetxt
needs an array, butg
conatins floats. But even when I define an arrayg_
, I end up with the same Error:k=range(8,15) for i in k: q=range(i) g=mean(q) g_=array(g) print g_ savetxt('mean_values.txt', g_)
Where's the trick?
-
MartyMcFly over 10 yearsthat will print only the mean value of the last list in the txt file. I'd like to have a list with all the mean values.