8.1 파일에 저장된 학생 정보 처리
student_records.txt | Lee 80 90 95 90 Kim 85 75 70 95 Park 70 80 90 85 Hong 90 85 95 85 Yoon 85 85 95 80 |
output.txt | name : kor, eng, math, sci, sum, avg ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ Lee : 80, 90, 95, 90, 355, 88.75 Kim : 85, 75, 70, 95, 325, 81.25 Park : 70, 80, 90, 85, 325, 81.25 Hong : 90, 85, 95, 85, 355, 88.75 Yoon : 85, 85, 95, 80, 345, 86.25 ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ |
## 22211975_homework8
"""
Project: 22211975_homework8.1
Author:
Date of last update: 22.10.31
Update list:
-v1.0: added user-defined module
"""
def fread_data(file_name):
data_list = []
f = open(file_name, 'r', encoding='utf-8') # 읽기모드, utf-8 로 file_name을 open
for line in f:
# 데이터를 스페이스바를 기준으로 name, kor, eng, math, sci 로 나눔
name, kor, eng, math, sci = line.split()
tmp = [name, int(kor), int(eng), int(math), int(sci)]
data_list.append(tmp)
f.close()
return data_list
def fwrite_data(file_name, data_list):
f = open(file_name, 'w', encoding='utf-8') # 쓰기모드, utf-8 로 file_name을 open
f.write("name : kor, eng, math, sci, sum, avg\n")
f.write("‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐\n")
for data in data_list:
# s 에 name을 추가하고 kor, eng, math, sci, sum, avg 까지 차례로 추가한 뒤 개행문자 입력
s = "{0:5s}:".format(data[0])
s += "{0:4d},".format(data[1])
s += "{0:4d},".format(data[2])
s += "{0:4d},".format(data[3])
s += "{0:4d}, ".format(data[4])
s += "{0:4d}, ".format(data[5])
s += "{0:5.2f}".format(data[6])
s += '\n'
f.write(s)
f.write("‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐\n")
f.close()
def calculate_score(data_list):
i = 0
for name, kor, eng, math, sci in data_list:
sumScore = kor + eng + math + sci
data_list[i].append(sumScore) # kor, eng, math , sci 점수의 합
data_list[i].append(sumScore/4.0) # kor, eng, math, sci 점수값을 모두 더하므로 4로 나누어준다
i = i + 1
# Application
file_name = "student_records.txt"
students = fread_data(file_name) # 사용자 정의 함수로 students_records.txt 호출
print("\nRead from {} :".format(file_name))
for st_info in students:
print(st_info)
calculate_score(students)
print("\nAfter calculating student score")
print("=============================================")
print("name : kor, eng, math, sci, sum, avg")
for st_info in students:
s = ""
s = "{0:4s} :".format(st_info[0])
s += "{0:4d},".format(st_info[1])
s += "{0:4d},".format(st_info[2])
s += "{0:4d},".format(st_info[3])
s += "{0:4d}, ".format(st_info[4])
s += "{0:4d}, ".format(st_info[5])
s += "{0:5.2f}".format(st_info[6])
print(s)
print("=============================================")
fwrite_data("output.txt", students)
print("\nAvergae score of each class: ")
list_kor = []
list_eng = []
list_math = []
list_sci = []
f = open(file_name, 'r', encoding='utf-8')
for line in f:
# 각 줄에 있는 값을 리스트로 구분하여 정리함 -> 평균값을 구하기 위해서
name, kor, eng, math, sci = line.split()
list_kor.append(int(kor))
list_eng.append(int(eng))
list_math.append(int(math))
list_sci.append(int(sci))
f.close()
"""
파일 내용의 각각 line을 index와 연결되있는 데이터를 반환하여 list를 생성함.
list 에 있는 마지막 튜플의 첫번째 요소를 구해 +1을 하면 학생수를 구할 수 있다.
"""
cnt = list(enumerate(students))[-1][0]+1
print("Kor_avg =", sum(list_kor)/cnt)
print("Eng_avg = ", sum(list_eng)/cnt)
print("Math_avg = ", sum(list_math)/cnt)
print("Sci_avg = ", sum(list_sci)/cnt)
8.2 행렬 데이터 파일 입력 및 행렬 연산
wip
8.3 Pandas와 Excel 파일을 사용한 데이터 분석
## 22211975_homework7
"""
Project: 22211975_homework8.3
Author:
Date of last update: 22.11.01
Update list:
-v1.0: pandas - df, calculation of average of each class, save to Excel
"""
import pandas as pd
df = pd.read_excel('C:/Users/wjdrl/Desktop/컴사파/vscode/student_scores.xlsx')
print("\ndf =")
print(df)
avg_student = df[['Eng','Kor','Math', 'Sci']].mean(axis=1) # 열을 기준으로 평균값을 구함
df.loc[:, 'Avg'] = avg_student # Avg columns 에 평균값 추가
avg_class = df[['Eng','Kor','Math','Sci', 'Avg']].mean(axis=0) # 행을 기준으로 평균값을 구함
print("\navg_class =")
print(avg_class)
df.loc[len(df)] = avg_class
df.at[len(df)-1, 'st_name'] = 'Total Avg'
print("\ndf_sorted_with_avg =")
print(df.sort_values('Avg', ascending=False)) # Avg 행을 기준으로 오름차순으로 sort하여 출력함
print("Writing df to excel file")
with pd.ExcelWriter("processed_scores.xlsx") as excel_writer:
df.to_excel(excel_writer, sheet_name='Students Records')
'과제' 카테고리의 다른 글
컴사파 - 7주차 (0) | 2022.10.10 |
---|---|
컴사파 - 6주차 (1) | 2022.10.04 |
컴사파 - 5주차 (0) | 2022.09.28 |
컴사파 - 4주차 (0) | 2022.09.22 |
컴사파 - 3주차 (1) | 2022.09.17 |