loc[] is label-based indexing: selecting a single row label returns that row, selecting a column name returns that column, and slicing between two labels selects every row from the first label through the second, inclusive of both endpoints — unlike Python's normal slicing, and unlike iloc, where the end of a slice is always exclusive. loc[] also accepts a boolean array/condition for the row selector, making it the standard way to combine label-based and condition-based selection in a single call.
1Understanding df.loc[]
loc[] is label-based indexing: selecting a single row label returns that row, selecting a column name returns that column, and slicing between two labels selects every row from the first label through the second, inclusive of both endpoints — unlike Python's normal slicing, and unlike iloc, where the end of a slice is always exclusive. loc[] also accepts a boolean array/condition for the row selector, making it the standard way to combine label-based and condition-based selection in a single call.
loc[]'s label-based slicing includes both endpoints, unlike Python's normal slice syntax and unlike iloc's position-based slicing, which both exclude the endpoint — a frequent source of off-by-one confusion.
import pandas as pd
df = pd.DataFrame({"name": ["Alice", "Bob", "Carol"], "age": [30, 25, 35]}, index=["a", "b", "c"])
print(df.loc["b"])2Practical Example
Here is a real-world application of df.loc[] showing how it is used in production Pandas code.
import pandas as pd
df = pd.DataFrame({"name": ["Alice", "Bob", "Carol"], "age": [30, 25, 35]})
print(df.loc[df["age"] > 28, "name"])3Best Practices
Follow these guidelines when working with df.loc[]:
1. Use loc[] whenever you're selecting by meaningful labels, names, dates, IDs, rather than raw position
2. Remember loc[]'s slice endpoint is inclusive, unlike iloc[] and plain Python slicing, to avoid an off-by-one surprise
3. Combine loc[] with a boolean condition for the row selector to filter rows and select specific columns in one call
Tip: loc[]'s label-based slicing includes both endpoints, unlike Python's normal slice syntax and unlike iloc's position-based slicing, which both exclude the endpoint — a frequent source of off-by-one confusion.
import pandas as pd
df = pd.DataFrame({"name": ["Alice", "Bob", "Carol"], "age": [30, 25, 35]}, index=["a", "b", "c"])
print(df.loc["b"])