The Problem
Real data moment
The same real Chipotle data from Lessons 01-02 — all 4,622 real order rows this time, not a hand-picked excerpt:
import pandas as pd
df = pd.read_csv("chipotle.tsv", sep="\t")
print(df.head())
order_id quantity item_name choice_description item_price
0 1 1 Chips and Fresh Tomato Salsa NaN $2.39
1 1 1 Izze [Clementine] $3.39
2 1 1 Nantucket Nectar [Apple] $3.39
3 1 1 Chips and Tomatillo-Green Chili Salsa NaN $2.39
4 2 2 Chicken Bowl [Tomatillo-Red... $16.98
One line, and every real quoting/comma problem from Lesson 01 is already handled correctly — notice NaN in place of the literal text "NULL" from the raw file, too: pandas recognized that string as a real missing-value marker automatically.
The gotcha
Filter the DataFrame, and look closely at what's on the left:
bowls = df[df["item_name"] == "Chicken Bowl"]
print(bowls.head())
order_id quantity item_name ... item_price
4 2 2 Chicken Bowl ... $16.98
5 3 1 Chicken Bowl ... $10.98
13 7 1 Chicken Bowl ... $11.25
19 10 1 Chicken Bowl ... $8.75
26 13 1 Chicken Bowl ... $8.49
Those row labels — 4, 5, 13, 19, 26 — are the rows' original positions in the full 4,622-row DataFrame, not 0, 1, 2, 3, 4. Filtering removed rows; it didn't relabel the ones that survived.
print(bowls.iloc[0])
order_id 2
quantity 2
item_name Chicken Bowl
item_price 16.98
Name: 4, dtype: object
print(bowls.loc[0])
KeyError: 0
.iloc[0] works — it means "the first row, by position," and there is one. .loc[0] raises a real KeyError — it means "the row labeled 0," and after filtering, no row in bowls carries that label anymore (it belonged to "Chips and Fresh Tomato Salsa," filtered out).
.loc is label-based, .iloc is position-based — and they quietly agree until you filter or sort
On a freshly loaded DataFrame, the index labels happen to match row positions (0, 1, 2, ...), so .loc[0] and .iloc[0] return the same thing and the distinction feels academic. The moment a DataFrame is filtered, sorted, or otherwise reshaped, that coincidence ends — and code that quietly assumed "the index is just row numbers" breaks in a way that looks like a pandas bug but is actually a correct, documented distinction.
After steak = df[df["item_name"] == "Steak Burrito"], which statement about steak's index is correct?
Filtering (like sorting) never automatically resets the index — the surviving rows keep whichever labels they had in the original df. That's exactly why steak.loc[0] can raise a KeyError even though steak.iloc[0] works fine: the label 0 only still exists in steak if the very first row of the original df happened to be a Steak Burrito.