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

Python Pandas – 인덱스 값을 내림차순으로 정렬하는 방법

Pandas에서 인덱스(Index)의 정렬된 복사본을 반환하려면 index.sort_values() 메서드를 사용하면 됩니다. 이때 ascending 매개변수를 False로 설정하면 내림차순으로 정렬할 수 있습니다.

sort_values() 메서드는 원본 인덱스를 변경하지 않고 정렬된 새로운 인덱스 객체를 반환한다는 점이 특징입니다. 기본값은 ascending=True(오름차순)이며, 내림차순 정렬을 원할 경우 명시적으로 False를 지정해야 합니다.

1. 라이브러리 임포트

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

import pandas as pd

2. Pandas 인덱스 생성

정렬에 사용할 Pandas 인덱스를 생성합니다.

index = pd.Index([50, 10, 70, 95, 110, 90, 30])

3. 인덱스 출력

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

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

4. 내림차순으로 인덱스 값 정렬

인덱스 값을 내림차순으로 정렬하려면 "ascending" 매개변수를 "False"로 설정합니다.

print("\nSort the index values in descending order...\n", index.sort_values(ascending=False))

전체 예제 코드

다음은 위 과정을 모두 포함한 전체 코드입니다.

import pandas as pd

# Pandas 인덱스 생성
index = pd.Index([50, 10, 70, 95, 110, 90, 30])

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

# 인덱스에 포함된 요소 개수 반환
print("\nNumber of elements in the index...\n", index.size)

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

# 인덱스 값 정렬
# 내림차순으로 정렬하려면 "ascending" 매개변수를 "False"로 설정
print("\nSort the index values in descending order...\n", index.sort_values(ascending=False))

실행 결과

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

Pandas Index...
Int64Index([50, 10, 70, 95, 110, 90, 30], dtype='int64')

Number of elements in the index...
7

The dtype object...
int64

Sort the index values in descending order...
Int64Index([110, 95, 90, 70, 50, 30, 10], dtype='int64')

핵심 정리

  • index.sort_values(): 인덱스 값을 정렬한 새로운 복사본을 반환합니다.
  • ascending=False: 내림차순 정렬을 지정합니다. 생략하거나 True로 설정하면 오름차순으로 정렬됩니다.
  • 원본 인덱스는 그대로 유지되며, 정렬된 결과는 새로운 인덱스 객체로 반환됩니다.