Select, filter, sort, and assign

3.1.1

Use label-based and position-based selection, and update a DataFrame with Copy-on-Write in mind.

On this page

Select with loc and iloc

loc selects by label and can apply a Boolean mask. A label slice includes both bounds when present. iloc selects by integer position and uses the usual exclusive stop for slices.

import pandas as pd

frame = pd.DataFrame({"item": ["Tea", "Cake", "Coffee"], "sales": [8, 15, 12]})
selected = frame.loc[frame["sales"].ge(10)].sort_values("sales", ascending=False)
print(selected["item"].tolist())
Example output
['Cake', 'Coffee']

Assign with one loc operation

pandas 3.x uses Copy-on-Write. Chained assignment cannot update the original DataFrame. To update the original, select the matching rows and target column together inside a single loc assignment.

import pandas as pd

frame = pd.DataFrame({"item": ["Tea", "Cake"], "sales": [8, 15]})
frame.loc[frame["item"].eq("Tea"), "sales"] = 10
print(frame["sales"].tolist())
Example output
[10, 15]

Official references