Pandas Series & DataFrame Internals (.loc vs .iloc)
1Concept
Pandas structures data into 1D `Series` and 2D `DataFrame` objects. `.loc` accesses rows and columns by label/name; `.iloc` accesses elements strictly by integer 0-indexed positions. Understanding the distinction prevents subtle data extraction bugs.
2Architecture Diagram
df.loc['row_label', 'col_name'] ---> Label-based indexing (inclusive of end!) df.iloc[0:2, 0:3] ---> Position-based integer indexing (exclusive of end!)
3Code Example
Python 3.12
# Simulating DataFrame index behaviors
records = [
{"user_id": 101, "name": "Alice", "spend": 450.0},
{"user_id": 102, "name": "Bob", "spend": 120.5}
]
print("=== DataFrame Indexing Hierarchy ===")
print(f"Record 0 (iloc[0]): {records[0]['name']} (Spend: ${records[0]['spend']})")
print("Rule: Use .loc for explicit labels; use .iloc for integer row indices.")4Expected Output
=== DataFrame Indexing Hierarchy === Record 0 (iloc[0]): Alice (Spend: $450.0) Rule: Use .loc for explicit labels; use .iloc for integer row indices.
5Key Takeaways
- ✓`.loc` slices are INCLUSIVE of both start and end bounds; `.iloc` slices are EXCLUSIVE of end.
- ✓Avoid chained indexing (`df['col'][0] = val`); it triggers `SettingWithCopyWarning`.
- ✓Use `.copy()` when slicing a DataFrame to avoid mutating the original dataset.