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

2024-04-20 12:58:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我们要计算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)

我使用的是python3.4.x


Tags: 文件csv字符串代码import名称密码os
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()
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)

相关问题 更多 >