We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

Custom Indexes

While Pandas assigns integers as index labels by default – and that's often perfectly sufficient – you can also set custom indexes. This unlocks powerful features like automatic alignment, where Pandas matches rows by label instead of position.

Setting a Custom Index

If you have a column in a DataFrame that contains a unique identifier for each row, you can use that column as the index by calling the .set_index() method:

df = pd.DataFrame(
    {
        "flight": ["UA123", "DL456", "AA789"],
        "destination": ["Denver", "Atlanta", "Dallas"],
        "delay_minutes": [12, 0, 45],
    }
)

df = df.set_index("flight")
print(df)
#        destination  delay_minutes
# flight
# UA123       Denver             12
# DL456      Atlanta              0
# AA789       Dallas             45

Now rows are identified directly by the flight number (UA123, DL456...) instead of by sequential integers.

You can select rows directly using .loc[] with the index labels:

print(df.loc["UA123"])
# destination      Denver
# delay_minutes        12

Common Index Types

Two types of column that are often used for custom indexes are strings, like a product SKU:

products = pd.DataFrame(
    {
        "sku": ["BOOK-HIST-HC-9781", "JCKT-DNM-BLU-L", "LAMP-DSK-LED-WHT"],
        "price": [19.99, 29.99, 9.99],
        "stock": [100, 50, 200],
    }
).set_index("sku")

print(products)
#                    price  stock
# sku
# BOOK-HIST-HC-9781  19.99    100
# JCKT-DNM-BLU-L     29.99     50
# LAMP-DSK-LED-WHT    9.99    200

Though another common one is timestamps, which we'll cover later in the course.

Assignment

SnackStack's device registry has no single unique ID column, but each device's device_type and location are unique in combination. The support team wants to build a key from those two columns and use it as the index.

Complete the set_device_index function. It accepts a DataFrame and should return a new DataFrame indexed by a combined "device_key".