Index and MultiIndex
Pandas Basics
2 min read
Published Sep 29 2025, updated Aug 17 2026
Guide Sections
Guide Comments
What is an Index?
- Every Pandas Series or DataFrame has an index.
- It labels rows, allowing you to access, slice, and align data.
- By default, a DataFrame gets a RangeIndex (0, 1, 2, …).
Example:
import pandas as pddf = pd.DataFrame({ "Name": ["Alice", "Bob", "Charlie"], "Age": [25, 30, 35]})print(df)Output:
Name Age0 Alice 251 Bob 302 Charlie 350,1,2 is the default index.
Custom Index
- You can set a column as the index using
.set_index():
df.set_index("Name", inplace=True)print(df)Output:
AgeName Alice 25Bob 30Charlie 35Now the index is Name, which can be used for label-based access:
df.loc["Bob"]Output:
Age 30Name: Bob, dtype: int64Index Properties and Methods
Attribute / Method | Description |
| Returns the index object |
| Returns column labels (also an Index object) |
| Resets the index to default RangeIndex, optionally keeping old index as column |
| Sets a column as index |
| Sorts rows by index labels |
| Set or get the name of the index |
| Get array of index values |
| Check if index has unique labels |
MultiIndex (Hierarchical Index)
- MultiIndex allows multiple levels of indexing in rows or columns.
- Useful for grouped, hierarchical, or panel-like data.
- MultiIndex works well with
.groupby(),.pivot_table(), and aggregation.
Creating MultiIndex - from arrays
arrays = [ ["East", "East", "West", "West"], ["Store1", "Store2", "Store1", "Store2"]]index = pd.MultiIndex.from_arrays(arrays, names=("Region", "Store"))df = pd.DataFrame({ "Sales": [100, 150, 200, 250]}, index=index)print(df)Output:
SalesRegion Store East Store1 100 Store2 150West Store1 200 Store2 250Region is level 0, Store is level 1.
Creating MultiIndex - from tuples
tuples = [("East", "Store1"), ("East", "Store2"), ("West", "Store1"), ("West", "Store2")]index = pd.MultiIndex.from_tuples(tuples, names=("Region", "Store"))df = pd.DataFrame({"Sales": [100,150,200,250]}, index=index)Accessing MultiIndex data
Single level:
df.loc["East"]Output:
SalesStore Store1 100Store2 150Specific row:
df.loc[("East","Store2")]Output:
Sales 150Name: (East, Store2), dtype: int64Slicing levels:
df.loc[pd.IndexSlice["East":"West", "Store1":"Store2"], :]Resetting and swapping levels
# moves MultiIndex back to columnsdf.reset_index() # swaps level 0 and level 1df.swaplevel() Sorting MultiIndex
# sort by first leveldf.sort_index(level=0) # sort by second level, then firstdf.sort_index(level=[1,0])