import csv
from math import sqrt
import os
class MaxiAverageCalculator(object):
def __init__(self):
self.ncols = 3
self.nrows = 0
self.s = [0.0, 0.0, 0.0]
self.s2 = [0.0, 0.0, 0.0]
def run(self, fullpath):
with open(fullpath, "rb") as infile:
reader = csv.reader(infile, delimiter=",")
self.colnames = list(next(reader))
assert len(self.colnames) == 3
for row in reader:
L = [ float(x) for x in row ]
assert len(L) == 3
for i, x in enumerate(L):
self.s[i] += x
self.s2[i] += x * x
self.nrows += 1
self.avg = [x/self.nrows for x in self.s]
self.std = [ sqrt((y/self.nrows) - a * a) for a, y in zip(self.avg, self.s2) ]
print "Results for {0}".format(fullpath)
for name, a, s in zip(self.colnames, self.avg, self.std):
f.write(str(a))
f.write(", ")
f.write(str(s))
f.write("\n")
## print "{0}: avg = {1:.5f}, std = {2:.5f}".format(name, a, s)
## print
if __name__ == "__main__":
path="A:\\yoyo\\heyy\\folder"
f=open("A\\yoy\\save.xls")
f.write("xavg, xstd, yavg, ystd, zavg, zstd")
f.write("\n")
dirList=os.listdir(path)
for file in dirList:
fullpath=os.path.join(path,file)
calc = MaxiAverageCalculator()
calc.run(fullpath)
所以我试图在一个单独的excel文件上打印x,y和z的平均值和std ...我在线获得了这个脚本。但它似乎不起作用...请帮助
答案 0 :(得分:1)
你还在使用flopy磁盘吗?哇 :-)
然而,在一条路径中,您在另一条"A:\\..."
中编写"A\\..."
。也许就是这样。
此外,您应明确将f
传递给run()
。这是更好的风格。
答案 1 :(得分:0)
执行此操作时:
for name, a, s in zip(self.colnames, self.avg, self.std):
f.write(str(a))
f.write(", ")
f.write(str(s))
您没有通过循环中的逗号或新行将先前的标准差与下一个平均值分开。因此,假设你的平均值是[10,20,30]和标准偏差[1,2,3]。写入文件的内容是:
10,120,230,3
如果你想要它:
10,1,20,2,30,3
然后我会说一些额外的代码(这可能不是最好的方法,但它有效):
count = 0
for name, a, s in zip(self.colnames, self.avg, self.std):
count += 1
f.write(str(a))
f.write(", ")
f.write(str(s))
if count < len(self.avg): # If it is not the last record
f.write(", ") # Add a comma separating the std from the next avg
另外,为什么要在循环中删除列名?你没有在任何地方使用它。