如何对csv文件中的行或列进行求和?

问题描述 投票:0回答:1

有人可以帮助我理解一行和一列中的python总和值,第二个我相信我已经想到了我到目前为止还没有掌握这个概念,一旦我能够分配值,总和,过滤到变量我可以前进到可视化。

Like sum the 1948 row and so on档案年Jan Fev Mar ...年度1948 4.0 4.7 4.5 ... 3.8 1949 5.0 5.8 5.6 ... 5.9 ......

with open('unemployment1948.csv', 'r') as unFile:
        unReader = csv.DictReader(unFile, delimiter = ',')
        unHeads = unReader.fieldnames
        print(unHeads)

        u = defaultdict(float)
        for r in unReader:
            for v in r['Year']:
                try:
                    d[r['1948']] += float(v)
                except ValueError:
                    pass
        print(d)
python-3.x csv sum row
1个回答
0
投票

pandas似乎是Python中的“go to”工具。

看起来你有一个DataFrame所以使用pandas你应该可以做类似的事情:

df.sum(axis = 0)

其中axis=0将返回几个月的值

df.sum(axis = 1)

将返回多年的值。

This answer也有一些例子和pandas docs本身。

© www.soinside.com 2019 - 2024. All rights reserved.