2011-09-26 60 views
0

我需要知道如何总结CSV文件中列的所有数字。如何总结python中一列的所有数字?

例如。我的数据是这样的:

column count min max sum mean 
80 29573061 2 40 855179253 28.92 
81 28861459 2 40 802912711 27.82 
82 28165830 2 40 778234605 27.63 
83 27479902 2 40 754170015 27.44 
84 26800815 2 40 729443846 27.22 
85 26127825 2 40 701704155 26.86 
86 25473985 2 40 641663075 25.19 
87 24827383 2 40 621981569 25.05 
88 24189811 2 40 602566423 24.91 
89 23566656 2 40 579432094 24.59 
90 22975910 2 40 553092863 24.07 
91 22412345 2 40 492993262 22 
92 21864206 2 40 475135290 21.73 
93 21377772 2 40 461532152 21.59 
94 20968958 2 40 443921856 21.17 
95 20593463 2 40 424887468 20.63 
96 20329969 2 40 364319592 17.92 
97 20157643 2 40 354989240 17.61 
98 20104046 2 40 349594631 17.39 
99 20103866 2 40 342152213 17.02 
100 20103866 2 40 335379448 16.6 
#But it's separated by tabs 

到目前为止,我编写的代码是:

import sys 
import csv 

def ErrorCalculator(file): 
     reader = csv.reader(open(file), dialect='excel-tab') 

     for row in reader: 
       PxCount = 10**(-float(row[5])/10)*float(row[1]) 


if __name__ == '__main__': 
     ErrorCalculator(sys.argv[1]) 

对于这个特殊的代码,我需要所有的总和,总结在PxCount所有的数字和鸿沟行号[1]中的数字...

如果告诉我如何总结列的数字或者如果您帮助我使用此代码,我将非常感激。

此外,如果你可以给我一个提示跳过标题。

回答

2

你可以叫“读卡器。 next()“在实例化读取器后放弃第一行。

要计算PxCount,只需在循环前设置sum = 0,然后在为每行计算后设置sum += PxCount

PS您可能会发现csv.DictReader也有帮助。

2

你可以使用"augmented assignment" +=保持运行总计:

total=0 
for row in reader: 
     PxCount = 10**(-float(row[5])/10)*float(row[1]) 
     total+=PxCount 

要跳过CSV文件的第一行(标题):

with open(file) as f: 
    next(f) # read and throw away first line in f 
    reader = csv.reader(f, dialect='excel-tab') 
1

使用DictReader将产生更清晰的代码。 Decimal会给你更好的精度。另外尝试遵循Python命名约定,并为函数和变量使用小写名称。

import decimal 

def calculate(file): 
    reader = csv.DictReader(open(file), dialect='excel-tab') 
    total_count = 0 
    total_sum = 0 
    for row in reader: 
     r_count = decimal.Decimal(row['count']) 
     r_sum = decimal.Decimal(row['sum']) 
     r_mean = decimal.Decimal(row['mean']) 
     # not sure if the below formula is actually what you want 
     total_count += 10 ** (-r_mean/10) * r_count 
     total_sum += r_sum 
    return total_count/total_sum 
相关问题