0Pricing
Pandas & NumPy Academy · درس

نمط التقسيم والتطبيق والدمج

افهم التدفق المفاهيمي لـ groupby: تقسيم DataFrame إلى مجموعات، وتطبيق دالة، ثم دمج النتائج.

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

بعض أجزاء هذا الدرس لم تُترجم بعد وتظهر باللغة الإنجليزية.

What Is GroupBy?

The GroupBy operation is one of the most powerful patterns in data analysis. It lets you split a DataFrame into groups, apply a function to each group independently, and then combine the results into a new structure. This workflow is known as the split-apply-combine pattern, a term coined by statistician Hadley Wickham.

The Split Step

In the split step, Pandas divides the DataFrame into sub-DataFrames based on the unique values in one or more columns. For example, if your data has a region column with values like 'North', 'South', and 'West', the split step creates three separate groups. No data is moved or copied yet — Pandas just records which rows belong to which group.

import pandas as pd

df = pd.DataFrame({
    'region': ['North', 'South', 'North', 'West', 'South'],
    'sales': [200, 150, 300, 180, 220]
})

# split: create a GroupBy object
grouped = df.groupby('region')
print(type(grouped))  # DataFrameGroupBy

The Apply Step

In the apply step, a function is applied to each group independently. The function can be a built-in aggregation like sum() or mean(), or a custom function you define. Each group's rows are passed to the function, and it returns a scalar, a Series, or a DataFrame as the result.

# apply: compute the sum of 'sales' within each region group
total_sales = grouped['sales'].sum()
print(total_sales)
# region
# North    500
# South    370
# West     180
# Name: sales, dtype: int64

The Combine Step

In the combine step, Pandas automatically assembles the per-group results back into a single object — typically a Series or DataFrame. The group keys become the index of the result. This step happens invisibly when you call an aggregation method on a GroupBy object, giving you a clean summary table with one row per group.

# combine happens automatically — result is a Series indexed by 'region'
print(total_sales.index)   # Index(['North', 'South', 'West'])
print(total_sales.values)  # [500, 370, 180]

Creating a GroupBy Object

You create a GroupBy object by calling df.groupby(column). Nothing is computed at this stage — it is a lazy object. You can iterate over it to see the groups, or chain an aggregation method to trigger computation. Passing as_index=False keeps the grouping column as a regular column instead of the index in the result.

grouped = df.groupby('region', as_index=False)
result = grouped['sales'].sum()
print(result)
#   region  sales
# 0  North    500
# 1  South    370
# 2   West    180

Iterating Over Groups

You can iterate over a GroupBy object to inspect each group individually. Each iteration yields a tuple of (group_key, sub_dataframe). This is useful for debugging or when you want to process each group with arbitrary Python code. However, for performance in production, prefer vectorised aggregation methods over explicit iteration.

for name, group in df.groupby('region'):
    print(f'--- {name} ---')
    print(group)
# --- North ---
#   region  sales
# 0  North    200
# 2  North    300
# --- South ---
#   region  sales
# 1  South    150
# 4  South    220

Common Aggregation Functions

Pandas GroupBy supports many built-in aggregation functions: sum(), mean(), count(), min(), max(), std(), median(), and more. These are highly optimised and run on all groups in a single pass. Always prefer them over writing a custom Python function when the built-in exists.

print(df.groupby('region')['sales'].mean())
# region
# North    250.0
# South    185.0
# West     180.0

print(df.groupby('region')['sales'].count())
# region
# North    2
# South    2
# West     1

Grouping Multiple Columns at Once

You can apply aggregations to multiple columns simultaneously by selecting them before calling the aggregation method, or by omitting column selection to aggregate all numeric columns. The result is a DataFrame instead of a Series, with one column per aggregated variable.

df2 = pd.DataFrame({
    'region': ['North', 'South', 'North', 'South'],
    'units': [10, 8, 12, 9],
    'revenue': [200, 160, 240, 180]
})

print(df2.groupby('region').sum())
#         units  revenue
# region
# North      22      440
# South      17      340

The GroupBy Mental Model

Think of GroupBy like SQL's GROUP BY clause. The Pandas code df.groupby('region')['sales'].sum() is equivalent to SELECT region, SUM(sales) FROM df GROUP BY region in SQL. Understanding this parallel helps you translate between the two tools and choose the right abstraction for your pipeline.

# Pandas GroupBy is equivalent to SQL GROUP BY
# SQL:    SELECT region, SUM(sales) FROM df GROUP BY region
# Pandas: df.groupby('region')['sales'].sum()

result = df.groupby('region')['sales'].sum().reset_index()
result.columns = ['region', 'total_sales']
print(result)

Why Not Use a Loop Instead?

You might wonder why not just loop over unique values and compute statistics manually. The answer is performance and readability. A Python loop over groups is much slower than a single vectorised groupby call, especially for large datasets. GroupBy operations run in compiled C code internally, making them 10-100x faster than equivalent Python loops.

# Slow approach with a loop
results = {}
for region in df['region'].unique():
    subset = df[df['region'] == region]
    results[region] = subset['sales'].sum()

# Fast approach with GroupBy
results_fast = df.groupby('region')['sales'].sum().to_dict()
# Both give the same answer, but GroupBy is orders of magnitude faster

GroupBy With Multiple Group Keys

When you need finer granularity, group by multiple columns by passing a list to groupby(). The result has a MultiIndex where each level corresponds to one grouping column. For example, grouping by both 'region' and 'quarter' gives totals for every region-quarter combination.

df3 = pd.DataFrame({
    'region': ['North', 'North', 'South', 'South'],
    'quarter': ['Q1', 'Q2', 'Q1', 'Q2'],
    'sales': [200, 300, 150, 220]
})

print(df3.groupby(['region', 'quarter'])['sales'].sum())
# region  quarter
# North   Q1         200
#         Q2         300
# South   Q1         150
#         Q2         220

Quick Check

Test your understanding of the split-apply-combine pattern from this lesson.

Lesson Recap

In this lesson you learned: the split-apply-combine pattern that underlies all GroupBy operations, how to create a GroupBy object with df.groupby(), and how to apply built-in aggregations like sum() and mean() to get one result per group. Next up we explore grouping by single and multiple keys with more aggregation methods.

الأسئلة الشائعة

هل درس «نمط التقسيم والتطبيق والدمج» مجاني؟

نعم — نص درس «نمط التقسيم والتطبيق والدمج» كامل متاح مجاناً هنا على الويب. لتمرينه بشكل تفاعلي (محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7) وفتح باقي دورة Pandas & NumPy Academy، انتقل إلى CoddyKit PRO. تتضمن دورة Pandas & NumPy Academy 4 دروس في المجموع.

ماذا ستتعلم في «نمط التقسيم والتطبيق والدمج»؟

افهم التدفق المفاهيمي لـ groupby: تقسيم DataFrame إلى مجموعات، وتطبيق دالة، ثم دمج النتائج. تتمرن على 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. GroupBy بمفتاح واحد أو عدة مفاتيح
  3. أسلوب agg()
  4. تحويل GroupBy وتصفيته
← العودة إلى Pandas & NumPy Academy