Data Analysis

데이터 시각화, 박스 플롯, 조건별 그룹 통계

김심슨 2025. 5. 26. 15:31

+) 한글 폰트 사용하기 

from matplotlib import font_manager, rc # 폰트 세팅을 위한 모듈 추가
font_path = "C:/Windows/Fonts/malgun.ttf" # 사용할 폰트명 경로 삽입
font = font_manager.FontProperties(fname = font_path).get_name()
rc('font', family = font)

1. boxplot 

데이터 분포를 요약해 시각화한 그래프 

중앙값, 사분위수, 이상치를 한 눈에 확인 가능 

막대가 길다 = 분산이 크다  |  막대가 짧다 = 안정적

import pandas as pd
import matplotlib.pyplot as plt

df_score = pd.DataFrame({
    'name': ['홍길동', '강감찬', '이순신'],
    'kor': [90, 80, 70],
    'eng': [100, 90, 80],
    'math': [60, 50, 40]
})

df_score.boxplot(column=['kor', 'eng', 'math'])
plt.title('과목별 점수 분포')
plt.grid(True)
plt.show()

2. 조건부 컬럼 생성 

import numpy as np

df_score['test'] = np.where(df_score['math'] >=60, pass, fail)
print(df_score)
----- 출력 -----
   name  kor  eng  math  test
0  홍길동   90  100    60  pass
1  강감찬   80   90    50  fail
2  이순신   70   80    40  fail

3. 조건별 개수 세기 (value_counts())

print(df_score['test'].value_counts())
----- 출력 -----
fail 2
pass 1

=> 막대그래프와 함께 쓰면 강력한 시각화 가능 

4. 조건 중첩 (np.where 중첩 사용)

df_score['grade'] = np.where(df_score['math'] >= 60, 'A',
                      np.where(df_score['math'] >= 50, 'B', 'C'))
print(df_score)
----- 출력 -----
   name  math  test grade
0  홍길동    60  pass     A
1  강감찬    50  fail     B
2  이순신    40  fail     C

5. 정렬 (sort_values)

df_score.sort_values(by='math', ascending=False)

- ascending = False : 내림차순 (높은 점수부터 정렬)

- by = "math" : 정렬 기준 열