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

Python Pandas – 마지막 항목을 유지하며 중복 값이 제거된 인덱스 반환하기

Pandas에서 마지막 항목을 유지하면서 중복 값이 제거된 인덱스를 반환하려면 index.drop_duplicates() 메서드를 사용하면 됩니다. 이때 keep 매개변수에 'last' 값을 지정하면, 각 중복 항목 그룹에서 가장 마지막에 등장한 값만 남기고 나머지는 모두 제거됩니다.

1. 필요한 라이브러리 임포트

먼저 pandas 라이브러리를 임포트합니다.

import pandas as pd

2. 중복 값이 있는 인덱스 생성

중복 값('Airplane')을 포함하는 인덱스를 생성합니다.

index = pd.Index(['Car', 'Bike', 'Airplane', 'Ship', 'Airplane'])

생성된 인덱스를 출력하여 확인해 보겠습니다.

print("Pandas Index with duplicates...\n", index)

3. 중복 값 제거하기 (마지막 항목 유지)

drop_duplicates() 메서드에 keep='last'를 지정하면 중복된 항목들 중 마지막으로 등장한 값이 유지됩니다.

print("\nIndex with duplicate values removed (keeping the last occurrence)...\n", index.drop_duplicates(keep='last'))

전체 예제 코드

다음은 지금까지의 내용을 모두 포함한 전체 코드입니다.

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='last'는 각 중복 항목 집합에서 마지막 항목을 유지함
print("\nIndex with duplicate values removed (keeping the last occurrence)...\n",
      index.drop_duplicates(keep='last'))

실행 결과

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

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 last occurrence)...
Index(['Car', 'Bike', 'Ship', 'Airplane'], dtype='object')

결과 해석

원본 인덱스에는 'Airplane'이 두 번 등장합니다(위치 2와 4). keep='last' 옵션을 적용하면 앞쪽의 'Airplane'은 제거되고, 마지막에 등장한 'Airplane'만 남습니다. 따라서 최종 결과는 ['Car', 'Bike', 'Ship', 'Airplane'] 순서로 반환됩니다.

참고로 keep 매개변수의 기본값은 'first'입니다. 이 경우 첫 번째 항목이 유지되어 ['Car', 'Bike', 'Airplane', 'Ship']가 반환됩니다. 또한 keep=False를 지정하면 중복된 모든 항목이 완전히 제거됩니다.