从csv文件中获取一些数字的平均值作为输入,并将平均值写入python 3中的输出csv文件中
我正在学习python3:),并尝试读取具有不同行的CSV文件 并取每个人(每行)的平均分数 并将其作为python 3的输出写入CSV文件中。 输入文件如下所示:从csv文件中获取一些数字的平均值作为输入,并将平均值写入python 3中的输出csv文件中,python,csv,Python,Csv,我正在学习python3:),并尝试读取具有不同行的CSV文件 并取每个人(每行)的平均分数 并将其作为python 3的输出写入CSV文件中。 输入文件如下所示: David,5,2,3,1,6 Adele,3,4,1,5,2,4,2,1 ... David,4.75 Adele,2.75 ... 输出文件应如下所示: David,5,2,3,1,6 Adele,3,4,1,5,2,4,2,1 ... David,4.75 Adele,2.75 ... 打印时,我似乎正确地读取了文件
David,5,2,3,1,6
Adele,3,4,1,5,2,4,2,1
...
David,4.75
Adele,2.75
...
输出文件应如下所示:
David,5,2,3,1,6
Adele,3,4,1,5,2,4,2,1
...
David,4.75
Adele,2.75
...
打印时,我似乎正确地读取了文件
终端中每个名称的平均值,但以CSV为单位
输出文件它只打印姓氏的平均值
输入文件,而我想打印所有的名称和
CSV输出文件中相应的平均值。
有人能帮我吗
import csv
from statistics import mean
these_grades = []
name_list = []
reader = csv.reader(open('input.csv', newline=''))
for row in reader:
name = row[0]
name_list.append(name)
with open('result.csv', 'w', newline='\n') as f:
writer = csv.writer(f,
delimiter=',',
quotechar='"',
quoting=csv.QUOTE_MINIMAL)
for grade in row[1:]:
these_grades.append(int(grade))
for item in name_list:
writer.writerow([''.join(item), mean(these_grades)])
print('%s,%f' % (name , mean(these_grades)))
您的代码中有几个问题:
与
)。没有理由在写入时使用它,但在读取时不使用它-因此您不会关闭“input.csv”文件'w'
模式下,在for
循环中重复打开文件。每次以写模式打开文件时,它都会擦除以前的所有内容。实际上,您会将每一行写入文件,但在下一次迭代中打开文件时,您只需再次擦除它import csv
import statistics
# use a context manager to read the data in too, not just for writing
with open('input.csv') as infile:
reader = csv.reader(infile)
data = list(reader)
# Create a dictionary to store the scores against the name
scores = {}
for row in data:
scores[row[0]] = row[1:] # First item in the row is the key (name) and the rest is values
with open('output.csv', 'w', newline='') as outfile:
writer = csv.writer(outfile)
# Now we need to iterate the dictionary and average the score on each iteration
for name, scores in scores.items():
ave_score = statistics.mean([int(item) for item in scores])
writer.writerow([name, ave_score])
这可以进一步巩固,但不太容易看到发生了什么:
with open('input.csv') as infile, open('output.csv', 'w', newline='') as outfile:
reader = csv.reader(infile)
writer = csv.writer(outfile)
for row in reader:
name = row[0]
values = row[1:]
ave_score = statistics.mean(map(int, values))
writer.writerow([name, ave_score])
将open('result.csv','w',newline='\n')作为f:
在for
循环的每次迭代中以write
模式打开文件。每次以写模式打开文件时,它都会擦除现有内容。因此,所有的结果都被写入,当您进入下一次迭代时,您只需将它们删除,然后使用open('result.csv','w',newline='\n')作为f:在读卡器:中的行上方,然后使用块适当地缩进以下代码,使其位于中,即使如此,您缺少聚合步骤。我将开始一个答案,但现在可能会被打败:非常感谢,我是在两周前开始使用python的,我发现了很多如何使用writerow在CSV文件中编写的方法,但没有一个是迭代的:)