TOP
class="layout-aside-left paging-number">
본문 바로가기
데이터분석 만능열쇠 [파이썬]/<파이썬 기초>

[파이썬] pivot_table

by 기록자_Recordian 2024. 4. 14.
728x90
반응형
시작에 앞서
해당 내용은 <파이썬으로 데이터 주무르기> -민형기 저, BJPUBLIC 출판사 의 내용을 토대로 작성되었습니다.
보다 자세한 내용은 해당 교재를 확인하여 주시기 바랍니다.

pivot_table 학습하기

 
하단 링크 접속 (깃허브)

 

pbpython/data at master · chris1610/pbpython

Code, Notebooks and Examples from Practical Business Python - chris1610/pbpython

github.com

 
saelsfunnel 엑셀 파일 다운로드 (파일명은 02. sales-funnel.xlsx 로 저장하였다)

salesfunnel 다운로드

pandas와 numpy 모듈을 불러온 후,
다운 받은 엑셀 파일 불러오기

다운로드 받은 엑셀 파일 불러오기


pivot_table(데이터명, index=["병합 기준 컬럼"] > 해당 데이터 기준으로 데이터 병합
pivot_table(데이터명, index=["컬럼"],values=["병합할 데이터(숫자)"])

 
pivot_table 을 사용하여 특정 컬럼의 데이터를 기준으로 데이터 병합
또한, 특정 value만 지정해서 나타나도록 할 수 있음

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

pivot_table 명령


aggfunc: pivot_table 때 다른 합산 옵션 부여

 
values를 pivot_table로 합친 경우 평균치가 기본이 되는데,
다른 옵션을 사용하려면 aggfunc 옵션을 사용

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

aggfunc 옵션 사용


fill_value 옵션으로 NaN 값 0으로 채우기

 
여러 index를 지정하고, 합산(np.sum)과 평균(np.mean)을 표시하고
NaN 값은 fill_value 옵션을 사용하여 0으로 채움

pd.pivot_table(df,index=["Manager","Rep","Product"],
               values=["Price","Quantity"],
               aggfunc=[np.sum,np.mean],fill_value=0,margins=True)

fill_value 옵션

 

728x90
반응형