October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run ScanOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk2 min

Pandas .loc vs .iloc: Labels, Positions, Slices, and Common Errors

Pandas .loc selects index and column labels; .iloc selects zero-based positions. See how integer indexes, slices, boolean masks, and errors differ.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use .loc when you mean an index or column label; use .iloc when you mean a zero-based position. An integer passed to .loc is still a label, not a position. For example, df.loc[0] selects the row labeled 0, while df.iloc[0] selects the first row.

What is the difference between .loc and .iloc?

The difference is what your selector refers to: .loc looks up labels, and .iloc counts positions from zero. Consider this DataFrame, whose row labels are letters:

As an Amazon Associate I earn from qualifying purchases.

import pandas as pd

df = pd.DataFrame(
    {"name": ["Ada", "Linus", "Grace"], "score": [98, 91, 95]},
    index=["a", "b", "c"]
)

df.loc["b"] returns the row labeled b (Linus). df.iloc[1] returns the row at position 1, which is also Linus in this example. They happen to reach the same row, but they use different rules.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The current stable pandas indexing guide describes .loc as primarily label-based. See the pandas indexing guide.

Why an integer index causes confusion

A DataFrame’s default index is usually 0, 1, 2, …. With that index, df.loc[0] appears to mean “first row” because the first row’s label is 0. It actually means “row whose label is 0.” If rows are reordered or the index is changed, the label and position may no longer match.

Use .iloc[0] when you specifically mean the first row, regardless of its label. Use .loc[0] when you specifically mean the row labeled 0.

How do .loc and .iloc slices differ?

.loc includes the stop label when that label is present. .iloc follows ordinary Python slicing: it includes the start position and excludes the stop position.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
df.loc["a":"b"]   # rows labeled "a" and "b"
df.iloc[0:2]      # positions 0 and 1

Here both expressions return the first two rows, but for different reasons. With .iloc, the stop value 2 is not included; with .loc, the endpoint label "b" is included.

How do you select rows and columns together?

Use a comma to separate the row selector from the column selector. Both selectors must follow the accessor’s convention:

df.loc["b", "score"]   # row label "b", column label "score"
df.iloc[1, 1]          # second row, second column
df.loc["a":"b", ["name", "score"]]
df.iloc[0:2, 0:2]

The same rule applies to Series: .loc selects by the Series index labels, while .iloc selects by position.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

What errors and boolean selectors should you expect?

  • Missing label: requesting a label that is not present with .loc raises KeyError.
  • Out-of-bounds position: an integer position outside the axis bounds passed to .iloc raises IndexError. Slice indexers can extend beyond the axis bounds under Python/NumPy slice behavior.
  • Boolean Series: .loc can use an index-aligned boolean Series, so its values are matched by index. .iloc expects a boolean array rather than an index-aligned Series; pass the values when you want array-style positional filtering.
  • Boolean arrays: both accessors accept boolean arrays. The pandas indexing guide says missing values in boolean arrays are treated as false.

For example, if mask is a boolean Series aligned to df, use df.loc[mask]. To give .iloc the boolean values as an array, use df.iloc[mask.to_numpy()].

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Which accessor should you choose?

  • Choose .loc when your code should keep referring to named rows or columns, even if their order changes.
  • Choose .iloc when your code should select a particular place in the current row or column order.

Memory aid: labels → .loc; positions → .iloc.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.