如何在python中仅提取CSV文件的特定列

时间:2015-10-22 16:24:03

标签: python csv python-3.x

我们必须计算Excel工作表中第5行的平均值,保存为csv文件。该文件的第一行具有使其成为字符串的列的名称。我似乎无法获得围绕所有行[4]的代码并将其计算为一个变量' sum'。这是我的代码。另外,

import csv
import os
sum = x_length = 0
with open('2.5_week.csv', newline='') as f:
    rows = csv.reader(f)
    for row in rows:
        if row[4] is int:
            sum = sum + float(row[4])
            x_length = x_length + 1
x_average = sum/len(x_length)
print(x_average)

我正在使用python 3.4.x

2 个答案:

答案 0 :(得分:2)

此示例可帮助您实现您尝试使用程序解决的目标:

import csv
import random
import statistics


def main():
    make_csv()
    read_csv_1()
    read_csv_2()


def make_csv():
    with open('2.5_week.csv', 'w', newline='') as file:
        writer = csv.writer(file)
        for index in range(1000):
            row = (random.random() * index,
                   random.randint(index, index * 2),
                   random.randrange(1 + index * 3),
                   random.random() + index,
                   random.randint(index, index + 10),
                   random.randrange(1 + index ** 2))
            writer.writerow(row)


def read_csv_1():
    with open('2.5_week.csv', 'r', newline='') as file:
        table = pivot_table(csv.reader(file))
    print(statistics.mean(map(float, table[4])))


def pivot_table(table):
    iterator = iter(table)
    pivot = tuple([cell] for cell in next(iterator))
    for row in iterator:
        for column, cell in zip(pivot, row):
            column.append(cell)
    return pivot


def read_csv_2():
    with open('2.5_week.csv', 'r', newline='') as file:
        print(statistics.mean(float(row[4]) for row in csv.reader(file)))

if __name__ == '__main__':
    main()

答案 1 :(得分:0)

total = 0
count = 0

with open("data.csv") as source:
    rdr = csv.reader(source, delimiter=',')
    next(rdr, None) #skip the header
    for row in rdr:
        try:
            if isinstance(float(row[4]),float):
                total+= float(row[4])
                count += 1
        except ValueError:
            pass

ave = round(total / count,2)
print(ave)