What is loc?
loc is a pandas accessor for label-based indexing and selection. It’s one of the most powerful tools for working with DataFrames because it allows you to access data using labels (row and column names) instead of numeric positions.
Why use loc instead of direct indexing?
- Works with any index type (integers, strings, dates, etc.)
- Supports boolean indexing for conditional selection
- Allows range slicing by labels (inclusive on both ends)
- More readable and maintainable code
- Essential for complex filtering operations
Key characteristics:
- Label-based: Uses row/column names, not positions
- Inclusive: Both start and end are included in slices
- Flexible: Works with scalars, lists, slices, and boolean arrays
- Fast: Optimized for large datasets
(more…)