Pandas Index에서 중복 값 제거하기
Pandas에서 중복 값이 제거된 인덱스를 반환하려면 index.drop_duplicates() 메서드를 사용합니다. 이 메서드는 원본 인덱스는 그대로 유지한 채, 중복이 제거된 새로운 Index 객체를 반환합니다.
1단계: 라이브러리 임포트
먼저 필요한 라이브러리를 임포트합니다.
import pandas as pd
2단계: 중복 값을 포함하는 인덱스 생성
'Car'가 두 번 등장하는 것처럼, 일부 중복 값을 가진 인덱스를 생성합니다.
index = pd.Index(['Car','Bike','Truck','Car','Airplane'])
3단계: 인덱스 출력
생성된 인덱스를 화면에 출력해 확인합니다.
print("Pandas Index with duplicates...\n",index)4단계: drop_duplicates()로 중복 값 제거
중복 값이 제거된 인덱스를 반환합니다. 기본적으로(keep='first') 중복 값 중 첫 번째로 등장한 값을 유지하고, 이후에 등장한 중복 항목만 제거합니다.
print("\nIndex with duplicate values removed...\n",index.drop_duplicates())전체 예제 코드
다음은 지금까지 설명한 내용을 모두 포함한 전체 코드입니다.
import pandas as pd
# 중복 값을 포함하는 인덱스 생성
index = pd.Index(['Car','Bike','Truck','Car','Airplane'])
# 인덱스 출력
print("Pandas Index with duplicates...\n",index)
# 데이터의 dtype 확인
print("\nThe dtype object...\n",index.dtype)
# 데이터가 차지하는 바이트 수 확인
print("\nGet the bytes...\n",index.nbytes)
# 데이터의 차원 확인
print("\nGet the dimensions...\n",index.ndim)
# 중복 값이 제거된 인덱스 반환
# 기본적으로 첫 번째로 등장한 값은 유지됨
print("\nIndex with duplicate values removed...\n",index.drop_duplicates())실행 결과
위 코드를 실행하면 다음과 같은 결과가 출력됩니다.
Pandas Index with duplicates... Index(['Car', 'Bike', 'Truck', 'Car', 'Airplane'], dtype='object') The dtype object... object Get the bytes... 40 Get the dimensions... 1 Index with duplicate values removed... Index(['Car', 'Bike', 'Truck', 'Airplane'], dtype='object')
정리
실행 결과를 보면 원본 인덱스에는 5개의 요소('Car', 'Bike', 'Truck', 'Car', 'Airplane')가 있었지만, drop_duplicates() 호출 후 두 번째 'Car'가 제거되어 4개의 요소만 남은 것을 확인할 수 있습니다. 참고로 keep='last' 옵션을 사용하면 마지막으로 등장한 값을 유지하고, keep=False를 사용하면 중복된 모든 항목을 제거할 수도 있습니다.