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

[Pandas] pivot_table

· 수정 · 📖 약 1분 · 188자/단어 #python #pandas #reshape #pivot #aggregation
Pandas pivot_table, pd.pivot_table, Excel pivot

정의

DataFrame.pivot_table(...)Pandas pivot 의 확장. 집계 함수를 동반 해 중복 (index, columns) 도 처리. Excel 의 피벗 테이블과 가장 가까운 기능.

기본

df.pivot_table(
    index='date',
    columns='product',
    values='sales',
    aggfunc='sum',
)
python
import pandas as pd
df = pd.DataFrame({
  'date': ['2024-01', '2024-01', '2024-01', '2024-02', '2024-02'],
  'product': ['A', 'A', 'B', 'A', 'B'],
  'sales': [100, 50, 200, 150, 250],
})
print(df.pivot_table(index='date', columns='product', values='sales', aggfunc='sum'))
결과
product     A    B
date
2024-01   150  200
2024-02   150  250
dateAB
2024-01150 (= 100+50)200
2024-02150250

여러 aggfunc

df.pivot_table(
    index='date',
    columns='product',
    values='sales',
    aggfunc=['sum', 'mean', 'count'],
)

margins (총계)

df.pivot_table(
    index='date',
    columns='product',
    values='sales',
    aggfunc='sum',
    margins=True,
    margins_name='Total',
)
dateABTotal
2024-01150200350
2024-02150250400
Total300450750

Excel 의 총계 행/열과 동일.

여러 index / values

df.pivot_table(
    index=['region', 'date'],
    columns='product',
    values=['sales', 'qty'],
    aggfunc='sum',
)

MultiIndex 행 + MultiIndex 컬럼.

fill_value

df.pivot_table(..., fill_value=0)   # NaN 을 0 으로

groupby 와의 관계

pivot_table 은 사실 groupby + unstack 의 단축형.

# 둘은 같음
df.pivot_table(index='date', columns='product', values='sales', aggfunc='sum')
df.groupby(['date', 'product'])['sales'].sum().unstack('product')

자주 쓰는 패턴

월별/카테고리별 매출 보고서

report = df.pivot_table(
    index='month',
    columns='category',
    values='revenue',
    aggfunc='sum',
    margins=True,
    fill_value=0,
)
report.to_excel('monthly_report.xlsx')

코호트 분석

df['cohort'] = df['signup_month']
df['period'] = (df['active_month'] - df['cohort']).dt.days // 30
df.pivot_table(index='cohort', columns='period', values='user_id', aggfunc='nunique')

함정

1. 기본 aggfunc 가 mean

df.pivot_table(index='date', columns='product', values='sales')
# 명시 안 하면 'mean'

매출 같은 경우 ‘sum’ 을 명시하자.

2. observed (categorical)

df.pivot_table(index='cat_col', ..., observed=False)
# Categorical index 의 모든 카테고리 포함 (등장 안 한 것도)

pandas 2.x 에서는 observed=False 가 deprecated, 명시 권장.

3. dropna

df.pivot_table(index='date', columns='product', values='sales', dropna=False)
# NaN 행을 보존

참고

이 글의 용어 (4개)
[Pandas] crosstabpandas
정의 는 두 (또는 그 이상의) Series 로 교차 빈도표 (contingency table) 를 만든다. SQL 의 PIVOT 또는 Excel 의 피벗 테이블과 비슷. 기본 …
[Pandas] groupbypandas
정의 는 데이터를 그룹으로 나누고 (split), 각 그룹에 함수를 적용 (apply), 결과를 합쳐 (combine) 새 DataFrame 으로 만드는 split-apply-c…
[Pandas] meltpandas
정의 는 의 역방향. wide-format → long-format 변환. 여러 컬럼을 두 컬럼 ( , ) 으로 합친다. 장기간 시계열 데이터나 시각화 (ggplot, seabo…
[Pandas] pivotpandas
정의 는 long-format → wide-format 변환. 한 열의 고유 값들이 새 컬럼이 되고, 원래 데이터는 그 자리에 배치된다. 집계가 없으므로 같은 (index, co…

💬 댓글

사이트 검색 / 명령어

검색

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