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

Python Pandas – 마지막 항목을 제외한 중복 인덱스 값 표시하기

Pandas에서 마지막 항목을 제외한 중복 인덱스 값을 확인하려면 index.duplicated() 메서드를 사용하고, keep 매개변수에 'last' 값을 지정하면 됩니다. 이렇게 하면 중복된 값 중 가장 마지막에 등장하는 항목은 False로 유지되고, 나머지 중복 항목들은 True로 표시됩니다.

duplicated() 메서드란?

duplicated()는 인덱스 내에서 중복된 값을 찾아 불리언(Boolean) 배열로 반환하는 메서드입니다. keep 매개변수는 어떤 항목을 유지할지(즉, False로 표시할지) 결정하며, 다음 세 가지 값을 사용할 수 있습니다.

  • 'first'(기본값): 첫 번째 항목을 유지하고 이후의 중복 항목을 True로 표시
  • 'last': 마지막 항목을 유지하고 앞선 중복 항목을 True로 표시
  • False: 모든 중복 항목을 True로 표시

구현 단계

먼저 필요한 라이브러리를 가져옵니다.

import pandas as pd

중복 값이 포함된 인덱스를 생성합니다.

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

생성된 인덱스를 출력하여 확인합니다.

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

마지막 항목을 제외한 중복 값을 표시하기 위해 keep 매개변수를 'last'로 설정합니다.

print("\nIndicating duplicate values except the last occurrence...\n", index.duplicated(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 dimensions...\n", index.ndim)

# 마지막 항목을 제외한 중복 인덱스 값을 True로 표시
# keep 매개변수를 'last'로 설정
print("\nIndicating duplicate values except the last occurrence...\n", index.duplicated(keep='last'))

실행 결과

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

Pandas Index with duplicates...
Index(['Car', 'Bike', 'Airplane', 'Ship', 'Airplane'], dtype='object')

The dtype object...
object

Get the dimensions...
1

Indicating duplicate values except the last occurrence...
[False False True False False]

결과 해석

출력 결과를 보면 'Airplane'이 두 번째와 다섯 번째 위치에서 중복되어 있습니다. keep='last' 옵션을 사용했기 때문에 두 번째 위치의 'Airplane'만 True로 표시되고, 마지막(다섯 번째) 위치의 'Airplane'은 False로 유지됩니다. 이를 통해 중복 제거 작업 시 마지막 항목을 보존하면서 앞쪽의 중복 항목만 손쉽게 식별할 수 있습니다.