Loc vs. Iloc Slicing in Pandas
Loc and iloc are two commonly used slicing methods in Pandas, which provide flexibility in selecting rows and columns from a DataFrame. However, understanding their subtle differences can be confusing.
Key Distinction: Labels vs. Locations
The primary difference between loc and iloc lies in the type of indexing they employ:
Examples:
Consider a DataFrame with a non-monotonic integer index:
df = pd.DataFrame({ 'a': [1, 2, 3], 'b': [4, 5, 6], 'c': [7, 8, 9] }, index=[0, 2, 4])
Loc:
Iloc:
Key Differences in Usage:
Feature | Loc | Iloc |
---|---|---|
Indexing | Labels | Integer locations |
Slicing | Inclusive (by default) | Exclusive (by default) |
Out-of-bounds behavior | KeyError | IndexError |
Negative indexing | Supported | Supported for final row only |
Boolean masking | NotImplementedError | Supports boolean mask |
Callable indexing | Function applied to index | Function applied to row or column |
When to Use Loc vs. Iloc:
The above is the detailed content of Loc vs. Iloc in Pandas: When Should I Use Each for Slicing?. For more information, please follow other related articles on the PHP Chinese website!