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

Python Pandas - index.repeat()로 인덱스 요소 반복하는 방법

Pandas에서 인덱스(Index)의 각 요소를 반복하려면 index.repeat() 메서드를 사용하면 됩니다. 이 메서드는 반복 횟수를 인자로 전달받아, 지정한 횟수만큼 각 요소를 순서대로 반복한 새로운 인덱스를 반환합니다.

필수 라이브러리 임포트

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

import pandas as pd

Pandas 인덱스 생성

교통수단 이름을 담은 Pandas 인덱스를 생성해 보겠습니다. name 매개변수를 사용해 인덱스에 'Transport'라는 이름을 부여했습니다.

index = pd.Index(['Car','Bike','Airplane', 'Ship','Truck','Suburban'], name ='Transport')

인덱스 출력 및 repeat() 적용

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

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

이제 repeat(2)를 호출하여 각 인덱스 요소를 두 번씩 반복합니다.

print("\nResult after repeating each index element twice...\n",index.repeat(2))

전체 예제 코드

지금까지 설명한 내용을 하나로 정리한 전체 코드입니다. 인덱스의 크기(size)와 데이터 타입(dtype)도 함께 확인할 수 있도록 추가했습니다.

import pandas as pd

# Pandas 인덱스 생성
index = pd.Index(['Car','Bike','Airplane', 'Ship','Truck','Suburban'], name ='Transport')

# Pandas 인덱스 출력
print("Pandas Index...\n",index)

# 인덱스의 요소 개수 반환
print("\nNumber of elements in the index...\n",index.size)

# 데이터의 dtype 객체 반환
print("\nThe dtype object...\n",index.dtype)

# 인덱스의 각 요소를 반복
print("\nResult after repeating each index element twice...\n",index.repeat(2))

실행 결과

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

Pandas Index...
Index(['Car', 'Bike', 'Airplane', 'Ship', 'Truck', 'Suburban'], dtype='object', name='Transport')

Number of elements in the index...
6

The dtype object...
object

Result after repeating each index element twice...
Index(['Car', 'Car', 'Bike', 'Bike', 'Airplane', 'Airplane', 'Ship', 'Ship',
'Truck', 'Truck', 'Suburban', 'Suburban'],
dtype='object', name='Transport')

정리

index.repeat(n) 메서드는 원본 인덱스의 각 요소를 n번씩 연속으로 반복한 새로운 인덱스를 생성합니다. 위 예제에서처럼 repeat(2)를 호출하면 총 6개의 요소가 12개로 확장되며, 원래 인덱스의 이름(name)과 dtype 속성도 그대로 유지됩니다. 이 기능은 DataFrame을 재구성하거나 라벨을 확장할 때 특히 유용하게 활용됩니다.