← Back to Pandas Course | Chapter 4: Indexing & Selection | Lesson 1 of 7

loc[]

loc selects rows and columns by their labels.

In this page:

  1. loc[]
Syntax
python
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[]

python
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
  1. Using positions instead of labels
  2. Chained indexing like df[mask]["col"] = 1
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.