如何在Python中求一列所有数字的总和?

0 投票
3 回答
3559 浏览
提问于 2025-04-17 03:08

我想知道怎么把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

我目前写的代码是:

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这一列的所有数字加起来,然后再除以第二行所有数字的总和……

如果你能告诉我怎么加一列的数字,或者帮我完善这段代码,我会非常感激。

另外,如果你能给我个建议,教我怎么跳过表头,那就更好了。

3 个回答

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
2

你可以用一种叫做“增强赋值”的方法来保持一个持续的总数,具体的写法是用“+=”:

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' )
2

你可以在创建读取器之后,立刻调用“reader.next()”来跳过第一行。

要计算PxCount的总和,只需在循环开始前设置sum = 0,然后在每一行计算完PxCount后,使用sum += PxCount来累加。

另外,csv.DictReader也可能对你有帮助。

撰写回答