2011-09-26 7 views
0

CSV 파일의 모든 열 번호를 합하는 방법을 알아야합니다.파이썬에서 한 열의 모든 숫자를 합하는 방법은 무엇입니까?

예를 들면. 내 데이터는 다음과 같습니다

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 

지금까지 쓰기 한 코드이다 : 나는 모든의 합으로 모든 PxCount의 숫자와 격차를 요약하기 위해 필요한이 특정 코드의 경우

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]) 

행 번호 [1] ...

열 번호를 합산하는 방법 또는이 코드를 사용하는 방법을 알려 주시면 감사하겠습니다.

또한 헤더를 건너 뛰는 팁을 줄 수있는 경우.

답변

2

당신은 호출 할 수 있습니다 "독자를. 다음() "첫 번째 줄을 버리기 위해 독자를 인스턴스화 한 직후.

PxCount를 합산하려면 루프 전에 sum = 0을 설정하고 각 행에 대해 계산 한 후에는 sum += PxCount으로 설정하면됩니다.

추신 : 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은 더 나은 정밀도를 제공합니다. 또한 파이썬 명명 규칙을 따르고 함수와 변수에 소문자 이름을 사용하십시오.

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 
관련 문제