0Pricing
Pandas & NumPy Academy · درس

الفرز حسب قيم الأعمدة

افرز DataFrame حسب عمود واحد أو عدة أعمدة باستخدام sort_values()، وتحكم في الترتيب التصاعدي أو التنازلي، وتعامل مع موضع NaN.

الفرز حسب قيم الأعمدة درس مجاني في Pandas & NumPy Academy على CoddyKit. هذا هو الدرس 1 من أصل 4. يمكنك قراءة الدرس كاملاً أدناه مجاناً — ثم تمرن عليه مباشرة في المتصفح باستخدام محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7. هذا الدرس جزء من مسار التعلم في 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     65

sort_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     30

Sorting 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    Eve

NaN 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             3

inplace=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     70

Getting 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      7

Chaining 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.00

Practical: 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) وفتح باقي دورة Pandas & NumPy Academy، انتقل إلى CoddyKit PRO. تتضمن دورة Pandas & NumPy Academy 4 دروس في المجموع.

ماذا ستتعلم في «الفرز حسب قيم الأعمدة»؟

افرز DataFrame حسب عمود واحد أو عدة أعمدة باستخدام sort_values()، وتحكم في الترتيب التصاعدي أو التنازلي، وتعامل مع موضع NaN. تتمرن على Pandas & NumPy Academy مع أكواد عملية تشغلها مباشرة في المتصفح، ومدرس ذكاء اصطناعي متاح 24/7 يجيب على أسئلتك أثناء عملك.

هل أحتاج إلى خبرة سابقة لأبدأ Pandas & NumPy Academy؟

لا تُشترط خبرة سابقة. Pandas & NumPy Academy على CoddyKit منظم للمبتدئين حتى المتقدمين، لذا يمكنك البدء من هنا أو من البداية والتقدم بسرعتك الخاصة. هذا هو الدرس 1 من أصل 4.

كم من الوقت يستغرق درس «الفرز حسب قيم الأعمدة»؟

معظم دروس CoddyKit تستغرق حوالي 5–10 دقائق. كل منها موجز وتفاعلي، لذا تحرز تقدماً مستمراً وتستأنف من حيث توقفت عبر الويب والتطبيق.

هل يمكنني كتابة وتشغيل أكواد في درس Pandas & NumPy Academy هذا؟

نعم. كل درس في Pandas & NumPy Academy يتضمن محرر أكواد مدمج، لذا تكتب وتشغل أكواداً حقيقية مباشرة في متصفحك وتحصل على تعليقات فورية من الذكاء الاصطناعي — بدون إعداد محلي.

جميع الدروس في هذه الدورة

  1. الفرز حسب قيم الأعمدة
  2. الفرز حسب الفهرس
  3. ترتيب القيم
  4. تعيين الفهرس وإعادة تعيينه
← العودة إلى Pandas & NumPy Academy