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

Python Pandas – 이미 생성된 Index 객체의 인덱스 이름 설정 방법

Pandas에서 이미 생성된 Index 객체에 이름을 지정하려면 set_names() 메서드를 사용합니다. 이 메서드는 기존 인덱스 객체를 직접 수정하지 않고, 이름이 부여된 새로운 Index 객체를 반환한다는 점이 특징입니다.

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

import pandas as pd

Pandas 인덱스를 생성합니다 −

index = pd.Index(["Electronics", "Mobile Phones", "Accessories", "Home Decor", "Books"])

생성한 Pandas 인덱스를 화면에 출력합니다 −

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

인덱스의 이름을 설정합니다 −

print("\nSet the index name...\n",index.set_names('Products'))

예제

다음은 전체 코드입니다 −

import pandas as pd

# Pandas 인덱스 생성
index = pd.Index(["Electronics", "Mobile Phones", "Accessories", "Home Decor", "Books"])

# 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("\nSet the index name...\n",index.set_names('Products'))

실행 결과

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

Pandas Index...
Index(['Electronics', 'Mobile Phones', 'Accessories', 'Home Decor', 'Books'], dtype='object')

Number of elements in the index...
5

The dtype object...
object

Set the index name...
Index(['Electronics', 'Mobile Phones', 'Accessories', 'Home Decor', 'Books'], dtype='object', name='Products')

참고 사항

출력 결과를 보면 마지막 인덱스에 name='Products'가 추가된 것을 확인할 수 있습니다. set_names() 메서드는 기본적으로 새로운 Index 객체를 반환하며, 원본 객체를 그대로 유지합니다. 만약 원본 인덱스 자체를 변경하고 싶다면 inplace=True 옵션을 사용하면 됩니다. 또한 다중 인덱스(MultiIndex)를 다룰 때는 각 레벨의 이름을 리스트 형태로 한 번에 지정할 수 있어, 복잡한 계층형 데이터 구조를 더 명확하게 관리할 수 있습니다.