본문으로 건너뛰기
김신건의 로그

[Pandas] pivot

· 수정 · 📖 약 1분 · 270자/단어 #python #pandas #reshape #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  250

Before (long-format):

dateproductsales
2024-01A100
2024-01B200
2024-02A150
2024-02B250

After (wide-format):

dateAB
2024-01100200
2024-02150250

행 라벨 (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

항목pivotpivot_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…

💬 댓글

사이트 검색 / 명령어

검색

스크롤 = 확대/축소 · 드래그 = 이동 · 0 = 원래 크기 · ESC = 닫기