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

Python Pandas – 인덱스의 기본 데이터 dtype 객체 반환 방법

Pandas에서 인덱스(Index)가 담고 있는 기본 데이터의 dtype 객체를 확인하려면 index.dtype 속성을 사용하면 됩니다. 이 속성은 해당 인덱스에 저장된 데이터의 자료형(데이터 타입)을 그대로 반환해 주기 때문에, 데이터 전처리나 디버깅 과정에서 매우 유용하게 활용됩니다.

필요한 라이브러리 불러오기

먼저 Pandas 라이브러리를 임포트합니다.

import pandas as pd

인덱스 생성하기

문자열 요소들로 구성된 인덱스를 생성해 보겠습니다.

index = pd.Index(['Car','Bike', 'Shop','Car','Airplace', 'Truck'])

인덱스 출력하기

생성된 인덱스를 화면에 표시합니다.

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

dtype 객체 반환하기

index.dtype 속성을 호출하면 해당 데이터의 dtype 객체가 출력됩니다.

print("\nThe dtype object...\n",index.dtype)

전체 예제 코드

아래는 위 내용을 모두 포함한 완전한 예제입니다.

import pandas as pd

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

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

# 인덱스 데이터를 배열 형태로 반환
print("\nArray...\n",index.values)

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

# 기본 데이터의 shape(형상) 튜플 반환
print("\nA tuple of the shape of underlying data...\n",index.shape)

실행 결과

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

Pandas Index...
Index(['Car', 'Bike', 'Shop', 'Car', 'Airplace', 'Truck'], dtype='object')

Array...
['Car' 'Bike' 'Shop' 'Car' 'Airplace' 'Truck']

The dtype object...
object

A tuple of the shape of underlying data...
(6,)

출력 결과를 보면 문자열로 구성된 인덱스의 dtype이 'object'로 지정되어 있으며, 요소는 총 6개이므로 shape 역시 (6,)으로 반환되는 것을 확인할 수 있습니다.