Pandas에서 인덱스(Index)에 포함된 중복 값을 제거하되 첫 번째 등장한 항목만 유지하고 싶다면 index.drop_duplicates() 메서드를 사용하면 됩니다. 이때 keep 매개변수에 'first' 값을 지정하면 각 중복 그룹에서 가장 처음 나온 값이 남게 됩니다.
1. 라이브러리 임포트
먼저 필요한 라이브러리를 임포트합니다.
import pandas as pd
2. 중복 값이 있는 인덱스 생성
중복 항목('Airplane')이 포함된 인덱스를 만들어 보겠습니다.
index = pd.Index(['Car', 'Bike', 'Airplane', 'Ship', 'Airplane'])
3. 인덱스 출력
생성된 인덱스를 화면에 표시합니다.
print("Pandas Index with duplicates...\n", index)
4. 첫 번째 항목을 유지하며 중복 제거
drop_duplicates() 메서드에 keep='first'를 지정하면, 중복된 항목들 중 각 그룹의 첫 번째 등장 값만 유지되고 나머지는 모두 제거됩니다.
index.drop_duplicates(keep='first')
전체 예제 코드
아래는 위 과정을 모두 포함한 전체 코드입니다.
import pandas as pd
# 중복 값이 있는 인덱스 생성
index = pd.Index(['Car', 'Bike', 'Airplane', 'Ship', '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 (keeping the first occurrence)...\n",
index.drop_duplicates(keep='first'))
실행 결과
위 코드를 실행하면 다음과 같은 결과가 출력됩니다.
Pandas Index with duplicates...
Index(['Car', 'Bike', 'Airplane', 'Ship', 'Airplane'], dtype='object')
The dtype object...
object
Get the bytes...
40
Get the dimensions...
1
Index with duplicate values removed (keeping the first occurrence)...
Index(['Car', 'Bike', 'Airplane', 'Ship'], dtype='object')
정리
실행 결과를 보면 원래 인덱스에는 'Airplane'이 두 번 등장했지만, drop_duplicates(keep='first')를 적용한 후에는 첫 번째 'Airplane'만 남고 두 번째 항목이 제거된 것을 확인할 수 있습니다.
참고로 keep 매개변수에는 다음과 같은 값을 사용할 수 있습니다.
- 'first': 첫 번째 등장한 값만 유지 (기본값)
- 'last': 마지막에 등장한 값만 유지
- False: 중복된 항목을 모두 제거