gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 04:24:47 24 4
gpt4 key购买 nike

我们必须计算 Excel 工作表中第 5 行的平均值,并保存为 csv 文件。文件的第一行包含使它们成为字符串的列的名称。我似乎无法获得一种循环所有行 [4] 并将其计算为一个变量“总和”的代码。这是我的代码。另外,

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

最佳答案

这个示例应该可以帮助您实现您试图通过程序解决的目标:

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()

关于python - 如何在Python中仅提取CSV文件的特定列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33285885/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com