작성: Corn/sec, ChatGPT, 편집: Corn/sec

파이썬의 pandas 라이브러리는 데이터프레임(DataFrame)을 다룰 때 강력한 정렬 기능을 제공합니다. 정렬은 데이터 분석에서 매우 중요한 과정으로, 데이터를 원하는 기준에 맞춰 정리하여 분석을 더 쉽게 수행할 수 있도록 합니다.
pandas에서는 크게 두 가지 방법으로 정렬할 수 있습니다.
import pandas as pd
# 예제 데이터 생성
data = {
'Name': ['Alice', 'Bob', 'Charlie', 'David'],
'Score': [85, 92, 88, 79],
'Age': [25, 23, 24, 22]
}
df = pd.DataFrame(data)
# Score 기준 오름차순 정렬
sorted_df = df.sort_values(by='Score')
print(sorted_df)
출력 결과:
Name Score Age
3 David 79 22
0 Alice 85 25
2 Charlie 88 24
1 Bob 92 23
sorted_df_desc = df.sort_values(by='Score', ascending=False)
print(sorted_df_desc)
출력 결과:
Name Score Age
1 Bob 92 23
2 Charlie 88 24
0 Alice 85 25
3 David 79 22
여러 개의 컬럼을 기준으로 정렬할 수도 있습니다. 예를 들어, Score 기준으로 정렬한 후, 동점자가 있을 경우 Age를 기준으로 정렬할 수 있습니다.
sorted_df_multi = df.sort_values(by=['Score', 'Age'], ascending=[False, True])
print(sorted_df_multi)
# 인덱스 기준 정렬
df_sorted_index = df.sort_index()
print(df_sorted_index)
sort_index()는 인덱스를 기준으로 정렬합니다. 특히, 행의 순서를 유지하면서 인덱스를 다시 정렬해야 하는 경우 유용합니다.
df_sorted_index_desc = df.sort_index(ascending=False)
print(df_sorted_index_desc)
| 정렬 함수 | 기준 | 원본 변경 여부 | 반환값 |
| sort_values(by='컬럼') | 특정 컬럼 값 | ❌ (기본적으로 변경 없음) | 정렬된 데이터프레임 |
| sort_index() | 행 인덱스 | ❌ (기본적으로 변경 없음) | 정렬된 데이터프레임 |
df.sort_values(by='Score', ascending=False, inplace=True)
print(df) # 원본이 변경됨
| [Python] 제너레이터 표현식(generator expressions) 연습 예제 (0) | 2025.02.05 |
|---|---|
| [Python] 비트 연산자(Bitwise Operator) 개념 정리 (0) | 2025.02.04 |