简体   繁体   中英

How to skip a column when reading a CSV file - Python

So in my CSV i have peoples names as the first row and i'm trying to get the average of 3 numbers on the columns 1-3. (not the first column though) Is there a way to skip a column so that i can just pull out columns 1-3? here is my code for getting the average. Any help would be much appreciated. So just to be clear on what i want: I want to skip a column so that i can successfully get the mean average from columns 1-3.

        if order ==("average score"):
            with open("data.csv") as f:
                reader = csv.reader(f)
                columns = f.readline().strip().split(" ")
                numRows = 0
                sums = [1] * len(columns)

                for line in f:
                # Skip empty lines
                    if not line.strip():
                        continue

                values = line.split(" ")
                for i in range(len(values)):

                    sums[i] += int(values[i])
                    numRows += 1

                for index, summedRowValue in enumerate (str(sums)):
                    print (columns[index], 1.0 * summedRowValue / numRows)

您需要做的就是将范围更改为从1开始而不是0,以跳过第一列:

for i in range(1, len(values)):

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