[英]Reading input files and writing into output files - Python
我有一個包含以下信息的輸入文件 (input.txt):
所以文本文件看起來像這樣
4
5
Jane Doe,80,75,90,100,95,68
Sara Jones,65,80,72,90,75,80
Bill Smith,50,70,90,70,55,90
John Foles,95,90,85,80,88
我正在嘗試創建一個 python 程序來讀取這些信息,並將某些值(班級平均分數、學生姓名、學生分數等)輸出到不同的文件 (output.txt) 中。
我一直在努力解決它,但我永遠無法讓我的程序完成我需要的一切。 例如,我只能輸出班級平均成績,或僅輸出一名學生的分數。 我不知道如何輸出多個函數。
我真的可以使用一些幫助。
為此,您將需要使用Pandas (另請參閱Pandas 手冊)。
首先,將以下內容復制到剪貼板:
Jane Doe,80,75,90,100,95,68
Sara Jones,65,80,72,90,75,80
Bill Smith,50,70,90,70,55,90
John Foles,95,90,85,80,88
接下來,運行以下腳本:
#%% Load Your Data
import pandas as pd
df = pd.read_clipboard(sep = ',')
# YOU WILL HAVE TO LOAD YOUR ACTUAL DATA AS FOLLOWS:
# file_path = 'path/to/your/file.txt'
# df = pd.read_csv()
number_of_students = df.shape[0]
number_of_tests = df.shape[1] -1 # This is the number of columns you have
score_names = ['score' + str(number+1) for number in range(number_of_tests)]
df.columns = ['student'] + score_names # Prepares the column names
df.set_index('student',inplace=True) # Makes the student names the index
#%% Calculate Maximum, Minimum and Average Class Score per test
score_summaries = df.describe()
#%% Calulate the average score for all students across all tests
average_exam_score = df.mean().mean()
#%% A single students' score
df.loc['Sara Jones']
該腳本將計算您的幾個請求。 它不做的一件事是加載您的文件(您必須刪除包含學生人數和考試成績的行,但不用擔心,它是根據分數數據本身重新計算的)。 我在評論中包含了有關如何執行此操作的提示,並將其留給您實施。
我鼓勵您仔細閱讀並探索刪除某些行或更改其他行會產生什么效果。
最后,我代表 SO 社區說歡迎! 我知道你的開局似乎很艱難(所有的反對票都是如此),但不要讓這讓你氣餒。 通讀如何問一個好問題,回來幫助我們一起學習!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.