Pandas 라이브러리 없이 순수 파이썬 문법만으로 CSV 파일을 읽고, 데이터를 분석하여 정렬하는 방법을 정리합니다.
,)로 구분하는 포맷.\t)으로 구분하는 포맷.외부 라이브러리 없이 open()과 split()만을 사용하여 데이터를 파싱하고 분석합니다.
f.readline()을 호출하여 컬럼명(첫 번째 줄)은 건너뛴다.split(",")으로 쪼개어 필요한 데이터(생존 여부, 객실 등급)를 추출한다. import os
1. 파일 경로 설정 및 읽기
base_path = r'/content/drive/MyDrive/dataset'
file_path = os.path.join(base_path, 'titanic.csv')
result = {}
with open(file_path, 'r', encoding='utf-8') as f:
f.readline() # 헤더(첫 줄) 스킵
for line in f:
psgr = line.split(",")
survived = int(psgr[1]) # 생존 여부 (1: 생존, 0: 사망)
pclass = int(psgr[2]) # 객실 등급 (1, 2, 3)
# 등급별로 데이터 분류 저장
if result.get(pclass):
result[pclass].append(survived)
else:
result[pclass] = [survived]
데이터를 보기 좋게 출력하기 위해 정렬 기능을 활용합니다.
data = [10, 4, 5, 6, -3]
# 오름차순
data.sort()
# 내림차순
data.sort(reverse=True)
딕셔너리의 items()를 사용하여 키(key)나 값(value) 기준으로 정렬할 수 있습니다.
myDict = {"b": 5, "c": 3, "a": 2}
# 키 기준으로 정렬된 리스트 반환
sorted_keys = sorted(myDict.items()) # [('a', 2), ('b', 5), ('c', 3)]
# 값(Value) 기준으로 정렬 (lambda 활용)
sorted_values = sorted(myDict.items(), key=lambda x: x[1])
sorted(result.items())를 활용하여 1등급부터 3등급까지 순서대로 분석 결과를 출력합니다.
# 분석결과 출력 루프
for pclass, survives in sorted(result.items()):
total = len(survives)
survived_count = survives.count(1)
survival_rate = (survived_count / total) * 100
print(f"{pclass}등급] 총 {total}명, 생존 {survived_count}명, 생존률 {survival_rate:.1f}%")
# [실행 결과 예시]
1등급] 총 216명, 생존 136명, 생존률 63.0%
2등급] 총 184명, 생존 87명, 생존률 47.3%
3등급] 총 491명, 생존 119명, 생존률 24.2%
# titanic.csv 파일
# 컬럼 의미
survival - Survival (0 = No; 1 = Yes)
Pclass - Passenger Class (1 = 1st; 2 = 2nd; 3 = 3rd)
name - Name
sex - Sex
age - Age
sibsp - Number of Siblings/Spouses Aboard
parch - Number of Parents/Children Aboard
ticket - Ticket Number
fare - Passenger Fare
cabin - Cabin
embarked - Port of Embarkation (C = Cherbourg; Q = Queenstown; S = Southampton)
boat - Lifeboat (if survived)
body - Body number (if did not survive and body was recovered)
data[1]
# 1,0,3,"Braund, Mr. Owen Harris",male,22,1,0,A/5 21171,7.25,,S\n