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

Python Pandas – 입력 레이블에 대한 슬라이스 인덱서 계산 방법

입력 레이블에 대한 슬라이스 인덱서를 계산하려면 index.slice_indexer() 메서드를 사용합니다. 이 메서드는 시작 레이블(start)과 끝 레이블(end)을 지정하면, 해당 레이블 위치에 대응하는 슬라이스(slice) 객체를 반환합니다.


먼저 필요한 라이브러리를 임포트합니다 −

import pandas as pd

Pandas 인덱스 객체를 생성합니다 −

index = pd.Index(list('pqrstuvwxyz'))

생성된 Pandas 인덱스를 화면에 출력합니다 −

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

슬라이스 인덱서를 구합니다. start는 슬라이스를 시작할 레이블이고, end는 슬라이스를 끝낼 레이블입니다 −

print("\nThe slice indexer with start and stop...\n",index.slice_indexer(start='s', end='w'))

예제

전체 코드는 다음과 같습니다 −

import pandas as pd

# create Pandas index object
index = pd.Index(list('pqrstuvwxyz'))

# Display the Pandas index
print("Pandas Index...\n",index)

# Return the number of elements in the Index
print("\nNumber of elements in the index...\n",index.size)

# Get the slice indexer
# The "start" is the label to begin with
# The "end" is the label to end with
print("\nThe slice indexer with start and stop...\n",index.slice_indexer(start='s', end='w'))

출력

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

Pandas Index...
Index(['p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'], dtype='object')

Number of elements in the index...
11

The slice indexer with start and stop...
slice(3, 8, None)

실행 결과를 살펴보면, 인덱스에는 총 11개의 요소가 있으며 slice_indexer(start='s', end='w') 호출 결과로 slice(3, 8, None)이 반환됩니다. 's'는 인덱스에서 3번째 위치(0부터 시작)에, 'w'는 7번째 위치에 있으므로, 끝 레이블까지 포함하는 슬라이스의 상한값으로 8이 계산된 것입니다. 이처럼 slice_indexer()는 레이블 기반으로 동작하기 때문에 위치 값을 일일이 세지 않고도 원하는 레이블 범위의 데이터를 간편하게 추출할 수 있다는 장점이 있습니다.