简体   繁体   中英

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 file is given below how can I add the numbers in column 3.

C栏总和

Using pandas module it might look like (more or less)

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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