02. Analysis Seoul Crime (Pandas pivot table)

JERRY·2025년 2월 9일

EDA

목록 보기
4/27
post-thumbnail

Pandas pivot table

  • index, columns, values, aggfunc
df = pd.read_excel("../data/02. sales-funnel.xlsx")
df.head()

index 설정

  • Name 컬럼을 인덱스로 설정
  • pd.pivot_table(df, index="Name")
df.pivot_table(index="Name")

  • 멀티 인덱스 설정
df.pivot_table(index=["Name", "Rep", "Manager"])

df.pivot_table(index=["Manager", "Rep"])

values 설정

df.pivot_table(index=["Manager", "Rep"], values="Price")

  • Price 컬럼 sum 연산 적용
df.pivot_table(index=["Manager", "Rep"], values="Price", aggfunc=np.sum)

df.pivot_table(index=["Manager", "Rep"], values="Price", aggfunc=[np.sum, len])

columns 설정

  • Product를 컬럼으로 지정
df.pivot_table(index=["Manager", "Rep"], values="Price", columns="Product", aggfunc=np.sum)

  • Nan 값 설정 : fill_value
df.pivot_table(index=["Manager", "Rep"], values="Price", columns="Product", aggfunc=np.sum, fill_value=0)

  • 2개 이상 index, values 설정
df.pivot_table(index=["Manager", "Rep", "Product"], values=["Price", "Quantity"], aggfunc=np.sum, fill_value=0)

  • aggfunc 2개 이상 설정
df.pivot_table(
    index=["Manager", "Rep", "Product"], 
    values=["Price", "Quantity"], 
    aggfunc=[np.sum, np.mean], 
    fill_value=0,
    margins=True)

0개의 댓글