Sütun Değerlerine Göre Sıralama
Bir DataFrame'i sort_values() ile bir veya daha fazla sütuna göre sıralayın, artan/azalan sırayı denetleyin ve NaN yerleşimini yönetin.
Sütun Değerlerine Göre Sıralama, CoddyKit'te ücretsiz bir Pandas & NumPy Academy dersidir. Bu, 4 dersinin 1. dersidir. Aşağıdan dersin tamamını ücretsiz okuyabilir, sonra tarayıcıda yerleşik kod editörü ve 7/24 yapay zeka koçu ile uygulamalı olarak pratik yapabilirsin. Bu, Pandas & NumPy Academy öğrenme yolunun bir parçasıdır ve ilerlemeniz web ve CoddyKit uygulaması arasında senkronize olur. Pandas & NumPy Academy kursu toplamda 4 dersten oluşur.
Bu dersin bazı bölümleri henüz çevrilmemiş olup İngilizce olarak gösterilmektedir.
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.
Sıkça Sorulan Sorular
“Sütun Değerlerine Göre Sıralama” dersi ücretsiz mi?
Evet — “Sütun Değerlerine Göre Sıralama” dersin tüm metni burada web'de ücretsiz olarak okunabilir. Etkileşimli olarak pratik yapmak (yerleşik kod editörü ve 7/24 yapay zeka koçu) ve Pandas & NumPy Academy kursunun geri kalanını açmak için CoddyKit PRO'ya yükselt. Pandas & NumPy Academy kursu toplamda 4 dersten oluşur.
“Sütun Değerlerine Göre Sıralama” dersinde ne öğreneceğim?
Bir DataFrame'i sort_values() ile bir veya daha fazla sütuna göre sıralayın, artan/azalan sırayı denetleyin ve NaN yerleşimini yönetin. Pandas & NumPy Academy ile uygulamalı kodu tarayıcıda doğrudan çalıştırarak pratik yaparsın ve 7/24 yapay zeka koçu dersi çalışırken sorularını yanıtlar.
Pandas & NumPy Academy öğrenmeye başlamak için deneyim gerekli mi?
Önceden deneyim gerekmez. CoddyKit'te Pandas & NumPy Academy, başlangıçtan ileri seviyeye kadar yapılandırıldığı için buradan başlayabilir veya başından başlayıp kendi hızında ilerleme yapabilirsin. Bu, 4 dersinin 1. dersidir.
“Sütun Değerlerine Göre Sıralama” dersi ne kadar sürer?
Çoğu CoddyKit dersi yaklaşık 5–10 dakika sürer. Her biri kısa ve etkileşimli olduğu için sabit ilerleme yaparsın ve web ile uygulama arasında tam olarak bıraktığın yerden devam edebilirsin.
Bu Pandas & NumPy Academy dersinde kod yazıp çalıştırabilir miyim?
Evet. Her Pandas & NumPy Academy dersi yerleşik bir kod editörü içerir, bu sayede tarayıcıda gerçek kod yazıp çalıştırabilir ve anlık yapay zeka geri bildirimi alırsın — yerel kurulum gerekli değildir.
Bu kursun tüm dersleri
- Sütun Değerlerine Göre Sıralama
- İndekse Göre Sıralama
- Değerleri Sıralama
- İndeksi Ayarlama ve Sıfırlama