Pandas에서 index.argsort() 메서드를 사용하면 인덱스를 정렬했을 때 어떤 순서가 되는지를 나타내는 정수 인덱스 배열을 얻을 수 있습니다. 이 메서드는 NumPy의 argsort와 동일한 방식으로 동작하며, 실제로 인덱스 자체를 변경하지 않고 정렬에 필요한 위치 정보만 반환한다는 점이 특징입니다.
argsort() 메서드란?
argsort()는 각 요소를 오름차순으로 정렬했을 때 원래 위치(정수 인덱스)를 반환합니다. 이후 반환된 인덱스 배열을 원본 인덱스에 적용하면 정렬된 결과를 손쉽게 확인할 수 있습니다.
구현 단계
먼저 필요한 라이브러리를 임포트합니다 −
import pandas as pd
Pandas 인덱스를 생성합니다 −
index = pd.Index(['Electronics','Accessories','Decor', 'Books', 'Toys'], name ='Products')
생성된 Pandas 인덱스를 출력합니다 −
print("Pandas Index...\n",index)인덱스를 정렬하기 위한 정수 인덱스를 반환받습니다 −
res = index.argsort()
전체 예제 코드
다음은 전체 코드입니다 −
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)
res = index.argsort()
# 인덱스를 정렬하기 위한 정수 인덱스 반환
print("\nThe integer indices to sort the index...\n",res)
print("\nOrdered..\n",index[res])실행 결과
위 코드를 실행하면 다음과 같은 결과가 출력됩니다 −
Pandas Index... Index(['Electronics', 'Accessories', 'Decor', 'Books', 'Toys'], dtype='object', name='Products') Number of elements in the index... 5 The dtype object... object The integer indices to sort the index... [1 3 2 0 4] Ordered.. Index(['Accessories', 'Books', 'Decor', 'Electronics', 'Toys'], dtype='object', name='Products')
결과 해석
출력 결과를 보면 argsort()가 [1 3 2 0 4]라는 정수 인덱스 배열을 반환했습니다. 이는 'Accessories'(1), 'Books'(3), 'Decor'(2), 'Electronics'(0), 'Toys'(4) 순서로 정렬된다는 의미입니다. 반환된 인덱스를 원본 인덱스에 적용하면 알파벳순으로 정렬된 새로운 인덱스를 얻을 수 있습니다.