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

Python Pandas – 인덱스의 전치(Transpose) 반환하기

Pandas에서 인덱스(Index)의 전치(Transpose)를 반환하려면 index.T 속성을 사용하면 됩니다. 인덱스는 1차원 구조이기 때문에 정의상 전치 결과는 자기 자신(self)과 동일하게 반환됩니다.

필수 라이브러리 가져오기

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

import pandas as pd

인덱스 생성하기

다음과 같이 문자열 요소로 구성된 Pandas 인덱스를 생성합니다.

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

인덱스 출력하기

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

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

인덱스의 전치 출력하기

인덱스의 전치를 출력합니다.

print("\nTranspose of the Pandas Index which is by definition self...\n",index.T)

전체 예제 코드

아래는 위 과정을 모두 포함한 완전한 예제 코드입니다.

import pandas as pd

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

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

# 인덱스 데이터를 나타내는 배열 반환
print("\nArray...\n",index.values)

# 인덱스의 전치 출력
print("\nTranspose of the Pandas Index which is by definition self...\n",index.T)

실행 결과

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

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

Array...
['Car' 'Bike' 'Truck' 'Ship' 'Airplane']

Transpose of the Pandas Index which is by definition self...
Index(['Car', 'Bike', 'Truck', 'Ship', 'Airplane'], dtype='object')

정리

Pandas의 Index.T 속성은 인덱스의 전치를 반환하지만, 인덱스는 본질적으로 1차원 자료구조이므로 전치 결과가 항상 원본 인덱스와 동일합니다. 이 속성은 DataFrame처럼 2차원 이상의 객체와 함께 사용할 때 실질적인 의미를 가지며, 인덱스 객체에서는 일관성을 위해 제공되는 기능이라고 이해하면 좋습니다.