← Back to Pandas Course | Chapter 9: Reshaping Data | Lesson 2 of 6

stack/unstack() का उपयोग

stack columns को row index में ले जाता है और unstack किसी index level को वापस columns में ले आता है।

In this page:

  1. stack/unstack()
Syntax
python
stacked = df.stack()
unstacked = stacked.unstack()

stack/unstack()

stack सबसे अंदरूनी column level को row index में pivot करता है, जिससे MultiIndex वाली Series बनती है। unstack इसका उल्टा करता है और अक्सर दो keys वाले groupby के बाद उपयोग होता है। गायब combinations NaN बन जाते हैं।

Note: unstack(fill_value=0) खाली combinations को fill करता है।

उदाहरण: stack/unstack()

python
import pandas as pd

df = pd.DataFrame({"g": ["a", "a", "b"], "k": ["x", "y", "x"], "v": [1, 2, 3]})
s = df.groupby(["g", "k"])["v"].sum()
print(s)
print(s.unstack(fill_value=0))

# Output:
# g  k
# a  x    1
#    y    2
# b  x    3
# Name: v, dtype: int64
# k  x  y
# g
# a  1  2
# b  3  0
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. यह भूल जाना कि stack का result एक Series है
  2. unstack के बाद NaN को handle न करना
  3. गलत level चुनना
चैप्टर सारांश
  • stack columns को rows में ले जाता है
  • unstack rows को columns में ले जाता है
  • groupby के साथ अच्छी तरह जोड़ी बनाता है
  • fill_value gaps handle करता है
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.