0Pricing
Pandas & NumPy Academy · درس

‏stack وunstack مع MultiIndex

حوّل المستوى الأعمق من الأعمدة إلى فهرس الصفوف باستخدام stack()، واعكس العملية باستخدام unstack().

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

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

Introduction to stack and unstack

stack() and unstack() are Pandas reshaping tools that move data between the row index and the column index. They are particularly useful when working with DataFrames that have a MultiIndex on either axis. stack() takes the innermost column level and rotates it into the innermost row level, while unstack() does the reverse.

stack(): Columns to Rows

DataFrame.stack() pivots the innermost level of the column labels into the innermost level of the row index, producing a longer, narrower result. If the original DataFrame had simple (non-multi) columns, the result is a Series with a MultiIndex. If the columns had multiple levels, stack() reduces the column levels by one.

import pandas as pd

df = pd.DataFrame({
    'Math': [85, 90, 78],
    'Science': [92, 88, 95]
}, index=['Alice', 'Bob', 'Carol'])

print(df)
#        Math  Science
# Alice    85       92
# Bob      90       88
# Carol    78       95

stacked = df.stack()
print(stacked)
# Alice    Math       85
#          Science    92
# Bob      Math       90
#          Science    88
# Carol    Math       78
#          Science    95
# dtype: int64

unstack(): Rows to Columns

Series.unstack() (or DataFrame.unstack()) is the inverse of stack(). It takes the innermost level of the row index and rotates it into new column labels, producing a wider result. This is functionally similar to pivot() but works directly on the index rather than on column values.

stacked = df.stack()
print(type(stacked))  # Series with MultiIndex

# Restore the original wide format
df_restored = stacked.unstack()
print(df_restored)
#        Math  Science
# Alice    85       92
# Bob      90       88
# Carol    78       95

# Identical to the original df!

Selecting Which Level to Stack

For DataFrames with a MultiIndex on the columns, stack(level) lets you choose which level to rotate. Pass a level number (0 for outermost, -1 for innermost, the default) or a level name. Similarly, unstack(level) selects which row-index level to rotate into columns. This fine-grained control is essential for navigating complex hierarchical data structures.

# MultiIndex columns
arrays = [['Math', 'Math', 'Science', 'Science'],
          ['Q1', 'Q2', 'Q1', 'Q2']]
multi_cols = pd.MultiIndex.from_arrays(arrays, names=['subject', 'quarter'])

df_multi = pd.DataFrame([[85, 90, 92, 88], [78, 80, 95, 91]],
                        index=['Alice', 'Bob'], columns=multi_cols)

# Stack the 'quarter' level (innermost, level=-1)
print(df_multi.stack(level='quarter').head())

unstack() on Specific Row Levels

When the DataFrame has a MultiIndex on rows (which is common after a groupby() on multiple columns), you can unstack() a specific row level to spread it across the columns. This is a very common pattern for building cross-tabulation style summaries without explicitly calling pivot_table().

# GroupBy produces MultiIndex rows
df2 = pd.DataFrame({
    'region': ['East', 'East', 'West', 'West'],
    'product': ['A', 'B', 'A', 'B'],
    'sales': [100, 150, 120, 200]
})

# MultiIndex result from groupby
multi = df2.groupby(['region', 'product'])['sales'].sum()
print(multi)

# Unstack the product level into columns
wide = multi.unstack('product')
print(wide)
# product    A    B
# region
# East     100  150
# West     120  200

Handling Missing Values in stack/unstack

When unstack() is called and not every row-index combination exists for every column level, Pandas fills missing cells with NaN. Conversely, stack() by default drops rows that are entirely NaN. You can control this with the dropna parameter: pass stack(dropna=False) to keep NaN rows.

# Incomplete data: West has no product B
df3 = df2[df2['product'] != 'B'].copy()
multi3 = df3.groupby(['region', 'product'])['sales'].sum()

wide3 = multi3.unstack('product', fill_value=0)
print(wide3)
# product    A    B
# region
# East     100    0  <- B filled with 0 instead of NaN
# West     120    0

stack() Then Compute on Rows

A powerful pattern is to stack() a wide DataFrame to convert columns into rows, apply a row-wise operation like filtering or groupby, then unstack() to return to wide format. This avoids the need to write column-by-column loops and keeps your code vectorised and readable. It is especially useful for applying the same transformation to every column simultaneously.

# Normalise each column by its column mean using stack/compute/unstack
normalised = (
    df.stack()
      .groupby(level=1)
      .transform(lambda s: (s - s.mean()) / s.std())
      .unstack()
)
print(normalised.round(2))
#        Math  Science
# Alice  0.0     0.39
# Bob    1.13   -1.09
# Carol -1.13    0.71

stack() for Plotting

Just like melt(), stack() converts data to long format, which is what Seaborn and many Matplotlib helpers expect. The main difference is that stack() operates on the column index and preserves the MultiIndex structure, while melt() produces a flat long DataFrame. Both lead to similar plotting workflows.

# Prepare data for line plot using stack
long = df.stack().reset_index()
long.columns = ['student', 'subject', 'score']
print(long)
#   student  subject  score
# 0   Alice     Math     85
# 1   Alice  Science     92
# ...

# Ready for: sns.barplot(data=long, x='student', y='score', hue='subject')

swaplevel() for Index Reordering

After stacking, the innermost row level is the original column name. Sometimes you want the outer level to be the variable name and the inner level to be the original row index. Use swaplevel() on the MultiIndex to swap the order of two levels, and then sort_index() to restore a clean ordering.

stacked = df.stack()  # MultiIndex: (student, subject)
swapped = stacked.swaplevel()  # MultiIndex: (subject, student)
swapped = swapped.sort_index()
print(swapped)
# subject  student
# Math     Alice      85
#          Bob        90
#          Carol      78
# Science  Alice      92
#          Bob        88
#          Carol      95

When to Use stack vs melt vs pivot

Choose stack() when working with MultiIndex column DataFrames and you want to reduce the column levels by one. Choose melt() when you have a flat DataFrame and want to go from wide to long format with control over which columns become rows. Choose pivot()/pivot_table() to go from long back to wide. These three tools cover all wide/long reshaping needs in Pandas.

# Decision guide (comment, not executable standalone):
# MultiIndex columns -> want fewer levels: use stack()
# Flat wide -> need long format for plotting/ML: use melt()
# Long -> need wide summary table: use pivot_table()
# Wide -> back to long: use melt() or stack()

# Example: stack when you have pivot_table output (MultiIndex cols)
tbl = df2.groupby(['region', 'product'])['sales'].sum().unstack()
long_again = tbl.stack().rename('sales').reset_index()
print(long_again)

Practical Summary: Reshaping Cheatsheet

Here is a concise mental model: stack() — columns collapse into rows, DataFrame gets narrower and taller. unstack() — rows expand into columns, DataFrame gets wider and shorter. melt() — named columns collapse into a key-value pair (two new columns). pivot_table() — a key-value column expands into multiple columns. All four are reversible, and knowing which direction to go is simply a matter of deciding whether the target analysis prefers wide or long format.

# stack/unstack cycle
df_wide = df.copy()             # wide format
df_long = df_wide.stack()       # long via stack
df_wide2 = df_long.unstack()    # back to wide

# melt/pivot cycle
df_melted = df_wide.melt(id_vars=[])    # wide -> long
# df_pivoted = df_melted.pivot(...)     # long -> wide

print('Original shape:  ', df_wide.shape)
print('After stack:     ', df_long.shape)
print('After unstack:   ', df_wide2.shape)

Quick Check

Test your understanding of stack and unstack with MultiIndex from this lesson.

Lesson Recap

In this lesson you learned: stack() rotates column labels into the row index to produce a longer, narrower result; unstack() does the reverse, rotating a row-index level into columns; both work with MultiIndex structures from groupby operations; and swaplevel() lets you reorder index levels. Next up we explore pd.crosstab() for quick frequency tables between categorical columns.

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

هل درس «‏stack وunstack مع MultiIndex» مجاني؟

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

ماذا ستتعلم في «‏stack وunstack مع MultiIndex»؟

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

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

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

كم من الوقت يستغرق درس «‏stack وunstack مع MultiIndex»؟

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

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

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

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

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