04_Index Object

Index Objects

  • Index Objects은 Index와 columns의 label과 메타정보를 저장하는 객체이다(The basic object storing axis labels for all pandas objects)
  • Series나 DataFrame을 생성할 때 label의 array는 자동적으로 Index 객체으로 변환되어 매핑된다.
  • 순위가 있고 slicing이 가능한 arary (Immutable ndarray implementing an ordered, sliceable set)
    • Index Object의 slicing을 가능하게 하는 index key(location)와 이에 대응하는 label이 있다.
    • label은 array로 표현되고 label이 유니크할 필요는 없다.
  • Index 객체는 Pandas에서 가장 어려운 개념에 속한다. Python for Data Analysis에 대부분에 독자는 Index객체에 대해 자세히 몰라도 되지만 Index 객체는 pandas의 데이터 모델 중에서 중요한 부분이라 노트 표시 되어 있다.
  • Index Objects docs를 보면 Index Objects 역시 여러가지의 메소드와 속성을 가지고 있는데 DataFrame 또는 Series의 그것들과 유사함을 확인할 수 있다.

  • 주요 메소드과 속성을 살펴 보면

    • Index(): Index객체를 생성함
    • df.index: DataFrame내의 index객체를 반환
    • df.columns: DataFrame내의 columns Index객체를 반환
    • get_loc:Label의 index key(위치, position)를 반환
In [1]:
import pandas as pd
import numpy as np
data = np.random.randn(16).reshape((4, 4))
columns = ['Arizona','Boston', 'Chicago','Detroit']
index = [2003,  2004, 2005, 2006]
df = pd.DataFrame(data, index = index, columns = columns)
In [2]:
# DataFrame을 생성하 때 자동으로 index 객체가 생성이 된다.
# index와 columns 함수는 DataFrame에서 index Object를 반환하는 함수 있다.  
obj1 = df.index
print(obj1)
obj2 = df.columns
print(obj2)
Int64Index([2003, 2004, 2005, 2006], dtype='int64')
Index(['Arizona', 'Boston', 'Chicago', 'Detroit'], dtype='object')
In [3]:
# Index 함수를 사용하여 생성함. 라벨의 중복을 허용함

obj3 = pd.Index(['Pari', 'Roma', 'Seoul','Pari'])
obj3
Out[3]:
Index(['Pari', 'Roma', 'Seoul', 'Pari'], dtype='object')
In [4]:
#index key로 indexing 하여 대응되는 label을 반환 
obj3[3]
Out[4]:
'Pari'
In [5]:
#index key로 slicing 하여 대응되는 label을 반환
obj3[1:3]
Out[5]:
Index(['Roma', 'Seoul'], dtype='object')
In [6]:
# index와 columns에 직접 index객체를 넣어 생성함.
df = pd.DataFrame(data, index = obj3, columns = obj3)

df
Out[6]:
PariRomaSeoulPari
Pari0.7901480.5207521.509777-0.934555
Roma-0.828068-0.019791-0.2097181.839801
Seoul-2.1899280.0033470.809648-0.094232
Pari-1.349733-0.2228710.150734-2.098341
In [7]:
obj3.get_slice_bound('Seoul', 'left', 'loc')
Out[7]:
2
In [8]:
#Label의 index key(위치, position)를 반환
obj3.get_loc('Seoul')
Out[8]:
2
In [9]:
#Label의 index key(위치, position)를 반환, label 이 중복인 경우 boolean array를 반환
obj3.get_loc('Pari')
Out[9]:
array([ True, False, False,  True], dtype=bool)


© 2017. All rights reserved.

Powered by ZooFighter v0.12