15 MultiIndex
| 6 Minute Read on Pandas
MultiIndex¶
- MultiIndex는 A multi-level, or hierarchical, index object로 정의된다.MultiIndex Docs
- MultiIndex 중요 세요소로는
- levels : 계층에 대한 이름(The unique labels for each level)
- labels : 각 이름별 계층 위치 (Integers for each level designating which label at each location)
- names : 레벨에 대한 이름( Names for each of the index levels.)
- MultiIndex 생성하는 메소드는 다음과 같음
- from_arrays(arrays[, sortorder, names])
- from_tuples(tuples[, sortorder, names])
- from_product(iterables[, sortorder, names])
- unstack()을 사용하여 columns을 index의 변경하여 MultiIndex를 생성할 수 있음 .
In [1]:
import pandas as pd
import numpy as np
arrays = [['Arizona','Boston','Chicago','Detroit', 'Arizona','Boston','Chicago','Detroit']
,['First','Second','First','Second','First','Second','First','Second']]
In [2]:
# from_arrays로 MulitIndex
index = pd.MultiIndex.from_arrays(arrays, names=('Team','Season'))
#level, label, names의 3요소가 생성이 됨
index
Out[2]:
In [3]:
# MulitIndex로 Series를 생성함
srz = pd.Series(np.random.randn(8), index=index)
srz
Out[3]:
In [4]:
#MulitIndex로 DataFrame을 생성함
df = pd.DataFrame(np.random.randn(8, 2), index=index)
df
Out[4]:
In [5]:
# from_tuples로 MultiIndex 객채를 생성
tuples = list(zip(*arrays)) #* unpack operator
print(tuples)
index = pd.MultiIndex.from_tuples(tuples, names=['Team','Season'])
index
Out[5]:
In [11]:
# from_product로 MultiIndex 객채를 생성
Team = ['Arizona', 'Boston', 'Chicago', 'Detroit']
Season = ['First', 'Second']
index = pd.MultiIndex.from_product([Team, Season ], names=['Team','Season'])
index
Out[11]:
In [7]:
import pandas as pd
import numpy as np
data = np.random.randn(3, 4)
index = [2002, 2003, 2004 ]
columns = ['Apple','Lemon', 'Orange','Tomato']
df = pd.DataFrame(data = data, index = index, columns = columns)
df
Out[7]:
In [8]:
#unstack()을 통해서 DataFrame의 Columns이 index로 변경됨
df.unstack()
Out[8]:
In [9]:
df = df.unstack()
In [10]:
print(type(df))
df.index
Out[10]: