exam.csv를 활용한 판다스 데이터 분석 & 시각화 입문
5개 반, 25명의 학생 성적 데이터입니다. 각 열의 의미는 다음과 같습니다.
no : 학생 번호 | nclass : 반 번호 (1~5)hours : 공부 시간 | extra : 과외 횟수math : 수학 점수 | eng : 영어 점수 | science : 과학 점수tot : 합계 점수 | test : 합격 여부 (Pass/Fail)판다스 분석에 필요한 라이브러리를 먼저 불러옵니다. pd.read_csv()로 CSV 파일을 DataFrame으로 읽어옵니다.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
# 한글 폰트 설정 (Windows)
matplotlib.rc('font', family='Malgun Gothic')
plt.rcParams['axes.unicode_minus'] = False
# CSV 파일 불러오기
df = pd.read_csv('exam.csv')
print(df)
데이터를 불러온 뒤 가장 먼저 크기, 열 정보, 데이터 타입을 확인합니다.
# 행 x 열 개수 확인
print("데이터 크기:", df.shape)
# 열 이름 확인
print("열 이름:", df.columns.tolist())
# 데이터 타입 및 결측치 확인
print(df.info())
# 앞에서 5행
print(df.head())
# 뒤에서 5행
print(df.tail())
# 특정 열만 보기 - 학생 번호와 과목 점수만
print(df[['no', 'math', 'eng', 'science']].head())
df.shape → (행 수, 열 수) / df.info() → 열 타입 + 결측치 요약 / df.head(n) → 위에서 n행 / df.tail(n) → 아래서 n행
df.describe()는 숫자형 열에 대해 개수, 평균, 표준편차, 최솟/최댓값, 사분위수를 한 번에 보여줍니다.
# 수치형 열 전체 통계 요약
df.describe()
특정 열이나 통계량만 따로 확인할 때 사용합니다.
# 과목별 평균
print("수학 평균:", df['math'].mean().round(1))
print("영어 평균:", df['eng'].mean().round(1))
print("과학 평균:", df['science'].mean().round(1))
# 합계 점수 최대·최솟값
print("최고 합계:", df['tot'].max())
print("최저 합계:", df['tot'].min())
# 공부 시간 중앙값 (중간값)
print("공부 시간 중앙값:", df['hours'].median())
# 여러 열 평균 한 번에
print(df[['math', 'eng', 'science']].mean().round(1))
범주형(문자) 열은 value_counts()로 빈도를 확인합니다.
# 합격/불합격 빈도 수
print(df['test'].value_counts())
# 비율로 보기 (normalize=True)
print(df['test'].value_counts(normalize=True).round(2))
대괄호 안에 조건식을 넣어 해당 행만 추출합니다. 조건식은 True/False로 평가됩니다.
# 1반 학생만
class1 = df[df['nclass'] == 1]
print(class1)
# 수학 점수 70점 이상
math_high = df[df['math'] >= 70]
print(math_high[['no', 'nclass', 'math', 'test']])
# 합격한 학생만
pass_df = df[df['test'] == 'Pass']
print(f"합격 학생 수: {len(pass_df)}명")
&(AND), |(OR) 연산자로 여러 조건을 결합합니다. 각 조건은 반드시 ()로 감싸야 합니다.
# AND: 수학 70점 이상 AND 영어 75점 이상
top = df[(df['math'] >= 70) & (df['eng'] >= 75)]
print("수학 70↑ & 영어 75↑:", len(top), "명")
print(top[['no', 'nclass', 'math', 'eng', 'test']])
# OR: 수학 80점 이상 OR 과학 80점 이상
excel = df[(df['math'] >= 80) | (df['science'] >= 80)]
print("수학 80↑ OR 과학 80↑:", len(excel), "명")
# isin(): 특정 반만 선택 (2반 또는 4반)
class24 = df[df['nclass'].isin([2, 4])]
print(class24[['no', 'nclass', 'math']])
query()는 문자열로 조건을 작성해 더 읽기 쉬운 코드를 만들 수 있습니다.
# query()로 동일한 조건 - 더 읽기 쉬움
result = df.query("math >= 70 and eng >= 75")
print(result[['no', 'nclass', 'math', 'eng']])
# 합격하고 공부 시간 30시간 이상
hardworking_pass = df.query("test == 'Pass' and hours >= 30")
print(hardworking_pass[['no', 'hours', 'tot', 'test']])
판다스에서는 and 대신 &, or 대신 |를 사용합니다. query() 안에서만 and/or를 사용할 수 있습니다.
groupby()는 특정 열의 값에 따라 데이터를 묶은 뒤 집계 함수를 적용합니다. Excel의 피벗 테이블과 유사합니다.
# 반별 수학 평균
print(df.groupby('nclass')['math'].mean().round(1))
# 반별 과목 평균 전체
class_mean = df.groupby('nclass')[['math', 'eng', 'science', 'tot']].mean().round(1)
print(class_mean)
# 반별 합격/불합격 인원 (crosstab)
ct = pd.crosstab(df['nclass'], df['test'])
print(ct)
# 반별 합격률 (비율로)
ct_pct = pd.crosstab(df['nclass'], df['test'], normalize='index').round(2)
print(ct_pct)
agg()로 여러 집계 함수를 동시에 적용할 수 있습니다.
# 반별 합계(tot) 통계: 평균, 최대, 최소, 중앙값
result = df.groupby('nclass')['tot'].agg(['mean', 'max', 'min', 'median']).round(1)
result.columns = ['평균', '최대', '최소', '중앙값']
print(result)
5반이 평균 합계 221.2점으로 1위, 3반이 159.0점으로 가장 낮습니다. groupby('열이름')['집계열'].집계함수() 패턴을 기억하세요!
# 과목 평균 점수 열 추가
df['avg'] = (df['math'] + df['eng'] + df['science']) / 3
df['avg'] = df['avg'].round(1)
print(df[['no', 'math', 'eng', 'science', 'avg']].head())
np.where(조건, 참일 때 값, 거짓일 때 값)으로 조건에 따라 값을 다르게 부여할 수 있습니다. 중첩해서 다중 조건도 처리합니다.
# 합계 기준 등급 부여: A(220↑), B(180↑), C(그 외)
df['grade'] = np.where(df['tot'] >= 220, 'A',
np.where(df['tot'] >= 180, 'B', 'C'))
print(df[['no', 'nclass', 'tot', 'grade']])
print("\n등급별 인원:")
print(df['grade'].value_counts().sort_index())
# 공부 효율 = 합계 / 공부시간 (1시간당 점수)
df['efficiency'] = (df['tot'] / df['hours']).round(1)
# 효율이 높은 상위 5명
top5 = df.nlargest(5, 'efficiency')
print(top5[['no', 'nclass', 'hours', 'tot', 'efficiency', 'grade']])
막대 그래프(bar chart)는 카테고리별 개수나 값을 비교할 때 가장 기본이 되는 그래프입니다. value_counts()로 개수를 센 다음 .plot.bar() 한 줄만 붙이면 됩니다.
# 합격/불합격 인원수 세기
counts = df['test'].value_counts()
# 막대 그래프 그리기
counts.plot.bar(color=['#2563eb', '#ef4444'], figsize=(7, 5))
plt.title('합격/불합격 인원')
plt.xlabel('')
plt.ylabel('인원 수')
plt.xticks(rotation=0)
plt.show()
히스토그램(histogram)은 점수가 어느 구간에 얼마나 모여 있는지 한눈에 보여주는 그래프입니다. 평균만 봐서는 알 수 없는 '분포의 모양'을 드러내 줍니다.
# 합계 점수 분포 히스토그램
df['tot'].plot.hist(bins=8, color='#2563eb',
edgecolor='white', figsize=(8, 5))
plt.title('합계 점수 분포')
plt.xlabel('합계 점수')
plt.ylabel('인원 수')
plt.show()
bins=8이면 전체 점수 범위를 8등분해서 그려요. 너무 적으면 뭉뚱그려지고, 너무 많으면 들쭉날쭉합니다.
산점도(scatter plot)는 두 변수가 같이 움직이는지(관계가 있는지)를 볼 때 사용합니다. 공부 시간이 늘면 점수도 함께 올라가는지 확인해 봅시다. 합격/불합격은 색으로 구분합니다.
# 합격은 파랑, 불합격은 빨강으로 색 지정
colors = df['test'].map({'Pass': '#2563eb', 'Fail': '#ef4444'})
# 산점도 그리기
df.plot.scatter(x='hours', y='tot',
c=colors, s=80, alpha=0.8,
figsize=(8, 6))
plt.title('공부 시간 vs 합계 점수')
plt.xlabel('공부 시간 (시간)')
plt.ylabel('합계 점수')
plt.show()
df.info()를 실행했을 때 확인할 수 없는 정보는 무엇인가요?df.info()는 열 이름·타입·결측치 수를 보여줍니다. 평균·최대값은 df.describe()로 확인합니다.math)가 70점 이상이고 합격(test == 'Pass')인 학생만 추출하는 올바른 코드는?&, OR 조건은 |를 사용하며 각 조건은 반드시 괄호 ()로 감쌉니다. Python의 and/or는 사용 불가!df.groupby('기준열')['집계열'].집계함수() — 기준이 되는 열을 groupby() 안에, 계산할 열을 [] 안에 씁니다.tot) 점수가 195점인 학생의 등급(grade)은?
df['grade'] = np.where(df['tot'] >= 220, 'A',
np.where(df['tot'] >= 180, 'B', 'C'))
np.where()는 조건을 위에서 아래로 순서대로 체크합니다.groupby('test')로 합격 여부를 나눠 색을 다르게 지정합니다.