Loc vs iLoc in Python Pandas
loc and iloc are two of the most commonly used indexing methods in Pandas DataFrames, and they are crucial for selecting data. The key difference lies in how they interpret the "labels" or "indices" you provide:
loc (Label-based indexing)
Syntax:
df.loc[row_label, column_label]What it does:
locis primarily label-based. This means you use the actual row and column labels (names) to select data.Key Characteristics:
Inclusive of end label: When using slicing with
loc(e.g.,start_label:end_label), both thestart_labelandend_labelare included in the selection.Can use boolean arrays: You can pass boolean arrays to
locfor filtering rows.Works with string labels, integer labels, or datetime objects: Whatever your DataFrame's index or column names are,
locexpects those exact labels.Allows for single labels, lists of labels, or slices of labels.
iloc (Integer-location based indexing)
Syntax:
df.iloc[row_index, column_index]What it does:
ilocis primarily integer-location based. This means you use the integer positions (from 0 ton-1, similar to standard Python list indexing) to select data.Key Characteristics:
Exclusive of end index for slicing: When using slicing with
iloc(e.g.,start_index:end_index), theend_indexis excluded from the selection. This is consistent with standard Python slicing.Always uses integer positions: Regardless of whether your DataFrame has string labels or integer labels,
iloctreats them as positions.Allows for single integers, lists of integers, or slices of integers.
Feature | loc (Label-based) | iloc (Integer-location based) |
How to select | By actual row/column labels (names) | By integer position (0-indexed) |
Slicing end | Inclusive (both start and end labels are included) | Exclusive (end index is not included) |
Input types | Labels (strings, integers, datetime objects, etc.) | Integers only |
Use case | When you know the specific names of rows/columns | When you know the positional order of rows/columns |
Boolean arrays | Can be used for row filtering | Not directly for row filtering (use loc for that) |

