Computer >> 컴퓨터 >  >> 프로그래밍 >> Python

Python Pandas - drop_duplicates()로 중복 값이 완전히 제거된 인덱스 반환하기

Pandas에서 중복 값이 완전히 제거된 인덱스를 반환하려면 index.drop_duplicates() 메서드를 사용하면 됩니다. 특히 keep 매개변수를 False로 설정하면, 중복으로 나타나는 값들을 모두 제거할 수 있습니다.

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 = False를 지정하면, 각 중복 항목 집합에 대해 해당 값의 모든 등장(occurrence)이 제거됩니다. 즉, 'Airplane'처럼 중복된 값은 결과 인덱스에서 완전히 사라집니다.

print("\nIndex with duplicate values removed (drops all occurrences)...\n",
index.drop_duplicates(keep = False))

전체 예제 코드

다음은 위 내용을 모두 포함한 전체 코드입니다.

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)

# 중복 값이 제거된 인덱스 반환
# "keep" 매개변수를 "False"로 설정하면 중복 항목의 모든 등장이 제거됨
print("\nIndex with duplicate values removed (drops all occurrences)...\n",
index.drop_duplicates(keep = False))

실행 결과

위 코드를 실행하면 다음과 같은 결과가 출력됩니다.

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 (drops all occurrences)...
Index(['Car', 'Bike', 'Ship'], dtype='object')

정리

drop_duplicates()는 기본적으로 첫 번째 중복 항목만 유지하지만, keep=False 옵션을 사용하면 중복된 값 자체를 완전히 제거할 수 있습니다. 데이터 정제 과정에서 고유한 값만 남기고 싶을 때 유용하게 활용할 수 있습니다.