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

reset_index और set_index

set_index एक column को row labels में बदल देता है और reset_index labels को वापस एक normal column में बदल देता है।

In this page:

  1. reset_index/set_index
Syntax
python
df = df.set_index("column")
df = df.reset_index()

reset_index/set_index

set_index("col") एक column को index बनाता है, optionally इसे columns से drop करते हुए। reset_index() index को वापस एक column में move करता है और एक 0..n-1 index restore करता है; drop=True इसकी बजाय old index discard करता है। ये दोनों same coin के flip sides हैं।

Note: Filter करने के बाद, reset_index(drop=True) एक clean 0..n-1 index देता है।

उदाहरण: reset_index/set_index

python
import pandas as pd

df = pd.DataFrame({"id": [101, 102, 103], "name": ["Ann", "Bob", "Cy"]})
by_id = df.set_index("id")
print(by_id)
print(by_id.loc[102, "name"])
print(by_id.reset_index())

# Output:
#     name
# id
# 101  Ann
# 102  Bob
# 103   Cy
# Bob
#     id name
# 0  101  Ann
# 1  102  Bob
# 2  103   Cy
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. drop=True इस्तेमाल करके old index खोना
  2. यह भूल जाना कि दोनों नए DataFrames return करते हैं
  3. Index values को duplicate रखना
चैप्टर सारांश
  • set_index एक column को index में promote करता है
  • reset_index इसे demote करता है
  • drop=True old index discard करता है
  • दोनों नए DataFrames return करते हैं
🔒

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.