reset_index और set_index
set_index एक column को row labels में बदल देता है और reset_index labels को वापस एक normal column में बदल देता है।
In this page:
Syntax
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
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. #}
आम गलतियां
- drop=True इस्तेमाल करके old index खोना
- यह भूल जाना कि दोनों नए DataFrames return करते हैं
- 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: