← Back to Pandas Course | Chapter 4: Indexing & Selection | Lesson 6 of 7

MultiIndex की बुनियादी बातें

एक MultiIndex rows को labels के दो या ज़्यादा levels देता है, grouped row headings वाली एक table की तरह।

In this page:

  1. MultiIndex Basics
Syntax
python
df = df.set_index(["column1", "column2"])
df.loc[(value1, value2)]

MultiIndex Basics

Hierarchical rows बनाने के लिए set_index([...]) से कई columns को index set करें। loc से एक outer level select करें, या xs से एक inner level। कई keys वाले groupby के बाद Hierarchical indexes naturally appear होते हैं।

Note: sort_index() MultiIndex slicing को faster और ज़्यादा predictable बनाता है।

उदाहरण: MultiIndex basics

python
import pandas as pd

df = pd.DataFrame({
    "country": ["FR", "FR", "JP", "JP"],
    "year": [2022, 2023, 2022, 2023],
    "gdp": [2.9, 3.0, 4.2, 4.3],
}).set_index(["country", "year"]).sort_index()
print(df)
print(df.loc["JP"])
print(df.loc[("FR", 2023), "gdp"])

# Output:
#               gdp
# country year
# FR      2022  2.9
#         2023  3.0
# JP      2022  4.2
#         2023  4.3
#       gdp
# year
# 2022  4.2
# 2023  4.3
# 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. एक unsorted MultiIndex slice करना
  2. multi-level selection के लिए एक tuple pass करना भूल जाना
  3. जब columns काफी होतीं MultiIndex overuse करना
चैप्टर सारांश
  • एक list वाला set_index एक MultiIndex बनाता है
  • loc outer levels pick करता है
  • xs कोई भी level pick करता है
  • पहले index sort करें
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 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.