تحليل GroupBy حسب المنطقة والفئة
جمّع إجمالي الإيرادات وعدد الطلبات حسب المنطقة وفئة المنتج، وحدد أفضل 5 من رموز SKU حسب هامش الربح.
تحليل GroupBy حسب المنطقة والفئة درس مجاني في Pandas & NumPy Academy على CoddyKit. هذا هو الدرس 3 من أصل 4. يمكنك قراءة الدرس كاملاً أدناه مجاناً — ثم تمرن عليه مباشرة في المتصفح باستخدام محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7. هذا الدرس جزء من مسار التعلم في Pandas & NumPy Academy، وتقدمك يتزامن عبر الويب وتطبيق CoddyKit. تتضمن دورة Pandas & NumPy Academy 4 دروس في المجموع.
بعض أجزاء هذا الدرس لم تُترجم بعد وتظهر باللغة الإنجليزية.
Setting Up GroupBy Analysis
After computing a revenue column, the natural next step is to aggregate it by business dimensions like region and category. The Pandas groupby() call splits the DataFrame into groups, you apply an aggregation function, and Pandas combines the results into a summary table. This split-apply-combine pattern replaces nested SQL GROUP BY queries.
import pandas as pd
df = pd.read_parquet('sales_features.parquet')
# Total revenue by region
region_rev = df.groupby('region')['revenue'].sum().sort_values(ascending=False)
print(region_rev)Grouping by Category
Aggregate revenue by product category to identify which categories drive the most sales. Use .agg() to compute multiple statistics at once — total revenue, order count, and average order value — in a single pass over the data rather than three separate groupby calls.
cat_summary = df.groupby('category')['revenue'].agg(
total_revenue='sum',
order_count='count',
avg_order_value='mean'
).sort_values('total_revenue', ascending=False)
print(cat_summary)Grouping by Two Keys: Region and Category
Pass a list of columns to groupby() to create a two-level summary. The result has a MultiIndex — outer level is region, inner is category. Use .reset_index() to flatten it into a plain DataFrame suitable for further filtering or export to a report.
region_cat = df.groupby(['region', 'category'])['revenue'].sum().reset_index()
region_cat.columns = ['region', 'category', 'total_revenue']
region_cat = region_cat.sort_values(['region', 'total_revenue'], ascending=[True, False])
print(region_cat.head(10))Computing Revenue Share Percentage
Absolute revenue numbers are useful, but revenue share shows each category's contribution to the total. Divide the per-category total by the grand total and multiply by 100. The transform('sum') trick broadcasts the grand total back to each row so you can compute the percentage in a single vectorised step.
df['total_revenue_all'] = df['revenue'].sum()
cat_share = df.groupby('category')['revenue'].sum() / df['revenue'].sum() * 100
cat_share = cat_share.sort_values(ascending=False).round(2)
print(cat_share.rename('revenue_share_%'))Finding Top-5 SKUs by Revenue
Identify the top-5 products by total revenue using groupby('product')['revenue'].sum().nlargest(5). The nlargest() method is more concise than sorting and slicing. Knowing the top SKUs guides inventory decisions and helps focus promotional efforts where revenue impact is highest.
top5_sku = df.groupby('product')['revenue'].sum().nlargest(5)
print('Top 5 Products by Revenue:')
print(top5_sku)Order Count vs. Revenue by Region
A region might have high order count but low average order value, or vice versa. Compute both metrics side by side to distinguish volume-driven regions from value-driven ones. Use agg() with a dict to assign descriptive column names and keep the output readable.
region_profile = df.groupby('region').agg(
order_count=('order_id', 'count'),
total_revenue=('revenue', 'sum'),
avg_order=('revenue', 'mean')
).round(2)
print(region_profile.sort_values('total_revenue', ascending=False))Percentage of Revenue per Region
Compute the share of total revenue contributed by each region. Use groupby().sum() and then divide by the scalar total. This makes it easy to answer executive-level questions like "What percentage of our revenue comes from the North region?" in a single DataFrame expression.
region_rev = df.groupby('region')['revenue'].sum()
region_share = (region_rev / region_rev.sum() * 100).round(2)
region_share.name = 'revenue_share_%'
print(region_share.sort_values(ascending=False))Filtering Groups by Revenue Threshold
Use groupby().filter() to keep only rows belonging to categories whose total revenue exceeds a threshold. This is useful when you want to remove niche categories from a visualisation or model to focus on material segments. The filter receives a group DataFrame and returns a boolean.
THRESHOLD = 10000
df_major = df.groupby('category').filter(
lambda g: g['revenue'].sum() >= THRESHOLD
)
print('Major categories:', df_major['category'].nunique())Month-over-Month Revenue by Category
Combine two groupby keys — month and category — to track how each category's revenue evolves over time. Pivot the result with unstack('category') to get a matrix where rows are months and columns are categories, making it easy to spot seasonal patterns per category.
monthly_cat = df.groupby(['month', 'category'])['revenue'].sum().unstack('category').fillna(0)
print(monthly_cat.round(0))Top SKU per Region
Identify the single best-selling product in each region by chaining groupby with idxmax(). Group by region and product to get total revenue per combination, then for each region pick the product index with the maximum revenue. This pattern reveals whether different regions prefer different products.
rev_by_region_sku = df.groupby(['region', 'product'])['revenue'].sum()
top_sku_per_region = rev_by_region_sku.groupby('region').idxmax()
print(top_sku_per_region)Exporting the Summary Table
After computing the region-category summary, export it to Excel with to_excel() so stakeholders who prefer spreadsheets can consume it. Use ExcelWriter to write multiple summary DataFrames to separate sheets in a single workbook. Add a timestamp to the file name so each run produces a versioned output.
from datetime import date
filename = f'sales_summary_{date.today()}.xlsx'
with pd.ExcelWriter(filename, engine='openpyxl') as writer:
region_profile.to_excel(writer, sheet_name='By Region')
cat_summary.to_excel(writer, sheet_name='By Category')
print('Saved:', filename)Quick Check
Test your understanding of Data Analysis concepts from this lesson.
Lesson Recap
In this lesson you learned: grouping by one and two keys to compute revenue summaries, computing revenue share percentages and top-N SKUs, and exporting multi-sheet Excel summary reports. Next up we explore monthly trend visualisation with line charts and moving averages.
الأسئلة الشائعة
هل درس «تحليل GroupBy حسب المنطقة والفئة» مجاني؟
نعم — نص درس «تحليل GroupBy حسب المنطقة والفئة» كامل متاح مجاناً هنا على الويب. لتمرينه بشكل تفاعلي (محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7) وفتح باقي دورة Pandas & NumPy Academy، انتقل إلى CoddyKit PRO. تتضمن دورة Pandas & NumPy Academy 4 دروس في المجموع.
ماذا ستتعلم في «تحليل GroupBy حسب المنطقة والفئة»؟
جمّع إجمالي الإيرادات وعدد الطلبات حسب المنطقة وفئة المنتج، وحدد أفضل 5 من رموز SKU حسب هامش الربح. تتمرن على Pandas & NumPy Academy مع أكواد عملية تشغلها مباشرة في المتصفح، ومدرس ذكاء اصطناعي متاح 24/7 يجيب على أسئلتك أثناء عملك.
هل أحتاج إلى خبرة سابقة لأبدأ Pandas & NumPy Academy؟
لا تُشترط خبرة سابقة. Pandas & NumPy Academy على CoddyKit منظم للمبتدئين حتى المتقدمين، لذا يمكنك البدء من هنا أو من البداية والتقدم بسرعتك الخاصة. هذا هو الدرس 3 من أصل 4.
كم من الوقت يستغرق درس «تحليل GroupBy حسب المنطقة والفئة»؟
معظم دروس CoddyKit تستغرق حوالي 5–10 دقائق. كل منها موجز وتفاعلي، لذا تحرز تقدماً مستمراً وتستأنف من حيث توقفت عبر الويب والتطبيق.
هل يمكنني كتابة وتشغيل أكواد في درس Pandas & NumPy Academy هذا؟
نعم. كل درس في Pandas & NumPy Academy يتضمن محرر أكواد مدمج، لذا تكتب وتشغل أكواداً حقيقية مباشرة في متصفحك وتحصل على تعليقات فورية من الذكاء الاصطناعي — بدون إعداد محلي.
جميع الدروس في هذه الدورة
- تحميل مجموعة بيانات المبيعات وتدقيقها
- حساب الإيرادات وهندسة الميزات
- تحليل GroupBy حسب المنطقة والفئة
- تصور الاتجاه الشهري