Pandas에서 Index 객체에 포함된 고유한 값들의 개수를 담은 Series를 반환하려면 index.value_counts() 메서드를 사용합니다. 이 메서드는 인덱스에 있는 각 고유 값이 몇 번 등장하는지 계산해 주며, 기본적으로 개수가 많은 순서대로(내림차순) 정렬된 결과를 반환합니다.
기본 사용 방법
먼저 필요한 라이브러리를 임포트합니다.
import pandas as pd
Pandas 인덱스를 생성합니다.
index = pd.Index([50, 10, 70, 110, 90, 50, 110, 90, 30])
생성한 Pandas 인덱스를 출력합니다.
print("Pandas Index...\n", index)고유한 값의 개수를 확인합니다.
print("\nGet the count of unique values...\n", index.value_counts())전체 예제 코드
다음은 지금까지 설명한 내용을 모두 포함한 전체 코드입니다.
import pandas as pd
# Pandas 인덱스 생성
index = pd.Index([50, 10, 70, 110, 90, 50, 110, 90, 30])
# 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("\nGet the count of unique values...\n", index.value_counts())실행 결과
위 코드를 실행하면 다음과 같은 결과가 출력됩니다.
Pandas Index... Int64Index([50, 10, 70, 110, 90, 50, 110, 90, 30], dtype='int64') Number of elements in the index... 9 The dtype object... int64 Get the count of unique values... 50 2 110 2 90 2 10 1 70 1 30 1 dtype: int64
결과 해석
출력 결과를 보면 50, 110, 90은 각각 2번씩 나타나며, 10, 70, 30은 각각 1번씩 나타나는 것을 확인할 수 있습니다. 이처럼 value_counts() 메서드를 활용하면 인덱스 데이터의 빈도 분포를 손쉽게 파악할 수 있어, 데이터 분석 시 중복 값 검토나 빈도 기반 정렬 작업에 유용하게 활용됩니다.