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

The Index in Pandas

Every Series and DataFrame has an index – a set of row labels, which appear on the left side when you print one of these structures. By default, Pandas assigns integer indexes starting at 0:

0    28
1    35
2    19
3    42

Click to play video

Not Just an Offset

The index isn't just a display nicety, nor is it a naïve row counter. It's a much more flexible and powerful means for Pandas to keep track of rows internally. Two important things to know:

  1. The index persists through filtering. When you filter a DataFrame to keep only certain rows, the original index values come with those rows – they don't reset to 0, 1, 2.... You might end up with index values like 1, 3, 7 after a filter.

    # Original DataFrame has index 0, 1, 2
    df = pd.DataFrame(
        {
            "player": ["Curry", "Jokic", "Doncic"],
            "points": [22, 45, 50],
        }
    )
    
    # After filtering, index values are preserved
    big_games = df[df["points"] > 40]
    print(big_games)
    #    player  points
    # 1   Jokic      45
    # 2  Doncic      50
    
  2. You can reset the index with .reset_index(drop=True) to get a new DataFrame with a clean 0, 1, 2... sequence after filtering.

    big_games_reset = big_games.reset_index(drop=True)
    print(big_games_reset)
    #    player  points
    # 0   Jokic      45
    # 1  Doncic      50
    

If you call reset_index without setting drop=True, the old index becomes a new column called "index". Probably not what you want!

Assignment

SnackStack's support team filters device data to find sensors that need attention:

hot_devices = df[df["temperature"] > 80]

After filtering, the result keeps the original index values. That can leave the team with messy indexes like 5, 234, 891 in a tiny report.

Complete the reset_device_index function. It accepts a filtered DataFrame and should return a DataFrame with a fresh sequential index, plus a "unique_idx" label column built from that new index.