[Pandas] pivot
Pandas pivot, DataFrame.pivot, long-to-wide
정의
DataFrame.pivot(index, columns, values) 는 long-format → wide-format 변환. 한 열의 고유 값들이 새 컬럼이 되고, 원래 데이터는 그 자리에 배치된다.
집계가 없으므로 같은 (index, columns) 조합이 두 번 있으면 에러. 집계가 필요하면 Pandas pivot_table.
시각화
기본
python
import pandas as pd
df = pd.DataFrame({
'date': ['2024-01', '2024-01', '2024-02', '2024-02'],
'product': ['A', 'B', 'A', 'B'],
'sales': [100, 200, 150, 250],
})
result = df.pivot(index='date', columns='product', values='sales')
print(result) 결과
product A B
date
2024-01 100 200
2024-02 150 250Before (long-format):
| date | product | sales |
|---|---|---|
| 2024-01 | A | 100 |
| 2024-01 | B | 200 |
| 2024-02 | A | 150 |
| 2024-02 | B | 250 |
After (wide-format):
| date | A | B |
|---|---|---|
| 2024-01 | 100 | 200 |
| 2024-02 | 150 | 250 |
행 라벨 (date) 는 유지, product 의 고유값 (A, B) 이 새 컬럼 이 됨.
여러 values
df.pivot(index='date', columns='product', values=['sales', 'qty'])
# MultiIndex 컬럼
중복 (index, columns) → 에러
df = pd.DataFrame({
'date': ['2024-01', '2024-01'],
'product': ['A', 'A'], # ← 중복!
'sales': [100, 50],
})
df.pivot(index='date', columns='product', values='sales')
# ValueError: Index contains duplicate entries, cannot reshape
해법: pivot_table (집계 사용).
df.pivot_table(index='date', columns='product', values='sales', aggfunc='sum')
# A → 150 (집계됨)
pivot 의 결과 처리
result = df.pivot(index='date', columns='product', values='sales')
result.columns.name = None # 'product' 이름 제거
result = result.reset_index() # date 를 컬럼으로
pivot vs pivot_table
| 항목 | pivot | pivot_table |
|---|---|---|
| 중복 (index, columns) | ❌ 에러 | ✓ aggfunc 로 집계 |
| 기본 aggfunc | 없음 | mean |
| values 생략 | ✓ (다른 컬럼들이 모두) | ✓ (numeric_only) |
| 속도 | 빠름 | 약간 느림 |
데이터가 이미 unique 한 long-format 이면 pivot, 아니면 pivot_table.
자주 만나는 함정
1. NaN 발생
# 일부 (date, product) 조합이 빠져 있으면 NaN
df.pivot(index='date', columns='product', values='sales')
# 빈 칸은 NaN
2. 컬럼 이름이 MultiIndex 가 됨
df.pivot(index='date', columns='product', values=['sales','qty'])
# 컬럼: ('sales','A'), ('sales','B'), ('qty','A'), ('qty','B')
평탄화: df.columns = ['_'.join(c) for c in df.columns].
3. unstack 과 거의 같음
df.set_index(['date', 'product'])['sales'].unstack()
# pivot 과 같은 결과 (MultiIndex 기반)
참고
이 글의 용어 (3개)
- [Pandas] meltpandas
- 정의 는 의 역방향. wide-format → long-format 변환. 여러 컬럼을 두 컬럼 ( , ) 으로 합친다. 장기간 시계열 데이터나 시각화 (ggplot, seabo…
- [Pandas] pivot_tablepandas
- 정의 는 의 확장. 집계 함수를 동반 해 중복 (index, columns) 도 처리. Excel 의 피벗 테이블과 가장 가까운 기능. 기본 <CodeWithOutput lang…
- [Pandas] stack / unstackpandas
- 정의 - : 가장 안쪽 컬럼 레벨 → 행 레벨 (DataFrame → Series 또는 더 좁은 DataFrame) - : 가장 안쪽 행 레벨 → 컬럼 레벨 / 의 MultiIn…
💬 댓글