I have simple text files containing floating numbers, e.g.:
3.235235
0.2346236
1.235235
I'm trying to calculate mean & variance for every file using the following code:
import numpy
import os
def main():
for filename in os.listdir("./"):
try:
df = numpy.genfromtxt(filename, delimiter='\n', usecols=(0))
with open(filename, "a") as newfile:
newfile.write("\nMean: " + numpy.mean(df) + "\n")
newfile.write("\Variance: " + numpy.var(df) + "\n")
newfile.close()
except IOError:
print "Error reading file: %r\n" % filename
except ValueError:
print "Non-numeric data found in the file: %r\n" % filename
if __name__ == "__main__":
main()
But I get the following error:
newfile.write("\nMean: " + numpy.mean(df) + "\n")
TypeError: ufunc 'add' did not contain a loop with signature matching types dtype('S32') dtype('S32') dtype('S32')
When observing the df
it looks like:
df.dtype = float64
df.shape = (3577,)
Moreover, when using python cli and running:
df = numpy.genfromtxt("arp_40000_host_0.txt", delimiter='\n', usecols=(0))
numpy.mean(df)
I get no errors, so it seems the problem is with the write
back to the file??
What am I doing wrong?
Thanks