

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Difficulty: 5
click for more info
Not enough gems
Cost: 6 gems
1: What Is Pandas?
incomplete
2: Series
incomplete
3: DataFrames
incomplete
4: Derived Columns
incomplete
5: Series vs. DataFrame
incomplete
6: Filtering Data
incomplete
7: The Index in Pandas
incomplete
8: Custom Indexes
incomplete
9: Loading Data
incomplete
10: Inspect Head
incomplete
11: Info & Describe
incomplete
12: Inspecting Workflow
incomplete
13: Data Properties
incomplete
14: Inspecting Columns
incomplete
Back
ctrl+,
Next
ctrl+.
This lesson's interactive features are locked, please to keep using them
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.
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
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.
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".