Index and MultiIndex

Pandas Basics

2 min read

Published Sep 29 2025, updated Aug 17 2026


21
0
0
0

PandasPython

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   35

0,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   35

Now the index is Name, which can be used for label-based access:

df.loc["Bob"]

Output:

Age    30Name: Bob, dtype: int64




Index Properties and Methods

Attribute / Method

Description

df.index

Returns the index object

df.columns

Returns column labels (also an Index object)

df.reset_index()

Resets the index to default RangeIndex, optionally keeping old index as column

df.set_index("col")

Sets a column as index

df.sort_index()

Sorts rows by index labels

df.index.name

Set or get the name of the index

df.index.values

Get array of index values

df.index.is_unique

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    250

Region 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    150


Specific row:

df.loc[("East","Store2")]

Output:

Sales    150Name: (East, Store2), dtype: int64


Slicing 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])  
© 2025 SimpleSteps.guide
AboutFAQPoliciesContact
Pandas Basics | Index and MultiIndex | SimpleSteps.guide