Pandas에서 인덱스를 DataFrame으로 변환하는 방법
Pandas에서 인덱스(Index)의 원본 값과 이름(name)을 모두 유지한 채 DataFrame을 생성하려면 index.to_frame() 메서드를 사용하면 됩니다. 이 메서드는 기존 인덱스 객체를 그대로 하나의 열로 변환해 주기 때문에, 인덱스 데이터를 별도의 테이블 형태로 다루고 싶을 때 매우 유용합니다.
1단계: 필요한 라이브러리 임포트
가장 먼저 Pandas 라이브러리를 불러옵니다.
import pandas as pd
2단계: 이름이 있는 인덱스 생성
카테고리 이름을 담은 리스트와 함께 name 파라미터를 지정하여 Pandas 인덱스를 생성합니다.
index = pd.Index(['Electronics','Accessories','Decor', 'Books', 'Toys'],name ='Products')
생성된 인덱스를 화면에 출력해 확인해 보겠습니다.
print("Pandas Index...\n",index)3단계: 인덱스를 DataFrame으로 변환
to_frame() 메서드를 호출하면 인덱스 값들이 하나의 열로 구성된 DataFrame으로 변환됩니다.
print("\nIndex to DataFrame...\n",index.to_frame())전체 예제 코드
아래는 위 과정을 모두 포함한 전체 실행 코드입니다.
import pandas as pd
# 'Products'라는 이름을 가진 Pandas 인덱스 생성
index = pd.Index(['Electronics','Accessories','Decor', 'Books', 'Toys'],name ='Products')
# Pandas 인덱스 출력
print("Pandas Index...\n",index)
# 인덱스에 포함된 요소 개수 반환
print("\nNumber of elements in the index...\n",index.size)
# 데이터의 dtype(자료형) 반환
print("\nThe dtype object...\n",index.dtype)
# 인덱스를 DataFrame으로 변환
print("\nIndex to DataFrame...\n",index.to_frame())실행 결과
위 코드를 실행하면 다음과 같은 결과가 출력됩니다.
Pandas Index...
Index(['Electronics', 'Accessories', 'Decor', 'Books', 'Toys'], dtype='object', name='Products')
Number of elements in the index...
5
The dtype object...
object
Index to DataFrame...
Products
Products
Electronics Electronics
Accessories Accessories
Decor Decor
Books Books
Toys Toys결과 해석
출력 결과를 살펴보면 다음과 같은 특징을 확인할 수 있습니다.
- 인덱스 정보: 5개의 요소(Electronics, Accessories, Decor, Books, Toys)로 구성되어 있으며, 자료형(dtype)은 object입니다.
- 인덱스 이름: name='Products'로 지정했기 때문에 변환된 DataFrame에서도 이 이름이 그대로 활용됩니다.
- 변환 결과: to_frame()을 적용하면 원래의 인덱스가 행 인덱스로 유지되면서, 동일한 값들이 'Products'라는 이름의 열에 채워집니다. 즉, 원본 인덱스의 값과 이름이 모두 보존됩니다.
이처럼 index.to_frame() 메서드를 활용하면 별도의 복잡한 처리 없이도 인덱스 데이터를 손쉽게 DataFrame 형태로 가져올 수 있어, 데이터 분석 및 전처리 작업에서 시간을 크게 절약할 수 있습니다.