skip to content

In pandas, how do df.loc and df.iloc differ on a frame indexed by non-sequential employee IDs, and what does each slice include?

level: juniorimportance: must knowfreq 85%

answer

  1. labels versus offsets
  2. which end of the slice survives
  3. stored order, not numeric order
  4. KeyError versus IndexError

basics

~20 s

df.loc selects by index label and its slices include both endpoints; df.iloc selects by 0-based position and its slices exclude the stop. On an ID index, loc[1007] is employee 1007 and iloc[1] is the second row.

solid answer

~40 s

`loc` is label-based: `emp.loc[1007]` finds the row whose index label is 1007, and `emp.loc[1007:1099]` returns every row from label 1007 through label 1099 **inclusive**, walking the index in its stored order. `iloc` is position-based: `emp.iloc[1:3]` returns the rows at positions 1 and 2, half-open like a Python slice, whatever their labels are. The failures differ too: a missing label raises `KeyError` from `loc`, a single out-of-range position raises `IndexError` from `iloc`, and an out-of-range `iloc` *slice* is simply truncated. On an unsorted index, a `loc` slice whose endpoint is absent raises `KeyError`; after `sort_index()` the same slice selects by rank. Both take a second, column, selector: when 1007 is the second stored row and `salary` the second column, `emp.loc[1007, 'salary']` and `emp.iloc[1, 1]` read the same cell.

code

python · 23 lines
python
import pandas as pd

emp = pd.DataFrame(
    {"name": ["Ana", "Ben", "Cho", "Dev", "Eli"],
     "salary": [52000, 81000, 77000, 60000, 49000]},
    index=pd.Index([1042, 1007, 1311, 1099, 1500], name="emp_id"),
)

print(emp.loc[1007:1099].index.tolist())   # labels, both ends included
print(emp.iloc[1:3].index.tolist())        # positions 1 and 2, stop excluded
print(emp.iloc[3:10].index.tolist())       # out-of-range slice is truncated

try:
    emp.loc[2]                 # 2 is not an employee ID
except KeyError as err:
    print("KeyError:", err)

try:
    emp.loc[1000:1200]         # endpoint 1000 missing, index unsorted
except KeyError as err:
    print("KeyError:", err)

print(emp.sort_index().loc[1000:1200].index.tolist())  # sorted: select by rank

go deeper

for a junior

Recall the two rules cold: loc means labels with both ends included, iloc means positions with the stop excluded. Then name the exception each raises when the key is not there.

for a middle

Explain that a loc slice resolves its endpoints to positions and follows stored order, why a missing endpoint needs a sorted index, and why an out-of-range iloc slice is truncated rather than raising.

for a senior

Show the habit that prevents bugs: loc when the code means an entity, iloc when it means a rank, explicit conversion with get_loc or index[...] when both are needed, and sort_index before range slicing.

for a principal

Frame it as a review convention: an index that is not 0..n-1 exposes every positional assumption, so selections whose meaning changes after a reorder should be flagged before they reach a pipeline.

## Two accessors, two coordinate systems A pandas `DataFrame` has two ways to name a row. The **label** is the value stored in its `Index` (the row labels); the **position** is its 0-based offset in the current row order. When a frame is indexed `0..n-1` the two coincide and bugs hide. They stop coinciding the moment the index holds real identifiers, such as an employee table indexed by IDs: ```python import pandas as pd emp = pd.DataFrame( {"name": ["Ana", "Ben", "Cho", "Dev", "Eli"], "salary": [52000, 81000, 77000, 60000, 49000]}, index=pd.Index([1042, 1007, 1311, 1099, 1500], name="emp_id"), ) emp.loc[1007] # the row labelled 1007 (Ben) emp.iloc[1] # the row at position 1 (also Ben, by coincidence of order) emp.loc[2] # KeyError: 2 is not an employee ID emp.iloc[2] # Cho, the third row ``` - **`DataFrame.loc`** is primarily **label based**: an integer such as `5` is read as a label, never as a position. - **`DataFrame.iloc`** is primarily **integer-position based**, from `0` to `length-1`; passing a label raises. - Both accept a single key, a list of keys, a slice, a boolean array and a callable, and both take an optional second selector for the columns: `emp.loc[1007, "salary"]` and `emp.iloc[1, 1]` address the same cell. ## What a loc slice includes A label slice includes **both** endpoints when they are present in the index. pandas looks up the position of each endpoint and returns everything between them **in stored order**, so `emp.loc[1007:1099]` returns Ben, Cho and Dev: three rows, including 1311 even though 1311 is numerically larger than 1099. It is not a numeric range filter. When an endpoint is **missing**, pandas needs a sorted index to know where it would fall: 1. On an unsorted index, `emp.loc[1000:1200]` raises `KeyError` ("Cannot get left slice bound for non-monotonic index with a missing label 1000"). 2. After `emp.sort_index()`, the same slice selects every label that ranks between 1000 and 1200: 1007, 1042 and 1099. 3. With a step, `loc[start:stop:step]` treats start and stop as labels but applies the step over positions inside that range. Inclusive ends make sense for labels: you rarely know the label that comes *after* the last one you want, and with string or date labels "one past the end" may not exist. ## What an iloc slice includes `iloc` follows Python and NumPy slicing: the start is included and the stop excluded, so `emp.iloc[1:3]` returns positions 1 and 2, two rows. Negative positions count from the end (`emp.iloc[-1]` is the last row), and slices may run past the end: `emp.iloc[3:10]` returns the two remaining rows instead of raising. ## The errors each one raises | Call | Key not there | Result | |---|---|---| | `emp.loc[2]` | label 2 absent | `KeyError: 2` | | `emp.loc[[1007, 9999]]` | one label absent | `KeyError` naming 9999 | | `emp.iloc[7]` | position past the end | `IndexError: single positional indexer is out-of-bounds` | | `emp.iloc[3:10]` | slice past the end | truncated, no error | | `emp.iloc[1, "salary"]` | a label given to `iloc` | `ValueError` listing the allowed key types | `loc` never falls back to positions when a label is missing, and `iloc` never looks at labels. ## Lists, columns and callables - **Lists** return rows in the order you list them: `emp.loc[[1500, 1007]]` puts Eli before Ben; `emp.iloc[[0, -1]]` takes the first and last rows. - **Columns** use the same rules on the second axis: `emp.loc[:, "name":"salary"]` includes `salary`; `emp.iloc[:, 0:1]` stops before position 1. - **A callable** receives the frame being indexed and must return something that accessor accepts. `emp.loc[lambda d: d["salary"].idxmax()]` returns the top earner's row without a temporary variable, which is what makes callables useful in method chains. For `iloc`, returning a row-and-column tuple from the callable is not supported. ## Mistakes interviewers listen for - Saying a `loc` slice "stops before" its end label, which is the `iloc` rule. - Reading `emp.loc[1007:1099]` as a numeric filter on IDs; it is a range of stored positions between two labels. - Expecting `emp.iloc[1007]` to find employee 1007; it asks for row number 1007 and raises `IndexError`. - Assuming a sorted-looking index is sorted; check `emp.index.is_monotonic_increasing` before slicing with a missing endpoint. ## A habit that avoids the confusion **Choose the accessor by what the code means.** If the code means "employee 1007", use `loc`; if it means "the first three rows after sorting", use `iloc`. When you need both, convert one side explicitly — `emp.iloc[:2, emp.columns.get_loc("salary")]` or `emp.loc[emp.index[:2], "salary"]` — so the selection keeps its meaning after rows are reordered or a column is inserted. Boolean filtering with masks and writing values through `loc` or `iloc` follow the same accessors but are separate topics.

  • What does a callable passed to loc receive, and when is it useful?
    It receives the object being indexed, the DataFrame or Series at that point in a chain, and must return something `loc` accepts: a label, a list, a slice or a boolean array. It lets you select from an intermediate result without naming it, such as `emp.loc[lambda d: d['salary'].idxmax()]` for the top earner's row. With `iloc`, returning a row-and-column tuple from the callable is not supported.
  • How do you take the first two rows of the salary column when you know the rows by position and the column by name?
    Keep one accessor and convert the other axis: `emp.iloc[:2, emp.columns.get_loc('salary')]` turns the column name into a position, and `emp.loc[emp.index[:2], 'salary']` turns the positions into labels. Either way the selection keeps its meaning if a column is inserted or the rows are reordered.
  • Why does emp.loc[1007:1099] include employee 1311 although 1311 is larger than 1099?
    A label slice resolves each endpoint to its position and returns everything between them in stored order; it does not compare values when both labels exist. In this frame 1311 is stored between 1007 and 1099, so it is included. Only a missing endpoint makes pandas need a sorted index, and then it selects by rank.

loc is a house number: '1007 Elm Street' names one house however you walk the street, and 'from 1007 to 1099' includes both of those houses. iloc is 'the second house from the corner': it depends on where you start counting, and 'houses 1 up to 3' stops before the fourth.

  • loc slices stop before the end label, just like Python slices.
  • emp.iloc[1007] finds the employee whose ID is 1007.
  • A loc label slice keeps IDs numerically between the endpoints, whatever the row order.
  • An iloc slice that runs past the last row raises IndexError.
  • loc falls back to positions when an integer label is missing.