Pandas.stack
https://kimdingko-world.tistory.com/211:[Pandas] 데이터의 재구조화 stack & unstack
- stack : 위에서 아래로 (행방향)
- unstack : 왼쪽에서 오른쪽으로 (열방향)
import pandas as pd import numpy as np import seaborn as sns titanic = sns.load_dataset('titanic') titanic.head() wideUnstack = titanic.groupby(['pclass', 'sex'])[['survived', 'age', 'fare']].mean() wideUnstack # stack 함수는 시리즈를 반환 longStack = wideUnstack.stack() # (level=-1, dropna=True) 마지막꺼.. longStack longStack[1] longStack[1]['female'] longStack[1, 'female'] longStack[1]['female']['age'] longStack[1, 'female'][['survived','fare']] # 3개의 level p/s/3 longStack.unstack(-1) # (level=-1),(2) 2번index인 3이 열로가고 p/s 기준 longStack.unstack(0) # 0번 index인 p가 열로 가고 s/3 기준 longStack.unstack(1) # 1번 index인 s가 열로 가고 p/3 기준 # wideUnstack == longStack.unstack() longStack.unstack().equals(wideUnstack) # True wideUnstack sns.heatmap(wideUnstack)