■ Series 클래스의 unstack 메소드를 사용해 컬럼을 행으로 회전시켜 재구성한 것을 복원하는 방법을 보여준다.
▶ main.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 |
import pandas as pd import numpy as np valueListList = [ ["bar", "bar", "baz", "baz", "foo", "foo", "qux", "qux"], ["one", "two", "one", "two", "one", "two", "one", "two"] ] multiIndex = pd.MultiIndex.from_arrays(valueListList, names = ["first", "second"]) dataFrame1 = pd.DataFrame(np.random.randn(8, 2), index = multiIndex, columns = ["A", "B"]) print(dataFrame1) """ A B first second bar one 0.934435 1.055454 two -0.634130 1.229960 baz one -1.519993 1.254971 two -0.019397 0.182054 foo one 0.167189 0.165197 two -0.990571 -0.789641 qux one -0.922977 1.540567 two 1.213828 -1.346134 """ print() series = dataFrame1.stack(future_stack = True) # pandas 2.0.0 버전부터 도입된 새로운 구현 방식을 사용한다. print(series) """ first second bar one A 0.934435 B 1.055454 two A -0.634130 B 1.229960 baz one A -1.519993 B 1.254971 two A -0.019397 B 0.182054 foo one A 0.167189 B 0.165197 two A -0.990571 B -0.789641 qux one A -0.922977 B 1.540567 two A 1.213828 B -1.346134 dtype: float64 """ print() dataFrame2 = series.unstack() # 기본적으로 마지막 레벨을 언스택한다. print(dataFrame2) """ A B first second bar one 0.934435 1.055454 two -0.634130 1.229960 baz one -1.519993 1.254971 two -0.019397 0.182054 foo one 0.167189 0.165197 two -0.990571 -0.789641 qux one -0.922977 1.540567 two 1.213828 -1.346134 """ print() dataFrame3 = series.unstack(1) # 1번 레벨을 언스택한다. print(dataFrame3) """ second one two first bar A 0.934435 -0.634130 B 1.055454 1.229960 baz A -1.519993 -0.019397 B 1.254971 0.182054 foo A 0.167189 -0.990571 B 0.165197 -0.789641 qux A -0.922977 1.213828 B 1.540567 -1.346134 """ print() dataFrame4 = series.unstack(0) # 0번 레벨을 언스택한다. print(dataFrame4) """ first bar baz foo qux second one A 0.934435 -1.519993 0.167189 -0.922977 B 1.055454 1.254971 0.165197 1.540567 two A -0.634130 -0.019397 -0.990571 1.213828 B 1.229960 0.182054 -0.789641 -1.346134 """ |
▶ requirements.txt
1 2 3 4 5 6 7 8 |
numpy==2.1.2 pandas==2.2.3 python-dateutil==2.9.0.post0 pytz==2024.2 six==1.16.0 tzdata==2024.2 |
※ pip install pandas 명령을 실행했다.