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

More Sorting

The .sort_index() method sorts a DataFrame by its index (the row labels) instead of by a column's values.

After filtering, those labels are often out of order. Sorting by index is also particularly handy when you've set a custom index like string IDs or timestamps.

# Sort by index
df_sorted = df.sort_index()

# Sort by index in descending order
df_sorted = df.sort_index(ascending=False)

In-Place Sorting

By default, .sort_values() returns a new DataFrame. Pass inplace=True to modify the original instead:

df.sort_values("close_price", inplace=True)

Handling Missing Values

Real market data has gaps. You can control where NaN ("Not a Number") values land in the sorted output:

# NaN values at the end (the default)
df_sorted = df.sort_values("close_price", na_position="last")

# NaN values at the beginning
df_sorted = df.sort_values("close_price", na_position="first")

This matters any time you sort by a numeric column that has missing values.

Assignment

SnackStack's field technicians need a daily service route. Devices that failed to report a temperature (a NaN reading) are the most suspicious, and everything else follows, hottest first.

Complete the build_service_route function. It accepts a DataFrame and returns a DataFrame ordered for the technician's route.

Sort by temperature_celsius in descending order with NaNs positioned first.