Reputation: 43
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 because savetxt
needs an array, but g
conatins floats.
But even when I define an array g_
, 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?
Upvotes: 2
Views: 11934
Reputation: 4051
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
Upvotes: 1
Reputation: 26572
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
Upvotes: 3