Skip to main content

Command Palette

Search for a command to run...

Loc vs iLoc in Python Pandas

Published
•2 min read•View as Markdown

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: loc is 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 the start_label and end_label are included in the selection.

    • Can use boolean arrays: You can pass boolean arrays to loc for filtering rows.

    • Works with string labels, integer labels, or datetime objects: Whatever your DataFrame's index or column names are, loc expects 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: iloc is primarily integer-location based. This means you use the integer positions (from 0 to n-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), the end_index is 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, iloc treats 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)