loc[]
loc selects rows and columns by their labels.
In this page:
Syntax
df.loc[row_labels, column_labels]
df.loc["row1":"row3", ["column1", "column2"]]
loc[]
df.loc[row_labels, column_labels] uses labels and includes the end of a slice. It accepts single labels, lists, slices and boolean masks. It is also the right way to assign values to a selection.
Note:
df.loc[mask, "col"] = value is the safe way to update filtered rows.
Example: loc[]
import pandas as pd
df = pd.DataFrame({"age": [28, 35, 41], "city": ["Oslo", "Rome", "Lima"]}, index=["ann", "bob", "cy"])
print(df.loc["bob"])
print(df.loc["ann":"bob", "city"])
df.loc[df["age"] > 30, "city"] = "Moved"
print(df)
# Output:
# age 35
# city Rome
# Name: bob, dtype: object
# ann Oslo
# bob Rome
# Name: city, dtype: object
# age city
# ann 28 Oslo
# bob 35 Moved
# cy 41 Moved
Related Topics
Common Mistakes
- Using positions instead of labels
- Chained indexing like df[mask]["col"] = 1
- Expecting slice ends to be excluded
Chapter Summary
- loc is label-based
- Slices include the end
- Accepts masks and lists
- Use loc for safe assignment
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: