Skip to content
Tutorials Center
My learning

Topics

Lesson 13 of 64 ยท Selecting and Filtering

loc and iloc

Learn the difference between loc (labels) and iloc (positions), how slices behave, how to filter and assign with masks, and how at and iat read single cells.

Square brackets are handy, but they do several jobs at once. For precise work pandas offers two dedicated indexers: loc selects by label, and iloc selects by integer position. Both take the form df.loc[rows, columns], so you can choose rows and columns in one step.

Understanding this pair is one of the biggest steps toward fluent pandas. This lesson explains the rule that separates them, the one slicing difference that trips everybody up, how to combine them with boolean masks, how to write values safely, and what the typical errors mean. It builds on Selecting Columns and Rows.

Labels versus positions

Every row has a label (its value in the index) and a position (0 for the first row, 1 for the second, and so on). With the default RangeIndex the two happen to be equal, which hides the difference. Give the rows real labels and the difference becomes visible.

flowchart LR
    subgraph T["DataFrame"]
        direction TB
        R0["position 0, label 'mon'"]
        R1["position 1, label 'tue'"]
        R2["position 2, label 'wed'"]
    end
    L["df.loc['tue']"] --> R1
    P["df.iloc[1]"] --> R1

Both indexers can reach the same row; loc asks for the label, iloc asks for the position.

Python Same row, two ways

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

A single label or position returns a Series (the row, whose index is the column names); a list returns a DataFrame; a pair [row, column] of single values returns one scalar.

Rows and columns together

The second argument selects columns. Use : to mean "all".

Python Two-dimensional selection

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

When a single row or column is requested, you get a Series; otherwise a DataFrame. If you need a DataFrame even for one row, wrap it in a list: week.loc[["tue"]].

The slicing difference

This is the rule worth memorizing:

Indexer Slice end Example Result
iloc excluded df.iloc[0:3] positions 0, 1, 2
loc included df.loc["a":"c"] labels a, b, c

iloc follows Python's normal slicing. loc includes the end label because labels have no natural "one past the end", and it would be awkward to ask for "up to but not including c". The same applies when labels are numbers: df.loc[0:3] on a default index returns four rows.

Python Inclusive loc, exclusive iloc

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Watch out: after filtering or sorting, the index is no longer 0, 1, 2, .... Code that assumed label equals position, such as df.loc[0] to get "the first row", will pick the row whose label is 0 (or raise KeyError), not the first row. Use iloc[0] for "the first row".

Boolean masks with loc

loc also accepts a boolean Series or array of the same length as the rows. This is how you filter and choose columns in one go. The full story of building conditions is in Filtering with Conditions.

Python A mask plus a column list

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

iloc accepts boolean arrays too, but not a boolean Series with its own index; if you need to pass a Series, call .to_numpy() on it or use loc.

Setting values

Because loc names the rows and columns exactly, it is also the right way to write. The pattern is df.loc[rows, columns] = value.

Python Assigning with loc and iloc

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

In older pandas you often saw a "SettingWithCopyWarning" here. In pandas 3 Copy-on-Write is always on: a selection is a separate object and writing to stock changes only stock. Chained forms such as stock[stock["qty"] < 5]["flag"] = "low" do nothing to stock, because the first bracket produced a temporary copy. Write one loc call instead. The rules are covered in Creating and Changing Columns.

at and iat for single cells

When you need exactly one value, at (label) and iat (position) are faster and more explicit than loc and iloc. They accept only a single row and a single column.

Python Scalar access

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Use them for occasional lookups. If you find yourself calling them in a loop over every row, step back: a vectorised operation (see Vectorised Operations) is almost always the better answer.

Common errors and what they mean

Most indexing errors fall into a handful of patterns.

Python Reading the error messages

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

In short:

  • KeyError means a label does not exist. Check spelling, and check whether the labels are strings or integers.
  • IndexError means a position is out of range. Remember that positions start at 0.
  • TypeError usually means you mixed the two worlds, such as passing a label to iloc.
  • IndexingError ("too many indexers") means you gave more indexes than there are dimensions.
  • Slices never raise for out-of-range ends: iloc[1:50] quietly returns what exists. A list of positions, however, is checked strictly.

Which one should I use?

Pick loc when you are thinking in terms of names: a date, a customer id, a column called price. Pick iloc when you really mean "the first three rows" or "the last column". For conditions, loc with a mask is the standard. Mixing, such as a row label with a column position, is not supported directly; convert one side first, for example df.loc[label].iloc[2], or use df.columns.get_loc("name") to turn a column name into a position.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A DataFrame has the index ['a', 'b', 'c', 'd']. How many rows does df.loc['a':'c'] return?

    Slices with loc include the end label, so the rows labeled a, b and c are returned.
  2. 2. After sorting a DataFrame by a column, which expression always returns the first row of the sorted result?

    Sorting reorders the rows but keeps their labels, so label 0 may no longer be first. iloc[0] always means the first position.
  3. 3. Which line sets the status column to 'late' for every row where days > 30?

    A single loc call with a mask and a column name writes into the original DataFrame. The chained form modifies a temporary copy, and iloc and at do not take a boolean Series that way.
  4. 4. What does df.iloc[1:50] do on a DataFrame with 10 rows?

    Slices are forgiving about out-of-range ends, just like Python lists. Only a single position or a list of positions raises IndexError.

Summary

  • loc selects by label, iloc by integer position; both use [rows, columns].
  • iloc slices exclude the end, loc slices include it.
  • A single label or position gives a Series or scalar; a list gives a DataFrame.
  • df.loc[mask, columns] filters and selects together, and df.loc[mask, "col"] = value writes safely in one step.
  • With Copy-on-Write, chained assignment such as df[mask]["col"] = x never changes df.
  • at and iat read or write one cell; KeyError means a bad label, IndexError a bad position.

Next up: build conditions that combine several tests in Filtering with Conditions.