Pandas에서 index.take() 메서드를 사용하면 지정한 인덱스 위치에 해당하는 값들로 구성된 새로운 Index 객체를 반환할 수 있습니다. 이 메서드는 원본 인덱스의 특정 위치에 있는 요소들을 추출할 때 유용하게 활용됩니다.
필수 라이브러리 임포트
먼저 필요한 라이브러리를 가져옵니다.
import pandas as pd
Pandas 인덱스 생성
상품 이름으로 구성된 Pandas 인덱스를 생성합니다.
index = pd.Index(['Electronics','Accessories','Decor', 'Books', 'Toys'], name ='Products')
인덱스 출력하기
생성한 Pandas 인덱스를 화면에 표시합니다.
print("Pandas Index...\n",index)take()로 새로운 인덱스 얻기
인덱스 위치 [1, 2]에 해당하는 값들로 새로운 인덱스를 생성합니다.
print("\nA new Index of the values selected by the indices...\n",index.take([1,2]))전체 예제 코드
아래는 위 과정을 모두 포함한 전체 코드입니다.
import pandas as pd
# Pandas 인덱스 생성
index = pd.Index(['Electronics','Accessories','Decor', 'Books', 'Toys'], name ='Products')
# Pandas 인덱스 출력
print("Pandas Index...\n",index)
# 인덱스의 요소 개수 반환
print("\nNumber of elements in the index...\n",index.size)
# 데이터의 dtype 반환
print("\nThe dtype object...\n",index.dtype)
# 지정한 인덱스 위치의 값들로 새로운 인덱스 생성
print("\nA new Index of the values selected by the indices...\n",index.take([1,2]))실행 결과
위 코드를 실행하면 다음과 같은 결과가 출력됩니다.
Pandas Index... Index(['Electronics', 'Accessories', 'Decor', 'Books', 'Toys'], dtype='object', name='Products') Number of elements in the index... 5 The dtype object... object A new Index of the values selected by the indices... Index(['Accessories', 'Decor'], dtype='object', name='Products')
출력 결과를 보면 take([1, 2])가 위치 1과 2에 해당하는 'Accessories'와 'Decor' 값을 선택하여, 기존 인덱스와 동일한 dtype('object')과 name('Products') 속성을 유지하는 새로운 Index 객체를 반환한 것을 확인할 수 있습니다.