Excel의 pivot table 기능을 python에서 작업하는 방법입니다.
python
1. working directory 설정 및 파일 import
import os
print(os.getcwd()) # check working directory
os.chdir("/home/brd/hdd/Researcher_PCY/SCI/") # Change me to working directory
print(os.getcwd()) # check changed working directory
import pandas as pd # importing pandas module
data = pd.read_csv("merger.csv") #change me as data file name
data.head() #displaying dataframe - Output 1
데이터 포맷은 아래와 같다.
여기서 'Genus' column에 피벗을 걸어줄 예정이다.
![](https://blog.kakaocdn.net/dn/ugUeR/btrT5su8rBT/A5bbBEzifv5J4x9pKF2GyK/img.png)
사진 설명을 입력하세요.
2. 피벗 실행
- Sum of Pivot
p_table = pd.pivot_table(data, index = ['Genus'], aggfunc = 'sum' ) # sum of pivot
print(p_table)
p_table.to_csv('merger_pivot.csv') #export file
- Average of Pivot
p_table = pd.pivot_table(data, index = ['Genus'], aggfunc = 'mean' ) # average of pivot
print(p_table)
p_table.to_csv('merger_pivot.csv') #export file
만약 피벗기능 중, 합치는게 아닌 다른 기능으로 하고싶다면
aggfun = 'mean' 값으로 바꾸면 된다.
mean은 평균값을 의미한다.