2013-07-05 206 views
2

我正在写一个代码在python中的项目,必须完成一些事情;通过 列2从xls文件列在数据读取) 1)平均该列的每行三个 3的基团)进行平均所得到的列平均下来的平均数据列

我已经完成图1和2,但不能完全似乎为了得到3,我认为很多麻烦源于我使用浮点数的事实,但是我需要数字到6位小数。任何帮助和耐心表示赞赏,我很新的Python

v = open("Pt_2_Test_Data.xls", 'wb') #created file to write output to 
w = open("test2.xls") 

count = 0 

for row in w: #read in file 
    for line in w: 
     columns = line.split("\t") #split up into columns 
     date = columns[0] 
     time = columns[1] 
     a = columns[2] 
     b = columns[3] 
     c = columns[4] 
     d = columns[5] 
     e = columns[6] 
     f = columns[7] 
     g = columns[8] 
     h = columns[9] 
     i = columns[10] 
     j = columns[11] 
     k = columns[12] 
     l = columns[13] 
     m = columns[14] 
     n = columns[15] 
     o = columns[16] 
     p = columns[17] 
     q = columns[18] 
     r = columns[19] 
     s = columns[20] 
     t = columns[21] 
     u = columns[22] 
     LZA = columns[23] 
     SZA = columns[24] 
     LAM = columns[25] 

     count += 1 

     A = 0 
     if count != 0: # gets rid of column tiles 
      filter1 = ((float(a) + float(b) + float(c))/3) 
      filter1 = ("%.6f" %A) 
      filter2 = (float(d) + float(e) + float(f))/3 
      filter2 = ("%.6f" %filter2) 
      filter3 = (float(g) + float(h) + float(i))/3 
      filter3 = ("%.6f" %filter3) 
      filter4 = (float(j) + float(k) + float(l))/3 
      filter4 = ("%.6f" %filter4) 
      filter5 = (float(m) + float(n) + float(o))/3 
      filter5 = ("%.6f" %filter5) 
      filter6 = (float(p) + float(q) + float(r))/3 
      filter6 = ("%.6f" %filter6) 
      filter7 = (float(s) + float(t) + float(u))/3 
      filter7 = ("%.6f" %filter7) 
      A = [filter1, filter2, filter3, filter4, filter5, filter6, filter7] 
      A = ",".join(str(x) for x in A).join('[]') 

      print A 
      avg = [float(sum(col))/float(len(col)) for col in zip(*A)] 
      print avg 

我也试图格式化数据,像这样:

  A = ('{0} {1} {2}  {3} {4} {5} {6} {7} {8}'.format(date, time, float(filter1), float(filter2), float(filter3), float(filter4), float(filter5), float(filter6), float(filter7))+'\n') # average of triplets 
      print A 

想我可以访问每一列的值和瓶坯通过像使用字典时那样调用它们来进行必要的数学计算,但这是不成功的:它似乎是将数据识别为一行(因此试图通过[0]访问任何列超出边界)或由个别字符,而不是数字列表。这与使用float函数有关吗?

回答

1

我不知道我知道你想在3到平均的列),但也许这你想要做什么:

with open("test2.xls") as w: 
    w.next() # skip over header row 
    for row in w: 
     (date, time, a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, 
     u, LZA, SZA, LAM) = row.split("\t") # split columns into fields 

     A = [(float(a) + float(b) + float(c))/3, 
      (float(d) + float(e) + float(f))/3, 
      (float(g) + float(h) + float(i))/3, 
      (float(j) + float(k) + float(l))/3, 
      (float(m) + float(n) + float(o))/3, 
      (float(p) + float(q) + float(r))/3, 
      (float(s) + float(t) + float(u))/3] 
     print ('['+ ', '.join(['{:.6f}']*len(A)) + ']').format(*A) 
     avg = sum(A)/len(A) 
     print avg 

你可以做同样的事情多一点简明像代码如下:

avg = lambda nums: sum(nums)/float(len(nums)) 

with open("test2.xls") as w: 
    w.next() # skip over header row 
    for row in w: 
     cols = row.split("\t") # split into columns 
     # then split that into fields 
     date, time, values, LZA, SZA, LAM = (cols[0], cols[1], 
              map(float, cols[2:23]), 
              cols[23], cols[24], cols[25]) 
     A = [avg(values[i:i+3]) for i in xrange(0, 21, 3)] 
     print ('['+ ', '.join(['{:.6f}']*len(A)) + ']').format(*A) 
     print avg(A) 
+0

是的!这看起来会完成我想要的!然而,我在行“print('['+','.join(['{:。6f}'] * len(A))+']')。格式(* A)'你解释了这部分代码的意义:“print('['+','.join(['::6f}'] * len(A))+']')。格式(* A)“? - 谢谢 – KJo

+0

这只是创建格式化字符串''[{:.6f},{:.6f},{:.6f},{:.6f},{: .6f},{:.6f},{:.6f}]'',然后将它应用于列表'A'中的所有'float'值。您在线上发生了什么错误? – martineau

+0

ValueError:零长度字段名称的格式为 – KJo

1

您可以使用decimal模块显示确切的数字。

from decimal import * 
getcontext().prec = 6 # sets the precision to 6 

注意,使用浮动点,这意味着:

print(Decimal(1)/(Decimal(7)) # 0.142857 
print(Decimal(100)/(Decimal(7)) # results in 14.2857 

这意味着你可能需要精确设定为较高值,以获得6位小数... 例如:

from decimal import * 
getcontext().prec = 28 
print("{0:.6f}".format(Decimal(100)/Decimal(7))) # 14.285714 

要给你的问题一个完整的答案,你能解释你寻找什么样的平均值吗?所有(21)列的平均值?你可能会发布一些test_data.xls?

+0

啊,谢谢,我不知道十进制模块。这有可能是非常有帮助的! – KJo

0

我会考虑使用numpy。我不知道如何读取xls文件,但似乎有提供此功能的软件包。我会这样做:

import numpy as np 

with open("test2.txt") as f: 
    for row in f: 
     # row is a string, split on tabs, but ignore the values that 
     # don't go into the average. If you need to keep those you 
     # might want to look into genfromtxt and defining special datatypes 
     data = (np.array(row.split('\t')[2:23])).astype(np.float) 
     # split the data array into 7 separate arrays (3 columns each) and average on those 
     avg = np.mean(np.array_split(data,7)) 
     print avg 

我不确定上面的平均值是否正是你想要的。您可能需要保存较小的阵列(smallArrays = np.array_split(data,7)),然后重复这些操作,随时计算平均值。

即使这不完全是你想要的,我建议看看numpy。我发现它非常易于使用,并且在进行像您正在尝试的计算时非常有用。