python

🔶 Pandas: loc vs iloc — THE Most Asked Question

# loc = Label-based (uses index/column NAMES)
# iloc = Integer position-based (uses 0-indexed positions)

df.loc[0:5]     # Rows with LABELS 0 through 5 → INCLUSIVE (6 rows)
df.iloc[0:5]    # Rows at POSITIONS 0 through 4 → EXCLUSIVE (5 rows)

The key gotcha: loc includes BOTH endpoints. iloc excludes the end (like normal Python slicing).

Most common real-world usage:

# Boolean filtering + column selection (this is what you'll actually write)
df.loc[df['age'] > 30, 'name']            # Label-based filter + column
df.loc[df['salary'] > 100000, ['name', 'dept']]  # Multiple columns

The SettingWithCopyWarning (bonus — it's related):

# WRONG — may modify a copy, not the original
df[df['category'] == 'A']['price'] = 10

# RIGHT — use loc for assignment
df.loc[df['category'] == 'A', 'price'] = 10