Pandas에서 값으로부터 유추된 데이터 타입을 문자열 형태로 확인하려면 index.inferred_type 속성을 사용하면 됩니다. 이 속성은 Index 객체에 저장된 값들을 분석하여 해당 데이터가 어떤 유형에 속하는지 판별해 줍니다.
필요한 라이브러리 불러오기
먼저 필요한 라이브러리를 임포트합니다.
import pandas as pd import numpy as np
인덱스 생성하기
이제 인덱스를 생성합니다. NaN 값을 넣기 위해 numpy 라이브러리를 활용했습니다.
index = pd.Index(['Car','Bike', np.nan,'Car',np.nan, 'Ship', None, None])
인덱스 출력하기
생성된 인덱스를 화면에 표시합니다.
print("Pandas Index...\n",index)유추된 타입 확인하기
값들로부터 유추된 타입을 문자열로 반환받습니다.
print("\nThe inferred type...\n",index.inferred_type)
전체 예제 코드
아래는 위 과정을 모두 포함한 전체 코드입니다.
import pandas as pd
import numpy as np
# 인덱스 생성
# NaN을 위해 numpy 라이브러리 사용
index = pd.Index(['Car','Bike', np.nan,'Car',np.nan, 'Ship', None, None])
# 인덱스 출력
print("Pandas Index...\n",index)
# Index의 데이터를 나타내는 배열 반환
print("\nArray...\n",index.values)
# 인덱스에 NaN이 있는지 확인
print("\nIs the Pandas index having NaNs?\n",index.hasnans)
# 데이터의 dtype 반환
print("\nThe dtype object...\n",index.dtype)
# 값으로부터 유추된 타입을 문자열로 반환
print("\nThe inferred type...\n",index.inferred_type)실행 결과
위 코드를 실행하면 다음과 같은 결과가 출력됩니다.
Pandas Index... Index(['Car', 'Bike', nan, 'Car', nan, 'Ship', None, None], dtype='object') Array... ['Car' 'Bike' nan 'Car' nan 'Ship' None None] Is the Pandas index having NaNs? True The dtype object... object The inferred type... Mixed
결과 해석
이 예제에서 인덱스는 문자열('Car', 'Bike', 'Ship')과 결측값(np.nan, None)이 섞여 있기 때문에, dtype은 object로 표시되고 inferred_type은 Mixed로 반환됩니다. 만약 인덱스가 순수한 정수나 문자열 등 단일 유형으로만 구성되어 있다면, inferred_type은 각각 'integer', 'string'처럼 해당 유형의 이름을 반환합니다. 이처럼 inferred_type 속성을 활용하면 Index 객체 내부 데이터의 성격을 빠르게 파악할 수 있습니다.