πŸͺ

Essential cookies keep authentication working. With your permission, we also use analytics to improve the product. Privacy Policy

DDataEngPrep.tech
Home
PricingBlog
Sign InStart Free→
Home/Questions/Python/Coding/Explain Stack vs Unstack and their use in data transformation.

Explain Stack vs Unstack and their use in data transformation.

Python/Codingeasy2 min read

Reviewed by Aditya Kumar Β· Last reviewed 2026-03-24

Stack and unstack are fundamental Pandas DataFrame methods used for reshaping data between "long" and "wide" formats by manipulating index levels and columns. Stack transforms columns into rows,…

πŸ€– Analyze Your Answer
Frequency
Low
Asked at 1 company
Category
179
questions in Python/Coding
Difficulty Split
127E|24M|28H
in this category
Total Bank
1,863
across 7 categories
Part of the Python for Data Engineers Interview Preparation Hub
Explore Python for Data Engineers Hub→
Reported in Interview Loops AtClick to view company-specific questions
🏒 Fractal Interview Hubβ†’

Why This Question Matters

This easy-level Python/Coding question appears frequently in data engineering interviews at companies like Fractal. While less common, it tests deeper understanding that distinguishes strong candidates.

How to Approach This

Start by clearly defining the core concept being asked about. Interviewers want to see that you understand the fundamentals before diving into implementation details. Structure your answer with a definition, then explain the practical application with a concise example. The expert answer includes a code example that demonstrates the implementation pattern.

Expert Answer
358 wordsIncludes code

Stack and unstack are fundamental Pandas DataFrame methods used for reshaping data between "long" and "wide" formats by manipulating index levels and columns. Stack transforms columns into rows, creating a MultiIndex, moving from a wide to a long format. Conversely, unstack pivots one or more levels from the DataFrame's index into new columns, transforming data from long to wide.

Mechanics and Use Cases

df.stack() takes the innermost column level and rotates it into the innermost row index level, resulting in a Series (if a single column) or DataFrame with a MultiIndex. This is useful for normalizing data, preparing it for statistical analysis that often expects a long format, or for efficient storage in analytical databases where columnar storage benefits from fewer distinct values per column (e.g., Snowflake, BigQuery).

df.unstack() performs the inverse operation. It takes a specified level from the DataFrame's index (which must be a MultiIndex) and pivots its unique values into new columns. This is commonly used for creating cross-tabulations, pivoting data for specific reports, or preparing data for tools that expect a wide format (e.g., certain visualization libraries or machine learning models). Both methods can take a level argument to specify which index/column level to operate on.

Example and Trade-offs

Consider a wide DataFrame. stack() will convert its columns into a new index level, making it "longer." If the original wide format had missing values, stack() might introduce NaNs. Conversely, unstack() will pivot an index level to columns, potentially introducing NaN values where combinations don't exist in the original data.
import pandas as pd
# Wide format DataFrame
df_wide = pd.DataFrame({'Sales_2020': [100, 150], 'Sales_2021': [110, 160]}, index=['NY', 'LA'])
# df_long = df_wide.stack() # Stacks 'Sales_2020', 'Sales_2021' into a new index level
# df_long.unstack(level=0) # Unstacks the first index level back to columns

In production, handling NaN values resulting from these transformations is crucial, often requiring fillna() or careful aggregation. For very large datasets, these operations can be memory-intensive, and their performance should be evaluated.

In the interview, also mention how these operations are fundamental for data normalization and denormalization, impacting data storage efficiency and query performance in systems like columnar databases.

⚑
Pro Tip

Pro-Move: melt/pivot for complex reshape. Red Flag: Confusing axis in multi-index.

Get The Complete 2026 FDE, AI & DE Master Vault (All 9 PDF Volumes)
FDE Interview Guide, FastMCP & RAG Playbook, and 7-Volume DE Vault with 1,863+ answers β†’
⭐ Save 45%

Related Python/Coding Questions

easyWhat are traits in Scala, and how are they different from classes?FreemediumWrite a Python function to check if a string is a palindrome.FreeeasyWhat is the difference between a list and a tuple in Python?FreeeasyExplain the difference between shallow copy and deep copy in Python.FreeeasyWrite a Python function to find the first non-repeating character in a string.Free

Level up your prep

Recommended
Educative
Educative Unlimited

800+ hands-on courses β€” Grokking System Design, Coding Patterns, and AI mock interviews for your DE loop.

Start learning β†’

Some links below are affiliate links. If you buy through them we may earn a small commission at no extra cost to you β€” it helps keep DataEngPrep free.

According to DataEngPrep.tech, this is one of the most frequently asked Python/Coding interview questions, reported at 1 company. DataEngPrep.tech maintains an editor-reviewed database of 1,863 data engineering interview questions across 7 categories.

← Back to all questionsMore Python/Coding questions β†’
Topic Hubs
All Topic Hubs (12 Competencies) β†’All 1,863+ QuestionsSQL Interview QuestionsApache Spark QuestionsPySpark QuestionsPython for Data EngineersSystem Design InterviewData Modeling & WarehousingStreaming (Kafka/Flink)SQL Window FunctionsETL Pipeline Design
Company Hubs
All Company Hubs (100+ Companies) β†’AmazonGoogleMetaDatabricksSnowflakeNetflixUberStripeMicrosoftAppleGoldman SachsAWS Engineering
Academies & Guides
All Guides & ArticlesData Engineering AcademyForward Deployed AI AcademyClient Simulation StudioApache Airflow QuestionsAzure Data EngineerBehavioral & STAR MethodCloud & Distributed Tools
AI Tools & Products
Answer Analyzer (Free)AI Mock InterviewsSQL PlaygroundATS Resume AnalyzerOffline PDF Answer VaultsMembership & Pricing
Company
About & Editorial PolicyContact UsAI DisclosureDisclaimerTerms of ServicePrivacy Policy
Β© 2026 DataEngPrep.tech. All rights reserved.
AboutBlogContactDisclaimer