열 값으로 정렬하기
sort_values()로 하나 이상의 열을 기준으로 DataFrame을 정렬하고 오름차순·내림차순과 NaN 배치를 제어합니다.
열 값으로 정렬하기은(는) CoddyKit의 무료 Pandas & NumPy Academy 강의입니다. 이것은 4개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Pandas & NumPy Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Pandas & NumPy Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
Why Sorting Matters
Sorting a DataFrame is important for presentation (top-N reports, leaderboards), correctness (time series operations require chronological order), and performance (binary search on a sorted index is O(log n) vs O(n)). Pandas' sort_values() method is the primary tool for sorting by column content, and it returns a new DataFrame without modifying the original.
import pandas as pd
df = pd.DataFrame({
'name': ['Dave', 'Alice', 'Carol', 'Bob'],
'score': [75, 92, 88, 65]
})
# Sort by score descending (highest first)
ranked = df.sort_values('score', ascending=False)
print(ranked)
# name score
# 1 Alice 92
# 2 Carol 88
# 0 Dave 75
# 3 Bob 65sort_values() — Basic Usage
DataFrame.sort_values(by) sorts rows by the values in the specified column. The by argument accepts a single column name (string) or a list of column names for multi-key sorting. By default, sorting is ascending (smallest first). Pass ascending=False for descending order.
import pandas as pd
df = pd.DataFrame({
'product': ['B', 'A', 'C', 'A', 'B'],
'price': [20, 10, 30, 15, 25]
})
# Ascending by price (default)
print(df.sort_values('price'))
# product price
# 1 A 10
# 3 A 15
# 0 B 20
# 4 B 25
# 2 C 30Sorting by Multiple Columns
Passing a list of column names to sort_values(by=) sorts by the first column, then breaks ties using the second column, and so on. The ascending parameter can also be a list of booleans matching the order of the columns, allowing different sort directions for each key.
import pandas as pd
df = pd.DataFrame({
'dept': ['HR', 'Eng', 'HR', 'Eng', 'Sales'],
'salary': [50000, 90000, 60000, 80000, 70000],
'name': ['Alice', 'Bob', 'Carol', 'Dave', 'Eve']
})
# Sort by dept A-Z, then by salary descending within each dept
sorted_df = df.sort_values(
by=['dept', 'salary'],
ascending=[True, False]
)
print(sorted_df)
# dept salary name
# 1 Eng 90000 Bob
# 3 Eng 80000 Dave
# 2 HR 60000 Carol
# 0 HR 50000 Alice
# 4 Sales 70000 EveNaN Placement with na_position
By default, NaN values are sorted to the end of the result regardless of ascending or descending order. Use the na_position parameter to control this: 'last' (default) or 'first'. Deciding where NaN appears matters in ranked tables — missing values might represent 'unknown' and should be clearly separated from valid ranked entries.
import pandas as pd
import numpy as np
df = pd.DataFrame({
'name': ['Alice', 'Bob', 'Carol', 'Dave'],
'score': [92, np.nan, 88, np.nan]
})
# NaN last (default)
print(df.sort_values('score', ascending=False, na_position='last'))
# name score
# 0 Alice 92.0
# 2 Carol 88.0
# 1 Bob NaN
# 3 Dave NaN
# NaN first
print(df.sort_values('score', na_position='first').head(2))Stable Sort and kind= Parameter
Pandas uses a stable sort by default (mergesort, which is O(n log n)) — when two rows have equal values in the sort key, their original relative order is preserved. This stability matters when you sort by a primary key first, then by a secondary key: the primary sort order is maintained among ties of the secondary sort. You can change the algorithm with kind='quicksort' (faster but unstable) or kind='heapsort'.
import pandas as pd
df = pd.DataFrame({
'group': ['A', 'B', 'A', 'B'],
'value': [10, 10, 20, 20],
'original_row': [0, 1, 2, 3]
})
# Stable sort: equal values keep original relative order
result = df.sort_values('value', kind='mergesort')
print(result)
# group value original_row
# 0 A 10 0
# 1 B 10 1 <- row 0 before row 1 (stable)
# 2 A 20 2
# 3 B 20 3inplace=True vs Reassignment
Like most Pandas methods, sort_values() returns a new DataFrame by default. Passing inplace=True modifies the DataFrame in place and returns None. Using inplace is generally discouraged in modern Pandas because it makes code harder to pipeline and debug — it is easier to always reassign: df = df.sort_values('col').
import pandas as pd
df = pd.DataFrame({'x': [3, 1, 4, 1, 5]})
# Preferred: reassign
df = df.sort_values('x')
print(df['x'].tolist()) # [1, 1, 3, 4, 5]
# Alternative: inplace (not recommended for pipelines)
df2 = pd.DataFrame({'x': [3, 1, 4]})
df2.sort_values('x', inplace=True)
print(df2['x'].tolist()) # [1, 3, 4]Resetting the Index After Sorting
After sorting, the row index reflects the original positions. In a table sorted descending, row 0 might now have index 4. Call .reset_index(drop=True) to reassign sequential indices starting from 0. This is important before using .iloc[0] to get the first-ranked row reliably, or before exporting to a file where index gaps look confusing.
import pandas as pd
df = pd.DataFrame({'score': [70, 90, 80]})
sorted_df = df.sort_values('score', ascending=False)
print(sorted_df)
# score
# 1 90
# 2 80
# 0 70
# Clean sequential index
reset_df = sorted_df.reset_index(drop=True)
print(reset_df)
# score
# 0 90
# 1 80
# 2 70Getting Top-N with nlargest() and nsmallest()
For selecting the top-N or bottom-N rows by a column value, df.nlargest(n, 'col') and df.nsmallest(n, 'col') are more efficient than sorting the entire DataFrame and slicing. They use a partial sort (heap selection) that is O(n log k) rather than O(n log n), which matters for large DataFrames.
import pandas as pd
df = pd.DataFrame({
'product': ['A', 'B', 'C', 'D', 'E'],
'revenue': [5000, 12000, 8000, 3000, 15000]
})
# Top 3 by revenue
top3 = df.nlargest(3, 'revenue')
print(top3)
# product revenue
# 4 E 15000
# 1 B 12000
# 2 C 8000
# Bottom 2 by revenue
bottom2 = df.nsmallest(2, 'revenue')
print(bottom2)Sorting Categorical Columns by Category Order
When sorting a column that contains an ordered Categorical dtype, sort_values() respects the category order rather than alphabetical order. This is essential for correctly ordering priority levels, severity ratings, or size labels — 'Small' should come before 'Medium' before 'Large', not in alphabetical order where 'Large' comes first.
import pandas as pd
df = pd.DataFrame({
'size': pd.Categorical(
['Large', 'Small', 'Medium', 'Small', 'Large'],
categories=['Small', 'Medium', 'Large'],
ordered=True
),
'count': [10, 5, 8, 3, 7]
})
print(df.sort_values('size'))
# size count
# 1 Small 5
# 3 Small 3
# 2 Medium 8
# 0 Large 10
# 4 Large 7Chaining Sort with Other Operations
Because sort_values() returns a DataFrame, it integrates naturally into method chains. A typical pattern is: filter rows → aggregate → sort → display top-N. Chaining keeps the transformation pipeline linear and readable.
import pandas as pd
df = pd.DataFrame({
'dept': ['Eng', 'HR', 'Eng', 'Sales', 'HR', 'Eng'],
'salary': [90000, 50000, 120000, 70000, 55000, 80000]
})
result = (
df
.groupby('dept')['salary'].mean()
.reset_index()
.sort_values('salary', ascending=False)
.head(2)
)
print(result)
# dept salary
# 0 Eng 96666.67
# 2 Sales 70000.00Practical: Top-5 Products Report
Here is a practical end-to-end example of producing a top-5 products report by revenue: load data, compute total revenue per product, sort descending, take the top 5, reset the index to produce a clean rank number, and add a rank column for display.
import pandas as pd
orders = pd.DataFrame({
'product': ['A', 'B', 'A', 'C', 'B', 'D', 'E', 'A', 'C', 'E'],
'revenue': [100, 200, 150, 80, 300, 60, 400, 120, 90, 350]
})
top5 = (
orders
.groupby('product')['revenue'].sum()
.reset_index()
.sort_values('revenue', ascending=False)
.head(5)
.reset_index(drop=True)
)
top5.index = top5.index + 1 # rank from 1
top5.index.name = 'rank'
print(top5)Quick Check
Test your understanding of sorting DataFrames by column values.
Lesson Recap
In this lesson you learned: sort_values(by=) sorts by one or more columns, ascending= can be a list for different directions per key, na_position='last' controls NaN placement, and nlargest()/nsmallest() efficiently extract the top/bottom N rows without sorting the entire DataFrame. Always reset_index() after sorting for clean sequential output. Next up we sort by the DataFrame index.
자주 묻는 질문
“열 값으로 정렬하기” 강의는 무료인가요?
네 — “열 값으로 정렬하기” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Pandas & NumPy Academy 강의 전체를 잠금 해제할 수 있습니다. Pandas & NumPy Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
“열 값으로 정렬하기”에서 뭘 배우나요?
sort_values()로 하나 이상의 열을 기준으로 DataFrame을 정렬하고 오름차순·내림차순과 NaN 배치를 제어합니다. 브라우저에서 직접 실행하는 실습 코드로 Pandas & NumPy Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Pandas & NumPy Academy을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Pandas & NumPy Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 1번째 강의입니다.
“열 값으로 정렬하기” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Pandas & NumPy Academy 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Pandas & NumPy Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- 열 값으로 정렬하기
- 인덱스로 정렬하기
- 값 순위 매기기
- 인덱스 설정과 재설정