Pandas에서 전달된 위치의 요소가 삭제된 새로운 인덱스(Index)를 만들려면 index.delete() 메서드를 사용하면 됩니다. 이 메서드는 원본 인덱스는 그대로 유지한 채, 지정한 위치의 요소만 제거된 새로운 Index 객체를 반환합니다.
먼저 필요한 라이브러리를 임포트합니다.
import pandas as pd
인덱스를 생성합니다.
index = pd.Index([15, 25, 35, 45, 55])
생성된 인덱스를 출력해 확인합니다.
print("Pandas Index...\n",index)3번째 위치, 즉 인덱스 2에 해당하는 요소 하나를 삭제합니다.
print("\nRemaining Index after deleting an index at location 3rd (index 2)...\n",index.delete(2))예제
지금까지 설명한 내용을 모두 담은 전체 코드는 다음과 같습니다.
import pandas as pd
# 인덱스 생성
index = pd.Index([15, 25, 35, 45, 55])
# 인덱스 출력
print("Pandas Index...\n",index)
# 인덱스의 요소 개수 반환
print("\nNumber of elements in the index...\n",index.size)
# 내부 데이터의 형태(shape) 튜플 반환
print("\nA tuple of the shape of underlying data...\n",index.shape)
# 데이터의 바이트 크기 확인
print("\nReturn the bytes...\n",index.nbytes)
# 데이터의 차원 확인
print("\nReturn the dimensions...\n",index.ndim)
# 3번째 위치(인덱스 2)의 요소 하나 삭제
print("\nRemaining Index after deleting an index at location 3rd (index 2)...\n",index.delete(2))출력 결과
위 코드를 실행하면 다음과 같은 결과가 출력됩니다.
Pandas Index... Int64Index([15, 25, 35, 45, 55], dtype='int64') Number of elements in the index... 5 A tuple of the shape of underlying data... (5,) Return the bytes... 40 Return the dimensions... 1 Remaining Index after deleting an index at location 3rd (index 2)... Int64Index([15, 25, 45, 55], dtype='int64')
추가 팁
delete() 메서드는 단일 위치뿐만 아니라 위치 목록(list)이나 배열(array)도 받을 수 있으므로, 여러 요소를 한 번에 삭제할 수 있습니다. 예를 들어 index.delete([1, 3])처럼 호출하면 인덱스 1과 3의 요소가 동시에 제거됩니다. 또한 이 메서드는 원본 인덱스를 수정하지 않고 항상 새로운 Index 객체를 반환하기 때문에, 기존 데이터를 안전하게 보존하면서 작업할 수 있다는 점도 기억해 두면 좋습니다.