[Pandas] DataFrame.style
Pandas style, Pandas Styler, DataFrame 서식
정의
DataFrame.style 는 HTML/CSS 기반 서식을 DataFrame 에 적용. Jupyter, 보고서, Excel 출력에 활용. 데이터 자체는 변하지 않고 표시 만 바뀐다.
자주 쓰는 메서드
| 메서드 | 효과 |
|---|---|
.format(...) | 숫자/날짜 포맷팅 |
.applymap(fn) / .map(fn) (2.1+) | 셀별 스타일 |
.apply(fn, axis=) | 컬럼/행 단위 스타일 |
.background_gradient(cmap=) | 색상 그라데이션 |
.bar() | 막대 시각화 |
.highlight_max(color=) | 최댓값 강조 |
.highlight_null() | NaN 강조 |
.set_caption(...) | 제목 |
.to_html() / .to_excel() | 내보내기 |
format
df.style.format({
'price': '{:,.0f} 원',
'rate': '{:.2%}',
'date': lambda x: x.strftime('%Y-%m-%d'),
})
| 포맷 | 의미 |
|---|---|
{:.2f} | 소수 2 자리 |
{:,.0f} | 천 단위 콤마 |
{:.2%} | 백분율 |
{:>10} | 우측 정렬 (10 칸) |
conditional 색상
df.style.background_gradient(cmap='RdYlGn', subset=['profit'])
# 빨강(낮) → 노랑 → 초록(높)
highlight
df.style.highlight_max(color='lightgreen')
df.style.highlight_min(color='salmon')
df.style.highlight_null(color='yellow')
df.style.highlight_between(left=0, right=100, color='lightblue')
사용자 정의 스타일
def color_negative(v):
return 'color: red' if v < 0 else ''
df.style.map(color_negative) # 모든 셀
df.style.map(color_negative, subset=['profit']) # 특정 컬럼만
apply (행/열 단위)
def highlight_max_row(s):
is_max = s == s.max()
return ['background-color: yellow' if v else '' for v in is_max]
df.style.apply(highlight_max_row, axis=1)
# 각 행의 max 값 강조
bar (셀 안 막대)
df.style.bar(subset=['sales'], color='lightgreen')
df.style.bar(subset=['profit'], color=['#ffcccc', '#ccffcc'], align='zero')
# 음수/양수 양방향 막대
보고서 내보내기
# HTML
df.style.format('{:.2f}').to_html('report.html')
# Excel (서식 포함)
df.style.background_gradient().to_excel('styled.xlsx')
# LaTeX
df.style.to_latex()
자주 쓰는 패턴
매출 보고서
report = monthly.style \
.format({'sales': '{:,.0f}', 'growth': '{:.1%}'}) \
.background_gradient(cmap='Greens', subset=['sales']) \
.applymap(lambda x: 'color: red' if x < 0 else 'color: green',
subset=['growth']) \
.highlight_max(subset=['sales'], color='gold')
report.to_excel('monthly_report.xlsx')
결측치 검사
df.style.highlight_null(color='red')
percentile 시각화
df.style.bar(color='lightblue', vmin=0, vmax=df.max().max())
함정
1. Style 는 view, 데이터 자체는 안 바뀜
styled = df.style.format('{:.2f}')
type(styled) # Styler (not DataFrame)
styled.data # 원본 DataFrame 접근
2. format 후 Excel 저장 시 dtype
df.style.format('{:.2f}').to_excel('out.xlsx')
# Excel 셀에는 그대로 숫자, 단지 표시 형식만
3. 무거운 스타일
수만 행에 그라데이션 적용 → 느림. 보고용 요약 데이터에 적합.
💬 댓글