简体   繁体   English

python中CSV文件的列总和

[英]Sum of a column in python for CSV file

I have a csv file and I want to find the total distance that the athlete runs. 我有一个csv文件,我想找到运动员跑步的总距离。 CSV file is given below how can I add the numbers in column 3. CSV文件如下所示,如何在第3列中添加数字。

C栏总和

Using pandas module it might look like (more or less) 使用pandas模块可能看起来像(或多或少)

import pandas as pd

df = pd.read_csv(filename, ... some other options ...)

print df[2].sum()

# print df['distance'].sum()

Here is an approach using the builtin csv module 这是使用内置csv模块的方法

import csv
csv_file = csv.reader(open("your_file_name.csv"))

dist = 0
for row in csv_file:
    _dist = row[2]
    try: 
        _dist = float(_dist)
    except ValueError:
        _dist = 0

    dist += _dist

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM