loc selects pandas rows and columns by label. iloc selects them by integer position. That is the whole difference between loc and iloc, and it shows up in four places: what you pass in, whether a slice includes its end, which error a missing key raises, and whether assignment can add a new row. An integer index label is still a label: .loc[20] asks for the row labelled 20, while .iloc[2] asks for the third row.
The distinction can stay hidden when a table has the default index 0, 1, 2, ..., because labels and positions start out identical. The examples below make them differ, so every result shows which rule is at work.
loc vs iloc: the differences at a glance
loc |
iloc |
|
|---|---|---|
| Selects by | Labels: index values and column names | Integer positions, starting at 0 |
| Slice end | Included: .loc[101:103] includes label 103 |
Excluded: .iloc[0:3] stops before position 3 |
| Accepts | A label, a list of labels, a label slice, a Boolean mask | An integer, a list of integers, an integer slice, a Boolean array |
| Missing key | Raises KeyError |
Raises IndexError (a slice past the end is allowed) |
| Assigning to a new key | Adds the row or column | Not allowed: iloc cannot enlarge the table |
| Typical use | Filtering by a condition, choosing columns by name, setting values | The first or last rows, the nth row, positional samples |
| Fastest for one value | df.at[label, column] |
df.iat[row, column] |
Both also accept a function that receives the table and returns a valid selection, which is useful at the end of a method chain.
loc vs iloc examples
This table has four rows labelled 101 to 104, so a label never equals its position:
import pandas as pd
df = pd.DataFrame(
{"name": ["Ada", "Ben", "Cy", "Di"], "score": [91, 78, 85, 62]},
index=[101, 102, 103, 104],
)
print(df.loc[102, "name"]) # row label 102, column "name"
print(df.iloc[1, 0]) # second row, first column: the same cell
print(df.loc[101:103].index.tolist()) # label slice, end included
print(df.iloc[0:3].index.tolist()) # position slice, end excluded
print(df.iloc[-1]["name"]) # last row
print(df.loc[df["score"] > 80, "name"].tolist()) # filter rows, pick a column
print(df.iloc[:, 1].tolist()) # second column by position
print(df.at[103, "score"], df.iat[2, 1]) # one value by label, then by position
Ben
Ben
[101, 102, 103]
[101, 102, 103]
Di
['Ada', 'Cy']
[91, 78, 85, 62]
85 85
The two slices return the same three rows by different routes: .loc[101:103] stops at label 103 and includes it, while .iloc[0:3] stops before position 3. Filtering with a condition is a loc job, because the mask df["score"] > 80 carries the table's labels. iloc[-1] is the usual way to get the last row, since negative positions count from the end.
The iloc vs loc mistake after sorting
Sorting moves rows but keeps their labels. With the default index, that is where loc and iloc stop agreeing:
import pandas as pd
scores = pd.DataFrame({"score": [62, 91, 78]}) # default index: 0, 1, 2
ranked = scores.sort_values("score", ascending=False)
print(ranked.index.tolist())
print(ranked.loc[0, "score"]) # the row labelled 0, wherever it now sits
print(ranked.iloc[0, 0]) # the first row after sorting
[1, 2, 0]
62
91
ranked.loc[0] still finds the record that was first before sorting (62). ranked.iloc[0] finds the top score now (91). Use iloc when you mean "whatever is in this position now" and loc when you mean "this particular record". Filtering has the same effect, leaving gaps in the labels. If you want labels to match positions again, reset_index(drop=True) renumbers them.
A worked example: labels, alignment and safe assignment
Our invented inspection table uses the labels 10, 20 and 40. We will filter rows, assign a corrected value and expose how label alignment affects a second assignment.
A label slice through a suitable ordered index includes its final label. A positional slice follows Python's usual stop-exclusive rule. Thus .loc[10:20] contains labels 10 and 20, while .iloc[0:1] contains only the first row.
A Boolean Series supplied to loc is aligned by labels. iloc was built for positions: pandas 2.x raises an error when you pass it a Boolean Series, and pandas 3.0 added support for Boolean masks in iloc. For a mask built from the same table, loc works the same in every recent version, so prefer it. Do not discard the index just to silence an alignment error unless position really is what you mean.
The program uses a simple one-step loc assignment. It avoids chained selection such as frame[mask]['score'] = value, which never updates frame under the Copy-on-Write behavior that is standard from pandas 3.0.
import pandas as pd
frame = pd.DataFrame({'part': ['gear', 'bolt', 'shaft'], 'score': [8., 5., 9.]},
index=[10, 20, 40])
print('loc label 20:', frame.loc[20, 'part'])
print('iloc position 2:', frame.iloc[2, 0])
print('loc slice:', frame.loc[10:20].index.tolist())
print('iloc slice:', frame.iloc[0:1].index.tolist())
mask = frame['score'] < 6
frame.loc[mask, 'score'] = 6.
print('corrected scores:', frame['score'].tolist())
try:
frame.loc[1]
except KeyError:
print('label 1: missing')
values = pd.Series([100., 200.], index=[40, 10])
frame.loc[[10, 40], 'score'] = values
print('aligned assignment:', frame['score'].tolist())
assert frame.loc[10, 'score'] == 200
assert frame.loc[40, 'score'] == 100
assert frame.index.is_unique
Checked output:
loc label 20: bolt
iloc position 2: shaft
loc slice: [10, 20]
iloc slice: [10]
corrected scores: [8.0, 6.0, 9.0]
label 1: missing
aligned assignment: [200.0, 6.0, 100.0]
Inspect alignment during assignment
The Series stores 100 under label 40 and 200 under label 10. Assigning it through loc[[10, 40], 'score'] aligns by those labels, producing 200 at row 10 and 100 at row 40. The order in which values appear in the Series is not the assignment order.
If you intentionally want positional assignment, use a positional selection and an array with a checked shape. Converting a Series to an array removes its labels; that can be correct, but it also removes a useful protection against accidentally mismatched records. State why the labels should be ignored.
Our fixture has a unique index. With duplicate labels, a scalar loc key can select multiple rows and may return a different result shape. Check index.is_unique if your program depends on one label identifying exactly one record. Resetting an index is an explicit data-model change, not a universal fix for duplicate observations.
Separate filtering from cleaning
A mask such as score < 6 encodes a rule. In this example the assignment is a demonstrative correction, not a recommendation to overwrite low inspection scores. Real cleaning should preserve the source measurement, record the reason for a correction and avoid manufacturing model targets.
Missing mask values and nullable data types deserve separate tests. Do not assume the same behavior for a NumPy Boolean array, a pandas nullable Boolean Series and a Python list without checking the selection API.
Extend the fixture
Reorder the rows and predict which iloc selection changes while .loc[20] still identifies the bolt. Then add a duplicate label 20 and inspect the returned object. Finally, give the assignment Series an unrelated label and explain the resulting missing value before deciding how to reject the mismatch.
The Data Tools track develops table indexing and cleaning, and the free pandas cheat sheet puts loc, iloc and the other everyday selections on one page. Continue with aggregation versus transform to see why preserving row alignment matters when adding group-derived features. Check merge relationships before combining independently indexed tables, and practise all of it in pandas projects for beginners.
Common questions about loc and iloc
What does iloc stand for?
Integer location. The pandas documentation describes iloc as "purely integer-location based indexing for selection by position". loc, by contrast, works by label.
When should I use loc vs iloc?
Use loc when you know the label or want to filter by a condition, and iloc when position is the point: the first five rows, the last row, every tenth row. In data-cleaning code loc is usually the safer choice, because a label stays with its record when rows are sorted or filtered.
Is loc or iloc faster?
Choose by meaning rather than speed. For a single value, the pandas documentation recommends at and iat as the fastest way to get or set a scalar.
Can iloc use column names?
No. df.iloc[0, "name"] raises a ValueError. To mix a position with a name, convert one into the other: df.loc[df.index[0], "name"] or df.iloc[0, df.columns.get_loc("name")].
Why does a loc slice include its end?
Labels are often dates or names, and there is no obvious "label after the last one" to stop before. So pandas includes the end label you name, while iloc keeps Python's usual rule of stopping before the end position.
Selecting rows by label or position comes up often in interviews. Practise it alongside grouping, merging and missing values with the pandas interview questions.
References
pandas indexing guide — Label and positional selection, endpoint rules, Boolean indexing and assignment.
DataFrame.iloc reference — The inputs iloc accepts.