Filtering and indexing
Quick answer
Use loc for selection by labels and iloc for selection by integer positions. Boolean masks select rows satisfying a condition. pandas aligns a Boolean Series by index labels when used with loc. A mask should refer to the same table and missing Boolean values need an explicit policy. Examples run locally on Python 3.13.5 and pandas 2.2.3; ByteMind package support is not verified. All data are synthetic.
Select with labels, positions and conditions
The index values are not row positions. loc label slices include the stop label when present; iloc slices exclude the stop position.
import pandas as pdx = pd.DataFrame({'temp': [19, 24, 26], 'ok': [True, False, True]}, index=[10, 20, 30])print(x.loc[10:20, 'temp'].tolist())print(x.iloc[0:2, 0].tolist())print(x.loc[(x['temp'] >= 20) & x['ok']].index.tolist())Expected output (pandas 2.2.3):
[19, 24][19, 24][30]Both slices happen to select the first two rows. The mask selects only row 30 because both conditions must hold. Use parentheses and & rather than Python and for elementwise conditions.
Update an independent subset
An explicit copy plus a single loc assignment expresses intent without relying on view behavior. Set Copy-on-Write explicitly for this local example.
import pandas as pdpd.options.mode.copy_on_write = Truex = pd.DataFrame({'temp': [19, 24, 26]})subset = x.loc[x['temp'] >= 24].copy()subset.loc[:, 'temp'] = 0print(subset['temp'].tolist())print(x['temp'].tolist())Expected output (pandas 2.2.3):
[0, 0][19, 24, 26]The subset changes without changing the original. pandas 2.2 supports opt-in Copy-on-Write; do not assume all versions have the same default. For scalar numeric cells this explicit copy is sufficient; nested mutable Python objects are a different case.
Common mistakes
Avoid chained assignment such as x[mask]["temp"] = 0. It does not reliably update x and cannot update the original under Copy-on-Write. Use x.loc[mask, "temp"] = 0 when you intend to update x. For a nullable mask, choose fillna(False) only if excluding unknown rows is justified.
Practice and next steps
Select two readings by their labels, then by their positions. Copy the result, change it and confirm the source stays unchanged. Try the pure-Python reasoning challenge and knowledge check separately; these do not assess pandas API execution.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Filtering and indexing — knowledge check
Apply tabular data reasoning to new synthetic fixtures.
For index [10,20,30], what does iloc[1] select?
What does loc[10:20] select with index [10,20,30]?
Which expression selects temperature >= 20 and valid rows?
How should you modify the original table for a mask?
What is the purpose of copying a numeric subset?