[英]getting average of some digits from a csv file as input and Write the averages in an output csv file in python 3
我正在學習 python3 :),並且我正在嘗試讀取具有不同行的 CSV 文件,並取每個人(每行中)的分數的平均值並將其寫入 CSV 文件中作為 python 3 中的輸出。輸入文件如下:
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)))
您的代碼中有幾個問題:
with
)。 沒有理由在寫入時使用它而不是在閱讀時使用它 - 因此您不會關閉“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])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.