0Pricing
Pandas & NumPy Academy · درس

‏pivot_table: الجدولة التقاطعية

أنشئ جداول محورية على نمط Excel باستخدام pd.pivot_table، مع تحديد index وcolumns وvalues وaggfunc.

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

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

What Is a Pivot Table?

A pivot table is a cross-tabulation that summarises data by two categorical dimensions — one forms the rows, another forms the columns — with an aggregated value in each cell. If you have ever built a pivot table in Excel, you will recognise the concept immediately. Pandas provides pd.pivot_table() (and the DataFrame method version) to create these summaries entirely in Python.

Basic pivot_table Call

The four key parameters of pd.pivot_table() are: values (the column to aggregate), index (which column becomes the rows), columns (which column becomes the columns), and aggfunc (the aggregation function, defaulting to 'mean'). The result is a DataFrame where each cell contains the aggregated value for that row-column combination.

import pandas as pd

df = pd.DataFrame({
    'region':  ['East', 'West', 'East', 'West', 'East', 'West'],
    'product': ['A',    'A',    'B',    'B',    'A',    'B'],
    'revenue': [200,    340,    150,    290,    310,    410]
})

table = pd.pivot_table(df,
                       values='revenue',
                       index='region',
                       columns='product',
                       aggfunc='sum')
print(table)
# product    A    B
# region
# East     510  150
# West     340  700

Choosing the aggfunc

The aggfunc parameter accepts any string name of a NumPy/Pandas aggregation function, a callable, or a list of callables. Common choices: 'sum' for totals, 'mean' for averages, 'count' for frequencies, 'min'/'max' for extremes. When you pass a list, each aggregation gets its own level in the column MultiIndex.

# Using mean (default)
table_mean = pd.pivot_table(df, values='revenue',
                            index='region', columns='product',
                            aggfunc='mean')
print(table_mean.round(1))
# product      A      B
# region
# East     255.0  150.0
# West     340.0  350.0

# Using count
table_count = pd.pivot_table(df, values='revenue',
                             index='region', columns='product',
                             aggfunc='count')
print(table_count)

Handling Missing Cells with fill_value

When a combination of row and column labels has no data, the cell contains NaN by default. Pass fill_value to replace those missing cells with a meaningful default, such as 0 for counts or revenue. This makes the table easier to read and prevents downstream arithmetic operations from silently producing NaN results.

df2 = pd.DataFrame({
    'region':  ['East', 'West', 'East'],
    'product': ['A',    'A',    'B'],
    'revenue': [200,    340,    150]
})

# West-B combination has no data -> NaN by default
table = pd.pivot_table(df2, values='revenue', index='region',
                       columns='product', aggfunc='sum', fill_value=0)
print(table)
# product    A    B
# region
# East     200  150
# West     340    0  <- filled with 0 instead of NaN

Adding Subtotals with margins

Pass margins=True to add row and column totals to the pivot table. Pandas appends an 'All' row at the bottom and an 'All' column on the right, containing the aggregated values across all categories. You can rename the margin label with margins_name. This mirrors the 'Grand Total' row in Excel pivot tables.

table = pd.pivot_table(df, values='revenue', index='region',
                       columns='product', aggfunc='sum',
                       fill_value=0, margins=True, margins_name='Total')
print(table)
# product    A     B  Total
# region
# East     510   150    660
# West     340   700   1040
# Total    850   850   1700

Multiple Values in pivot_table

The values parameter can be a list of column names to aggregate several metrics at once. The result has a column MultiIndex where the outer level is the value column and the inner level is the category. This lets you create a comprehensive summary table in a single call instead of building and merging multiple separate pivot tables.

df['units'] = [10, 15, 8, 12, 14, 18]

table = pd.pivot_table(df,
                       values=['revenue', 'units'],
                       index='region',
                       columns='product',
                       aggfunc='sum')
print(table)
# Columns: (revenue, A), (revenue, B), (units, A), (units, B)
print(table.columns.tolist())

Hierarchical index and columns

When you pass a list to index or columns, the pivot table has a MultiIndex on the corresponding axis. This lets you create more granular summaries — for example, breaking down revenue by region and quarter on the rows, and by product on the columns. Access sub-levels with .loc and index tuples as usual.

df['quarter'] = ['Q1', 'Q1', 'Q2', 'Q2', 'Q1', 'Q2']

table = pd.pivot_table(df, values='revenue',
                       index=['region', 'quarter'],
                       columns='product',
                       aggfunc='sum', fill_value=0)
print(table)
# product         A    B
# region quarter
# East   Q1     510    0
#        Q2       0  150
# West   Q1     340    0
#        Q2       0  700

Flattening the Result

After creating a pivot table, the index is the grouping column and the column MultiIndex (when using multiple values) can be unwieldy. A common clean-up pattern is to call reset_index() to flatten the row index, then collapse the column MultiIndex into a single level by joining the levels with an underscore using a list comprehension.

table = pd.pivot_table(df, values=['revenue', 'units'],
                       index='region', columns='product', aggfunc='sum')

# Flatten MultiIndex columns
table.columns = ['_'.join(str(c) for c in col) for col in table.columns]
table = table.reset_index()
print(table.columns.tolist())
# ['region', 'revenue_A', 'revenue_B', 'units_A', 'units_B']

pivot_table vs groupby().agg()

Both pivot_table and groupby().agg() produce summary statistics. The difference is in the output shape: groupby().agg() returns a long format DataFrame with one row per group combination, while pivot_table returns a wide format table where one dimension becomes columns. For dashboards and reports, the wide format of pivot tables is often more readable; for further machine learning or statistical analysis, long format is preferred.

# Long format (groupby)
long = df.groupby(['region', 'product'])['revenue'].sum().reset_index()
print(long)
# region product  revenue
# East        A      510
# East        B      150

# Wide format (pivot_table)
wide = pd.pivot_table(df, 'revenue', 'region', 'product', 'sum', fill_value=0)
print(wide)
# product    A    B
# region
# East     510  150

Sorting and Styling the Pivot Table

A pivot table is a regular DataFrame, so you can sort it, compute derived columns, and format it exactly like any other Pandas DataFrame. For example, sort by a specific product column descending to rank regions by that product's performance, or add a percentage column by dividing each cell by the row total.

table = pd.pivot_table(df, 'revenue', 'region', 'product', 'sum', fill_value=0)

# Sort by product A revenue descending
table_sorted = table.sort_values('A', ascending=False)
print(table_sorted)

# Add percentage of row total
table['A_pct'] = (table['A'] / table.sum(axis=1) * 100).round(1)
print(table)

Practical Use: Sales Dashboard Table

Pivot tables are a core tool for building management reports and dashboards. A typical workflow: load raw transaction data, create a pivot table with months as columns and product categories as rows, add margin totals, then export to Excel. The entire workflow from raw data to boardroom-ready table takes just a handful of Pandas calls.

# Simulated monthly product revenue pivot
result = pd.pivot_table(
    df,
    values='revenue',
    index='product',
    columns='region',
    aggfunc='sum',
    fill_value=0,
    margins=True,
    margins_name='Grand Total'
)
print(result)
# Export to Excel
# result.to_excel('sales_pivot.xlsx')

Quick Check

Test your understanding of pd.pivot_table from this lesson.

Lesson Recap

In this lesson you learned: pd.pivot_table() creates cross-tabulation summaries with one dimension as rows and another as columns; fill_value handles missing cells and margins=True adds totals; you can aggregate multiple values at once; and pivot tables produce wide-format output ideal for reports. Next up we explore the reverse operation: melt() to convert wide data back to long format.

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

هل درس «‏pivot_table: الجدولة التقاطعية» مجاني؟

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

ماذا ستتعلم في «‏pivot_table: الجدولة التقاطعية»؟

أنشئ جداول محورية على نمط Excel باستخدام pd.pivot_table، مع تحديد index وcolumns وvalues وaggfunc. تتمرن على Pandas & NumPy Academy مع أكواد عملية تشغلها مباشرة في المتصفح، ومدرس ذكاء اصطناعي متاح 24/7 يجيب على أسئلتك أثناء عملك.

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

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

كم من الوقت يستغرق درس «‏pivot_table: الجدولة التقاطعية»؟

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

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

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

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

  1. ‏pivot_table: الجدولة التقاطعية
  2. ‏melt: من التنسيق العريض إلى الطولي
  3. ‏stack وunstack مع MultiIndex
  4. ‏crosstab لجداول التكرارات
← العودة إلى Pandas & NumPy Academy